我目前使用令牌身份验证设置了API。我有一个父类ApiController
,我的其他API控制器继承了它包含以下内容:
class ApiController < ApplicationController
protect_from_forgery with: :null_session
protected
def authenticate
authenticate_token || render_unauthorized
end
def authenticate_token
authenticate_with_http_token do |token, options|
User.find_by(auth_token: token)
end
end
def render_unauthorized
self.headers['WWW-Authenticate'] = 'Token realm="Users"'
render json: 'Bad credentials', status: 401
end
end
在我的API控制器中,我只需设置before_action :authenticate
即可确保来自具有auth_token
的用户的有效请求。
我有时需要发出请求的用户,例如,当关注用户时,我需要让提出请求的用户跟随另一个用户,看看我有什么我可以如何在我的控制器中进行设置可以访问发出请求的用户吗?
答案 0 :(得分:1)
您可以在authenticate_token
方法中设置控制器可以访问的实例变量。就这样
@current_user = User.find_by(auth_token: token)
然后,例如,您定义为&#34;的Controller :: Action跟随&#34;用户可以使用@current_user
。
def follow()
@current_user.follow (another_user)
end