pyfl88 pyfl88 - 5 months ago 17
Ruby Question

How do I generate a temporary page like confirmation page in rails?

I am using devise and want to redirect users to a confirmation page upon signup, this is what I am doing right now:

users/registrations_controller.html.erb

class Users::RegistrationsController < Devise::RegistrationsController

def confirm_email
end

private

def after_inactive_sign_up_path_for(resource)
users_confirmyouremail_path
end
end


config/routes.rb

devise_scope :user do
get 'users/confirmyouremail' => 'users/registrations#confirm_email'
end


I have no problem with redirecting the page after signup. However, I think it is quite weird that anyone can visit the page with url like `host.com/confirmyouremail' and see the confirmation page. Are there any ways I can write a route that will use random code that is allow only for one time visit? Thanks in advance.

Answer

Maybe something like this:

before_action :authenticate_user!

def confirm_mail
    redirect_to root_path if current_user.confirmed
...
end

You are storing in the database if the user has already confirmed his account. If his account is confirmed then he won't be able to access this page. You can redirect to whatever page you want. A user without any account won't be able to access this page because of the before action

In case the user is not logged in when he accesses this confirm_mail page you have different possibilities. You could use a session or a cookie:

# after sign up:
session[:confirm] = true
# alternatively a cookie
cookies[:confirm] = true

Then in the confirm mail action:

def confirm_mail
  if session[:confirm].blank? # or cookies[:confirm].blank?
    redirect_to root_path
  end

  # otherwise delete the field from the session
  session.delete(:confirm)
  # alternatively the cookie
  cookies.delete(:confirm)
end

Another way would be by using a Token. You create a new model like ConfirmMailToken. Then on sign up you create a new token and redirect the user to the confirm page with the token as a URL param. Then in the confirm_mail action you check if a token is available and delete it if it is. This way you ensure that the page is only shown after redirect.