我按照教程设置了authentication_token以与Devise一起使用,因此用户可以通过API登录/注销。该会话控制器应该覆盖Devise。
sessions_controller.rb
def destroy
respond_to do |format|
format.html {
super
}
format.json {
user = User.find_by_authentication_token(request.headers['X-API-TOKEN'])
if user
user.reset_authentication_token!
render :json => { :message => 'Session deleted.' }, :success => true, :status => 204
else
render :json => { :message => 'Invalid token.' }, :status => 404
end
}
end
end
user.rb模型
def generate_secure_token_string
SecureRandom.urlsafe_base64(25).tr('lIO0', 'sxyz')
end
def generate_authentication_token
loop do
token = generate_secure_token_string
break token unless User.where(authentication_token: token).first
end
end
def reset_authentication_token!
self.authentication_token = generate_authentication_token
end
def ensure_authentication_token!
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end
如果该字段为空(它适用于所有现有用户),则会成功生成令牌,但是当用户登录/注销时,令牌只保持静态。这似乎打败了目的。
知道为什么会这样吗?