How to add email confirmation while sign-up using devise in ruby on rails

in #utopian-io6 years ago

Repository

Rails Demo Porject

What Will I Learn?

  • You will learn how to add confirmation email in ruby on rails app while sign-up using devise
  • You will learn how to add the column in users table to store the user confirmation email details
  • You will learn how to show an error message on view if the user had not confirmed their email and tried to sign in to the app

Requirements

  • OS: Ubuntu/Mac OS
  • A text editor like sublime
  • Basic understanding of Ruby on Rails

Difficulty

  • Intermediate

Tutorial Contents

Hello and welcome to the tutorial.
Sometimes when we build a web app, we have to take care of fake signup's. In that case, we have to use an email confirmation while sign-up, so that only genuine sign up will be created on the app. So let's start to add confirmation email into the project with the help of devise gem in rails

NOTE: Please follow my previous tutorials, so that you can better understand about the project, link added in the curriculum.

Open the project in the terminal and the text editor (sublime).

First of all, we need confirmation details columns in the user table to store the email confirmation data, for that we need to add migration file. Open the terminal and copy the following code into that.

rails g migration add_confirmable_to_users
It will add a migration file under app > db > migrate folder with the same name i.e timestamp_add_confirmable_to_users.
Migration file are used to add/remove/change column or create new table in the database in ruby on rails.

Next, we have to add the column names like as shown below

def change
 add_column :users, :confirmation_token, :string
 add_column :users, :confirmed_at, :datetime
 add_column :users, :confirmation_sent_at, :datetime
 add_index :users, :confirmation_token, unique: true
end

The above code is explained below:

  • The first one add's a 'confirmation_token' column that is a string type. This token sent to the user in the email so that we can compare the token while confirming the user.
  • Next one is 'confirmed_at' is a datetime type, which store when user confirmed the email.
  • Next is 'confirmation_sent_at' is also a datetime type, which stores the information when confirmation email sent to the user.
  • Next is the indexing of 'confirmation_token' and it should be unique.
  • Next step is to run migrate command as shown below:
rake db:migrate
Above command will add the new column in the user table.
*You can see the highlighted part of the image showing that new fields are added to the database.

Now go to user model and add the following code

devise :confirmable
You just need to add confirmable and please do not make any changes.
Devise has the predefined method for confirmation but we have to enable that option. If we add the confirmation option and then generate the views, our app will ready to send the confirmation emails. But we have to also configure our app to send emails. I am already creating a tutorial how to configure our app to send email, please refer that tutorial also for more guidance.
  • Now generate the devise views by the following command
rails generate devise:views users
If you have already generated it, then it will prompt you that it is already generated and ask for overwriting, so please tap 'N' and entered. Now devise views with confirmation is created.

Now the main part is coming here, we have successfully configured but if the already existing user tried to sign in into the app, the app will won't allow it because devise first checks if the user confirmed_at is confirmed or not. But we have to add a task so that all existing user is automatically confirmed.

  • Go to lib > tasks and create a new file with named updated_confirmed_at_users.rake
  • Copy the following code into that file
task :updated_confirmed_at_users => :environment do
 User.all.each do |user|
 user.update(confirmed_at: DateTime.now)
end
The above task will take all user in loop and update their confirmed_at column with value of current time.

To run the task, go to the terminal under the project path and run the following code.

rake updated_confirmed_at_users
You can check the user's table, if the values are updated or not.
  • Now go to sign up page and create a new user. A confirmation email will send to the user, without confirming the email user cannot be entered into the website. And also confirmation token and confirmation sent at are also filled in the database, you can also verify that. Now we have to show an error message if the user is not confirmed their email address.

First go to the session_controller > create method and add the following code.

if User.find_by_email(params[:user][:email]).present?
 if User.find_by_email(params[:user][:email]).try(:confirmed_at).present?
  super
 else
  redirect_to :back, notice:  'Please confirm your email first'
 end
else
 redirect_to :back, notice:  'User not found'
end
This check verifies that is the user is not confirmed the email show them an error message on the sign in page.

The above code is explained below

  • At the first line,we are checking if user present in the database or not. Next, if a user is found then we are checking that user is confirmed their email address or not. If not redirect to sign in page with a message. we also pass an error message from the controller and we have to show it on the view page. To show it go to views > users > session.html.erb > new.html.erb and the following code at the top of the page.
<div><%=notice%></div>
The error messages will shown show as in highlighted part of below image.

Everything is set up now one last step is to confirm the email. Now go to your registered email and confirm your email by clicking the confirm link in the email. If the user successfully confirmed email it will now access the app.

You can customise the confirmation email. The confirmation emails source code can be found views > users > mailer > confirmation_instruction The following the simple content for confirm email for now

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

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

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

It has simple content like user email in the @email variable and link to confirm the email in the app.

Curriculum

Proof of Work Done

https://github.com/aman9463

Sort:  

Hey @amn
Thanks for contributing on Utopian.
We're already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

In the next tutorial try to structure the tutorial better. Thank you for your contribution.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

nice tutorial @amn. I am looking for your next contributions. Nice work just keep mods suggestion in mind for your next contribution.

Thanks @iamankit, I will definately try in my upcoming tutorial.

cool... Best of luck

Thank you @portugalcoin, I will keep trying to improve my structure and content in upcoming tutorials

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by amn from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Congratulations @amn! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Do you like SteemitBoard's project? Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.27
TRX 0.12
JST 0.032
BTC 61979.42
ETH 2916.97
USDT 1.00
SBD 3.63