【发布时间】:2016-02-15 14:55:32
【问题描述】:
我有一个 Rails 3.2.22 应用程序在生产中运行了 +1 年,它使用 Devise 来验证用户身份。
我正在尝试实现令牌身份验证,因此我可以使用名为 Simple Token Authentication https://github.com/gonzalo-bulnes/simple_token_authentication 的 Gem 发送带有 URL 参数的交易电子邮件,这些参数可以自动登录用户。
按照所有说明操作后,我将控制器中的 before_filter :authenticate_user! 替换为 acts_as_token_authentication_handler_for User。
gem 与 Devise 集成并具有 default 后备功能,因此不再需要在控制器中调用 devise;如果参数中缺少令牌(或错误),Devise 将接管。
在我的测试中,如果我将此行添加到 ApplicationController,一切正常,我可以使用 gem 生成的 authentication_token= 密码登录用户。
但我不需要 auth 用于 ApplicationController,我需要它用于其他控制器(如 DashboardController),网址为 /dashboard
如果我将 acts_as_token_authentication_handler_for User 放入该控制器(替换 Devise 的调用),我会遇到最奇怪的情况。
使用 binding.pry,我可以确认在加载模板期间正确设置了 current_user。
但是模板中有一点使用@last_emails,它在ApplicationController 的方法中定义。
使用 binding.pry,我可以确认 current_user 在那里 nil。
这是代码:
class DashboardController < ApplicationController
layout 'material'
acts_as_token_authentication_handler_for User
在 ApplicationController 中:
class ApplicationController < ActionController::Base
layout 'omega'
before_filter :populate_last_contacts_for_menu
private
def populate_last_contacts_for_menu
if current_user
@last_contacts = Contact.where("user_id" => current_user.id).where('blocked != ? or blocked is null', true).last(10).reverse
end
end
有趣的是:使用 binding.pry,就像我说的那样,我可以检查模板中是否定义了 current_user(这意味着 sign_in 是成功的)。它甚至在更好的错误控制台中定义。但是,如果我去主页,我看到该用户没有登录...
我已经在整个网络上查看了这一点:阅读 Gem 的 github 中的所有问题以及 SO 中关于 current_user 为 nil 的所有帖子,但一点也不亮。
我的devise_for :users 不在 routes.rb 的任何范围内,正如我所说,我在整个应用程序中多次调用 current_user,这是我第一次遇到 Devise 问题。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 authentication devise