How do I create a link that automatically logs a user into dev / rails?

I'm trying to get registered users to take some action on my website, so I want to email a link directly to that action.

The problem is that I want you to be auto-registered when you click on this link.

I can do something obvious like create a unique token and pass it through the url mysite.com/my_funky_action?login_bypass_token=af123fa127ba32, but that seems to me to be a problem "solved many times before"

So, is there an easy way to do this using rails / devise? I have searched for documentation with no success.

+3


source to share


2 answers


Using the code from the restore method as a basis, I did this

Model:

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:

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

      

email template (in haml)

= link_to 'View this awesome page without login!', awesomeness_url(:login_bypass_token => @login_bypass_token)

      

+1


source


This is generally not good.

If you are not using a token, this means that you will need to create a path that explicitly includes the email address, eg.

http://my_app.com/special_action?email=john@sample.com



Considering that anyone will be able to log in as any logged in user simply by submitting a URL structured like above, replacing whatever they want.

Go to the token, make sure it expires on use, or after the shortest time you can leave.

0


source







All Articles