简体   繁体   English

rails设计挂钩到on_login

[英]rails devise hook into on_login

I'm looking to hook into devise after login / after session create. 我想在登录/会话创建后挂钩设计。 How would I go about doing this? 我该怎么做呢?

Basically I want to set a users location every time they login, and to do that I need an after login hook of sorts. 基本上我想在每次登录时设置用户位置,为此我需要一个登录后的挂钩。

Devise is built on Warden, so you can use Warden's after_authentication hook. Devise建立在Warden之上,所以你可以使用Warden的after_authentication钩子。

Put this in an initializer: 把它放在初始化器中:

Warden::Manager.after_authentication do |user,auth,opts|
  # do something with user
end

The remote IP address and other request info is stored in auth.request (ie auth.request.remote_ip). 远程IP地址和其他请求信息存储在auth.request(即auth.request.remote_ip)中。

See https://github.com/hassox/warden/wiki/callbacks 请参阅https://github.com/hassox/warden/wiki/callbacks

Devise updates the value of the user.current_sign_in_at timestamp on successful login. 设计成功登录时,设计会更新user.current_sign_in_at时间戳的值。 So, you could simply add a before_save filter to your User model. 因此,您只需向用户模型添加before_save过滤器即可。 In that filter, check to see if the value of this field has changed, and if it has, set the users location. 在该过滤器中,检查此字段的值是否已更改,如果已更改,请设置用户位置。

BTW - I'm not sure what you mean by "location" - if you mean IP address, Devise already stores that for you. 顺便说一句 - 我不确定你所说的“位置”是什么意思 - 如果你的意思是IP地址,Devise已经为你存储了。

Here's a page from the devise wiki: How To: Redirect to a specific page on successful sign in . 以下是设计维基的页面:操作方法:成功登录后重定向到特定页面

In summary, the recommendation is to add the following method to the application controller: 总之,建议将以下方法添加到应用程序控制器:

app/controllers/application_controller.rb 应用程序/控制器/ application_controller.rb

def after_sign_in_path_for(resource)
    custom_location_for(resource) || welcome_path
end

In the above code, resource means the object (user, account, etc) that you've implemented devise authentication for. 在上面的代码中, resource表示您已实现的对象(用户,帐户等)设置身份验证。 (The object that has the devise_for in your routes.) (在路由中具有devise_for的对象。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM