vfi*_*lby 21 ruby devise ruby-on-rails-3
我有一个具有基本Devise身份验证的应用程序.登录后,我想查找用户帐户(用户belongs_to帐户,帐户has_many用户),并将其存储在会话中,以便它可用@current_user.
这样存储会话的轨道方式是什么?在成功登录后,我可以使用Devise来执行代码吗?
Mat*_*Fiz 33
实际上,如果在Devise中组合了Omniauth和Database登录模块,则接受的答案将无法正常工作.
在Devise中每次成功登录操作后执行的本机挂钩(忽略用户身份验证通道)是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
Run Code Online (Sandbox Code Playgroud)
更新2015-04-30:感谢@seanlinsley的建议(请参阅下面的评论),我已经更正了包括以下内容的答案::fetch以便仅在用户通过身份验证时才触发回调,而不是每次设置时都触发回调.
更新2018-12-27感谢@thesecretmaster指出Warden现在已经内置了回调函数, 用于在after_authentication上执行您自己的代码https://github.com/wardencommunity/warden/wiki/Callbacks#after_authentication
Ant*_*zzo 18
编辑:请考虑这曾经是一个很好的解决方案,但可能有更好的方法来处理这个问题.我只是留在这里为人们提供另一种选择并保存历史,请不要贬低.
是的,你可以这样做.我要看的第一个资源是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
Run Code Online (Sandbox Code Playgroud)
您可以在ApplicationController或自定义RegistrationsController中实现此方法.
我正在使用rails 5并设计4.2.1,我的解决方案是在用户模型上的over over devise功能:
def after_database_authentication
# here's the custom code
end
Run Code Online (Sandbox Code Playgroud)
用户模型将如下所示:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:timeoutable, :lockable
def after_database_authentication
# here's the custom code
end
end
Run Code Online (Sandbox Code Playgroud)
在认证之后调用它,我从这个设计文档中读取它,希望这可以帮助
我通过覆盖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
Run Code Online (Sandbox Code Playgroud)
换句话说,如果身份验证成功(通过调用super),那么我将执行我的设置。
| 归档时间: |
|
| 查看次数: |
20822 次 |
| 最近记录: |