How to redirect to login page/ or making user login successful after confirm email in devise token auth

960 Views Asked by At

I am using devise token auth with React frontend and now I am making user confirmable through email. Email is being sent but somehow it generates a wrong URL.

The URL that is generated is.

http://localhost:3001/auth/confirmation.4?confirmation_token=AoWH2yYxuHHnBzJRF746

My routes.

new_user_confirmation GET      /auth/confirmation/new(.:format)                                                         users/confirmations#new
                    user_confirmation GET      /auth/confirmation(.:format)                                                             users/confirmations#show
                                      POST     /auth/confirmation(.:format)                                                             users/confirmations#create

My app/views/devise/mailer/confirmation_instructions.html.erb

<p>Welcome <%= @email %>!</p>

<p>You can confirm your account email through the link below:</p>

<p><%= link_to 'Confirm my account', user_confirmation_url(confirmation_token: @token) %></p>

After clicking confirm my account, it takes me to my application successfully, but with the wrong URL. I will be happy if I achieve one of the following.

  1. User is automatically logged in after confirming.
  2. It goes to login page after confirm account and after that he gives thee credentials and login.

For 1, I have overridden the confirmations_controller.rb like.

# frozen_string_literal: true

class Users::ConfirmationsController < Devise::ConfirmationsController
  # The path used after confirmation.
   def after_confirmation_path_for(resource_name, resource)
     sign_in(resource) # In case you want to sign in the user
     root_path
   end
end

In routes.rb

mount_devise_token_auth_for 'User', at: 'auth', controllers: { confirmations: 'users/confirmations' }
1

There are 1 best solutions below

6
Clara On

First, the url helper that you use in the email doesn't need to receive the @resource - this is why it generates the url with the .4. It should rather be

<p><%= link_to 'Confirm my account', user_confirmation_url(confirmation_token: @token) %></p

Second, according to this tutorial, you can redirect the user after confirmation, like you tried already. https://github.com/heartcombo/devise/wiki/How-To:-Add-:confirmable-to-Users#redirecting-user

Just give a path in your app after you signed in the user

def after_confirmation_path_for(resource_name, resource)
  sign_in(resource) # In case you want to sign in the user
  your_new_after_confirmation_path
end

So no need to go to session_new again after signing in.