我有一个与 API 通信的无数据库 Rails 应用程序。
对于身份验证,我将用户凭据发送到 api 并在成功时接收会话令牌。随后,我发出的每个 api 请求都应包含该令牌。
api_request.rb:
class ApiRequest
def initialize(relative_path,params={})
params = _add_base_data params
send_request relative_path, params
end
private
def send_request(relative_path,params)
conn = Faraday.new(:url => MyApp::Application.config.server) do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
encoded = conn.post relative_path,params
@data = JSON.parse encoded.body
@data
end
def _add_base_data params
params[:session_token] = ?
params
end
end
my_session.rb:
class MySession
def login? email,pass
params = { :email => email, :password => pass }
resp = ApiRequest.new '/user/login', params
if resp.failed?
false
else
@session[:token] = resp.data['session_token']
true
end
end
end
如何使会话令牌可用于每次调用的 ApiRequest 模型?