成功使用Devise登录后,我可以执行自定义操作吗?

我有一个具有基本Devise身份validation的应用程序。 登录后,我想查找用户帐户(用户belongs_to帐户,帐户has_many用户),并将其存储在会话中,以便像@current_user一样@current_user

这样存储会话的轨道方式是什么? 在成功登录后,我可以使用Devise来执行代码吗?

编辑 :请考虑这曾经是一个很好的解决方案,但可能有更好的方法来处理这个问题。 我只是留在这里为人们提供另一种选择并保存历史,请不要贬低。

是的,你可以这样做。 我要看的第一个资源是http://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in 。 另外,请查看如何使用rails devise gem成功注册时如何重定向到特定页面? 一些想法。

你可以这样做:

 def after_sign_in_path_for(resource_or_scope) session[:my_account] = current_user.account profile_url end 

您可以在ApplicationController或自定义RegistrationsController中实现此方法。

实际上,如果在Devise中组合了Omniauth和Database登录模块,则接受的答案将无法正常工作。

在Devise中每次成功登录操作后执行的本机挂钩(忽略用户身份validation通道)是warden.set_user(由devise sign_in帮助程序调用: http : //www.rubydoc.info/github/plataformatec/devise/Devise/ Controllers / SignInOut#sign_in-instance_method )。

为了在成功用户登录后执行自定义操作(根据Warden Docs: https : //github.com/hassox/warden/wiki/Callbacks ),将其放入初始化程序(例如, config / initializers中的 after_sign_in.rb

 Warden::Manager.after_set_user except: :fetch do |user, auth, opts| #your custom code end 

更新2015-04-30 :感谢@seanlinsley建议(请参阅下面的评论),我已经更正了包括以下内容的答案::fetch以便仅在用户通过身份validation时触发回调,而不是每次设置时都触发​​回调。

我正在使用rails 5并设计4.2.1,我的解决方案是在用户模型上的over over devisefunction:

 def after_database_authentication # here's the custom code end 

用户模型将如下所示:

 class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :timeoutable, :lockable def after_database_authentication # here's the custom code end end 

它是在认证之后调用的,我从这个设计文档中读取它,希望这可以帮助

我通过覆盖会话控制器的create方法解决了这个问题,如下所示

 class Admin::SessionsController < Devise::SessionsController def create super # here goes my code # my settings, etc # do something with current_admin.fullname, for example end end 

换句话说,如果validation成功(通过调用super ),那么我执行我的设置。