Implementing Devise in Your Ruby on Rails Application For Authentication
Tags: ruby, rails, webdev, softwareengineering
Published: 2023-08-04 14:06:56

**INTRODUCTION**
[Devise](https://github.com/heartcombo/devise#getting-started) is an effective authentication gem for Ruby on Rails that makes it easier to integrate user authentication into your online applications. Numerous functions are offered, such as session management, third-party sign-in, password reset capability, and others. By providing pre-built modules and functions that are simple to incorporate into your Rails applications, Devise streamlines the process rather than requiring you to construct these features from scratch.

**COMPONENTS OF DEVISE**
Devise has a rich actionable pact composed of 10 modules:

* [Database Authenticatable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/DatabaseAuthenticatable): 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](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Omniauthable): adds [OmniAuth](https://github.com/omniauth/omniauth) support.
* [Confirmable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
* [Recoverable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Recoverable): resets the user password and sends reset instructions.
* [Registerable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account.
* [Rememberable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie.
* [Trackable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Trackable): tracks sign in count, timestamps and IP address.
* [Timeoutable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Timeoutable): expires sessions that have not been active in a specified period of time.
* [Validatable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations.
* [Lockable](http://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.


Devise, an exceptionally thorough gem, does the majority of the authentication chores on your behalf. Even if you're thinking about implementing highly specialised features, Devise can still manage a sizable chunk of the effort involved because it maintains all crucial authentication processes.

## STEPS:

**Making a New Rails Application is the first step.**
```
rails new device-sample
```
![Rew rails app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l1srtvcbi0ugs97d9o7z.png)
A new Rails project with a number of generated files and folders will be created under the directory  device-sample by the rails new command.

**Insert devise into the gemfile as the next step**
```
gem 'devise'
```
![gemfile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2krgollpfoh00ctq5051.png)

**Run bundle install from your terminal after that.**
```
bundle install
```
In Ruby on Rails applications, the command "bundle install" is used to install each of the required gems (libraries) listed in the project's Gemfile. This command resolves dependencies, downloads and installs the requested gems, and then verifies the Gemfile for the necessary gems and their versions. It guarantees that your project has all the dependencies needed to function properly.

**Next step is to run the command to install devise to the project**

```
$ rails generate devise:install
```

![Devise run](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4sm01wrbbbl9vgakdazm.png)
 
Lets go over some of the instructions signalled above:
* **Default URL**: Use the `config.action_mailer.default_url_options` parameter to define default URL options in your environment files. For instance, update the host and port in config/environments/development.rb to the real host in production.
* **Root UR**L: Create a root URL by specifying it in your config/routes.rb file, unless you're developing an API-only service. Use root to: `"home#index"` as an example to establish your root URL.
* **Flash Messages Setup**: To improve user experience, incorporate flash messages into your application's layout (often located in app/views/layouts/application.html.erb). Include `p class="notice">%= notice%> and p class="alert">%= alert%>` in your text.


![Prompt message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zrbdvgzw735ypzicqbi3.png)

**Next we generate view for our application where the login will be**
```
rails generate devise:views
```

![Views](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfc6nb2kdg06hmk67dw8.png)


Great! We can now generate our model. You can call your devise model whatever you want, I will call it "User". It's a generic name understandable by anyone. Let's run the command now.
```
$ rails generate devise User
```
![User model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2wiq2tdizhyf7hjc015.png)

opening the migration file (db/migrate/2........_devise_create_users.rb) to review the default code:

![Miraation path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3yfh9uwdsxo6k4fa0a3g.png)


Here, you can uncomment the fields you want to use, for example, if you want to be able to confirm your users sending them an email, you can uncomment the four lines below # Confirmable. The devise gem will do the rest (plus some configuration of your own you will have to investigate, as it's not going to be covered in this tutorial). 


**Next step is adding a route**

![Rails route](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kowwrgc6i8dm16apssxj.png)

After reviewing the Devise-generated files and configuration, you may use the following command to execute the migration you created at the beginning of this step:

```
$ rails db:migrate
Or you can also write:

$ rake db:migrate
```

![Migration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tmtufhl33n07xt5kz2z.png)


** Finally lets run the server**
```
$ rails server
```

![Sign up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2f7s9p69yor9shu14uq.png)


You've successfully learned how to install devise in your apps, add models using devise, add fields to those models, and modify devise's views. The remaining portions of your web application may now be completed.


Thank you for reading!