我花了一些时间试图了解如何绕过我的登录来创建远程重复到 json 的记录,而不会失去登录提供的安全性。我设法用 HTTParty 做到了这一点,但我想 rest-client 也会这样做。
我现在分享我的解决方案,但我仍然认为可能有更好、更安全的方法来做到这一点,并想听听您对此的看法。
所以,第一件事。这是我的控制器:
things_controller.rb
...
before_filter :signed_in_user, only: [:show, :destroy]
before_filter :signed_in_user, only: [:create], unless: :is_it_json?
...
def create
if is_it_json?
user = User.find_by_email(params[:session][:email].downcase)
if !(user && user.authenticate(params[:session][:password]))
format.json { render json: @user.errors, status: :unprocessable_entity }
else
@thing = user.things.build(params[:thing])
end
else
@thing = current_user.things.build(params[:thing])
end
respond_to do |format|
if @thing.save
format.html { redirect_to root_path, :flash => { :success => 'thing was successfully created.'} }
format.json { render json: @thing, status: :created, location: @thing}
else
@feed_items = []
format.html { render action: "static_pages/home" }
format.json { render json: @thing.errors, status: :unprocessable_entity }
end
end
end
application_controller.rb
...
def is_it_json?
request.format.json?
end
...
我的红宝石脚本:wsConsumption_httparty.rb
require 'HTTParty'
def ask(prompt)
print prompt, ' '
$stdout.flush
s = gets.chomp
end
class thingCreate
include HTTParty
base_uri 'localhost:3000'
format :json
headers "Accept" => "application/json"
def initialize
end
def post(description, weight,typeid,email,password)
options = { body:
{thing:
{description:description,
weight:weight,
type_id:typeid
},
session:
{email:email,
password:password
}
}
}
self.class.post('/things', options)
end
end
username = ask("What is the user email?")
password = ask("What's the password?")
description = ask("thing description: ")
weight = ask("Weight: ")
typeid = ask("Type Id: ")
thing = thingCreate.new()
print thing.post(description, weight,typeid,username,password)
这非常适合创建...我想听听您的意见:
- 这种创建事物的机制如何更安全(使用https就足够了?
- 我应该对服务应用某种故障保护机制吗?有什么建议么?
- 如果插入了错误的用户/密码,我想返回一条短信,只说“无效的用户名/密码”......关于我如何实现这一点的任何想法?
- 您可能有任何其他建议。
干杯