Devise Gem for Authentication in Rails Applications
Introduction
Devise is a flexible authentication solution for Rails based on Warden. It:
- is Rack based;
- is a complete MVC solution based on Rails engines;
- allows you to have multiple models signed in at the same time;
- is based on a modularity concept: use only what you really need.
It is built on top of Warden. Warden is a rack application that runs as a separate and standalone module. It provides cookie-handling that verifies the identity of a logged user via a session string in which the “id” is stored and disguised. It also provides hook-dealing with users who aren’t currently logged in.
Devise interacts with Warden using strategies. Strategies are used for encrypting passwords, email confirmation and for HTTP authentication.
Working with Devise
Devise is a complete MVC solution based on Rails engine. It is based upon the modularitty concept which is based on the principle of “Use what you really need”. It is composed of 10 modules:
- Database Authenticatable: hashes and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
- Omniauthable: adds OmniAuth (https://github.com/omniauth/omniauth) support.
- Confirmable: sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
- Recoverable: resets the user password and sends reset instructions.
- Registerable: handles signing up users through a registration process, also allowing them to edit and destroy their account.
- Rememberable: manages generating and clearing a token for remembering the user from a saved cookie.
- Trackable: tracks sign in count, timestamps and IP address.
- Timeoutable: expires sessions that have not been active in a specified period of time.
- Validatable: provides validations of email and password. It’s optional and can be customized, so you’re able to define your own validations.
- Lockable: locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.
Steps
Open up your Gemfile and add this line
Add Devise Gem
1
gem 'devise'
and run
1
bundle install
to install the gem. Also remember to restart the Rails server.
Set up devise in your app
Run the following command in the terminal.
1
rails g devise:install
Configure Devise
Ensure you have defined default url options in your environments files. Open up
config/environments/development.rb
and add this line:
1
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
before the end
keyword.
Devise Utility Methods
1
2
3
4
5
6
- authenticate_user!
- current_user
- user_ signed_in?
- sign_in(@user)
- sign_out(@user)
- user_session
Setup the User model
We’ll use a bundled generator script to create the User
model.
1
2
rails g devise user
rails db:migrate
Explain what user model has been generated. What are the fields?
Create your first user
Now that you have set everything up you can create your first user. Devise creates all the code and routes required to create accounts, log in, log out, etc.
Make sure your rails server is running, open http://localhost:3000/users/sign_up and create your user account.
Add sign-up and login links
All we need to do now is to add appropriate links or notice about the user being logged in in the top right corner of the navigation bar.
In order to do that, edit app/views/layouts/application.slim
add:
1
2
3
4
5
6
7
8
9
p.navbar-text.pull-right
- if user_signed_in?
= current_user.email
= link_to 'Edit profile', edit_user_registration_path, :class => 'navbar-link'
= link_to "Logout", destroy_user_session_path, method: :delete, :class => 'navbar-link'
- else
= link_to "Sign up", new_user_registration_path, :class => 'navbar-link'
= link_to "Login", new_user_session_path, :class => 'navbar-link'
end
Finally, force the user to redirect to the login page
if the user was not logged in. Open up app/controllers/application_controller.rb
and add:
1
before_action :authenticate_user!
after
1
protect_from_forgery with: :exception
Open your browser and try logging in and out from.