如何创建一个链接,使用户自动登录到devise / rails? [英] How to create a link that automatically logs the user in on devise / rails?
问题描述
我正试图让注册用户在我的网站上执行某些操作,所以我想通过电子邮件向他们发送直接指向此操作的链接。
I'm trying to make signed up users to take some actions on my website, so I want to send them, by e-mail, a link directly to this action.
问题是我希望他们在单击此链接时能够自动登录。
The problem is that I want them to be automatically logged in when clicking on this link.
我可以做一些明显的事情,例如创建一个唯一的令牌并传递它通过URL mysite.com/my_funky_action?login_bypass_token=af123fa127ba32
,但是在我看来这是一个之前已解决很多次的问题。
I can do something obvious as creating an unique token and pass it through the url mysite.com/my_funky_action?login_bypass_token=af123fa127ba32
but this seems to me as a problem "solved many times before"
那么,有一个简单的方法可以使用rails / devise来做到这一点吗?我搜索了devise文档,但没有成功。
So, there is a simple way out there to do this using rails / devise? I've searched on devise documentation without success.
推荐答案
使用devise可恢复代码作为基础,我做到了
Using as basis the code from devise's recoverable, I did this
模型:
class User < ActiveRecord::Base
def set_login_bypass_token
raw, enc = Devise.token_generator.generate(User, :login_bypass_token)
self.login_bypass_token = enc
self.login_bypass_token_set_at = Time.now.utc
self.save(validate: false)
raw
end
def self.by_bypass_token(token)
original_token = Devise.token_generator.digest(self, :login_bypass_token, token)
User.find_by(:login_bypass_token => original_token)
end
end
mailer:
class SomeMailer < ActionMailer::Base
def send_something
...
@login_bypass_token = @user.set_login_bypass_token
...
end
end
application_controller:
application_controller:
class ApplicationController < ActionController::Base
layout :application_layout
protect_from_forgery with: :exception
before_action :bypass_login
before_action :authenticate_user!
private
def bypass_login
if params[:login_bypass_token]
user = User.by_bypass_token(params[:login_bypass_token])
sign_in(user, :bypass => true) if user
redirect_to request.path
end
end
end
电子邮件模板(以haml结尾)
email template (in haml)
= link_to 'View this awesome page without login!', awesomeness_url(login_bypass_token: @login_bypass_token)
这篇关于如何创建一个链接,使用户自动登录到devise / rails?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!