signin user upon clicking the link in email automa

2019-06-12 21:33发布

问题:

I have a User model in my rails application. which is a "devise" model. i have one form called "user-info" form this form can be available once the user logs into the system.

i have one admin login in which an admin can send the link to the user email like fill the "user info" by clicking a button. once the user clicks the button i want the user to login into the system automatically without redirecting to the login page. and should be navigated to the user-info form.

i have an idea of sending query string parameters in the url like email = "x@gmail.com "&& form = "user_info". but once the user clicks on this what needs to be implemented to achieve my requirement.

回答1:

My understanding is that you can use the tokens to log in or to hit arbitrary pages that need authentication, even with cURL. If you look in config/initializers/devise.rb, there should be a line that says something like:

config.token_authentication_key = :auth_token

Whatever the name of the token_authentication_key is should match what you put as the query or form parameter in your request. You used authentication_token in your example, not sure if you changed devise.rb to match that or not.

If you want to figure out how things are working internally, I would try git clone git://github.com/plataformatec/devise.git and search for the methods you need clarification of.

Here are some sample cURL requests (I made a custom Users::SessionsController that extends Devise::SessionsController and overrides the create method to handle JSON.)

class Users::SessionsController < Devise::SessionsController
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)

    respond_to do |format|
      format.html do
        respond_with resource, :location => redirect_location(resource_name, resource)
      end
      format.json do
        render :json => { :response => 'ok', :auth_token => current_user.authentication_token }.to_json, :status => :ok
      end
    end
  end
end 

And then the cURL requests I gave:

curl -X POST 'http://localhost:3000/users/sign_in.json' -d 'user[email]=example@example.com&user[password]=password'
-> {"response":"ok","auth_token":"ABCDE0123456789"}

curl -L 'http://localhost:3000/profile?auth_token=ABCDE0123456789'
-> got page that I wanted that needs authentication


回答2:

You can use this Simple Token Authentication gem, it is well known to generate the authentication token and to be sent by email to the users you would like to have this authentication. please follow the setup instruction.