Using Devise to Implement Registrations and Login Functionality
This guide gives step by step instructions for how to install the Devise gem and configure it to allow users to register, login, and logout of a Ruby on Rails 5 application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So we have the gem stalled, nothing has actually changed in our application. In fact if we were to start up our app and start navigating around, literally not a single change has occurred. Installing the library is really just the first step, that simply gives our application the ability to call these modules and methods that are provided by devise.

The installation guide is usually on the homepage or the documentation page on rubygems.org. If you click on homepage, this will take me to where the full set of installation instructions are.

large

Anytime you want to install a gem, usually you're going to come to a page like this and have all of the installation guide details. First thing we already was install devise and ran bundle install.

Next we have to install the generator. Devise has its own special generator, if I copy and paste this code rails generate devise:install into the terminal. This is going to install a number of the things we're going to need in order to have authentication on our system.

It's going to give us a config/initializers file and also a config/locales file. The initializer allows us to have some custom settings that we may want to have with devise, we'll take a look at that in a second.

The locales is something we're not going to worry about for now. If you ever wanted to do something like have a different language for your application then you could actually have multiple locales. You could have one for Spanish, Chinese or Mandarin or something like that. If you put that here then when it runs you'd have the option to have different languages.

The next thing, you have all of your instructions right here, which is awesome. Let's go take a look at config/initializers/devis.rb You can see all of the special devise options. For the most part we're going to keep most of these the same. There is only one that I'm to change but I do want to show you a few that are there.

We talked about validation items in the last section, devise actually ships with its own set of validations. This (line 162 config.email_regexp = /\A[^@\s]+@[^@\s]+\z/) is a validation for emails, you can read the comments that says the email regex is used to validate e-mail formats. It simply asserts that one and only one @ symbol exists in the given string and this gives user feedback and not to assert the email validity.

What this means is it's just verifying that there is an @ symbol and that it is in between two other set of strings. This is a pretty loose type of validation, if you ever wanted to customize it and make it more strict this is the best spot to do it.

You also could change the password length (line 157), by default it allows you to have 6 to 128 characters and it's given in the range format, config.passwaord_length = 6..128. If you wanted to make it a little bit tougher like say you wanted to have 10 characters or something like that then you could put it right here and the error messages would automatically say your password needs to be 10 characters.

Scrolling down, you also have with devise to reset your password (line 203) config.reset_password_within = 6.hours. This actually sets a default token so that when a user requests the new password, the e-mail that gets sent to them to reset their password is only good for six hours. You can customize it right here, if you had a banking application and you only wanted this to be good for one hour or something like that you could change that.

Here you can select how you want to sign out the defaults delete (line 245) config.sign_out_via = :delete, that's pretty standard. There are all kinds of other customizations and feel free to explore those, there are some pretty cool ones and some that you will probably use maybe once in your lifetime.

The one thing we are going to change is the mailer sender (line 15) config.mailer_sender = which means if you have the system set up so you want users to have a custom e-mail address that they see for the "from" (example: they say I forgot my password, we could send something like "support@devcamp.com") When they click on "forgot my password" this is going to be what is in the "from" field of the email that follows.

If you read it before it said "please-change-me-at-config-Initializers-devise@example.com". You probably don't want that sent to any of your users. That's our only change on that side.

Now we can look at the rest of our instructions, the first is having your default options in the environment files. This is for setting the mailer, we can copy this It tells us to put it in config/environments/development.rb. Right above the "end", we're going to say host: 'localhost', port: 3000. If you're using a different port, which is something we'll talk about later, you can customize this but for most applications this is what we're going to be using.

They do mention that in production, host should be set to the actual host of your application. That means that when your site is live on the web then host shouldn't say localhost it should say "yoursite.com" or whatever your URL is.

Step two is to make sure that you have a homepage, (that your route URL) and we have that.

Step three is to have Flash messages. These are these little notice and alerts. if I go into the application.html file we don't have any of these right now. Let's add these, we're not going to use these exact ones and we'll eventually customize our own that will look much better than. That way we can get our alerts right at the top of the page.

Last thing that we're going to do is type rails g devise:views. This is another generator that is going to create all of the view files we're going to need for a devise.

large

As you can see, it created all kinds of view files.

Let's take a quick look at these. If I go to app/views you'll see we now have a new directory right here called devise, it has all kinds of different directories inside of it.

  • confirmations
  • mailers
  • passwords
  • registrations
  • sessions
  • shared
  • unlocks.

The two we are going to be the most concerned about in the beginning are registrations and sessions. For lack of a better term, this means a registration is like signing up for your application and a sessions is signing into your application.

We have everything we need but we're not quite done yet. If we go back to the devise documentation, the next set of instructions is where it says rails generate devise model. It says "model" but do not type model, what they mean is whatever model you personally want to use. The traditional one is to use one called "user." Type in rails generate devise User and hit return.

This is going to create a migration file and a model file called "user" and also give us some routes. Let's take a look at all of those.

If I go to route's first, you can see that we have a new route method here called devise_for :users. This essentially means that it created all kinds of routes for us like our login and logout.

large

The other thing that it created. Is our model file.

large

Right here by default it inherits from ApplicationRecord like normal but it has this special devise method. By default we have

  • database_authenticatable
  • register
  • recoverable
  • rememberable
  • trackable
  • validatable

These ship by default. Some other options that you have are

  • confirmable
  • lockable
  • timeoutable
  • omniauthable

Confirmable means that when a user signs up for the application, they can't actually access the application until they have confirmed that they are a real human being. Meaning that they were sent an e-mail and the e-mail says if you really signed up for the site please click this confirmation link. I don't think that this would be a good user experience for a portfolio app, the only people that are signing up for your site are people who are going to be commenting. You wouldn't want to make it hard for them to comment, however, if you want to, feel free to research it and put that in.

Lockable gives you the ability to lock a user out given a number of times that they tried to login with the wrong username and password. If you implement lockable, you'd have the ability to set some some rules and configuration options to say "I want to lock this person out if they have five failed login attempts."

Timeoutable means that you want the ability to time-out a user by default. As long as the user is logged in they're not going to be logged out of your application. They could be logged in and come back a month later and they're still going to be logged in. This gives you have the ability to set some options to say "I want to log the user out after 5 hours or five days." This is something that would be helpful if you were building a banking or a stock application, something where security is important. You don't want to let a user sign in, forget to sign out, and leave a shared computer and have someone come hack their account.

Omniauthable allows you to integrate third party log ins. If you wanted to allow a user to login/register via Facebook, this is the option that would allow for that.

Each of these require some other settings to be placed in, if you just add them to the list they're not going to work right off the shelf. You also have to do some customizations, I did want to point them out in case that was something that you wanted to do.

Let's open up our db/migration file. We have DeviseCreateUsers and you can see that this has a big table with all kinds of attributes

picture

  • e-mail
  • password
  • created at
  • when a user signed in
  • the current sign in
  • the last time they were signed in
  • their IP address when they signed in

We have the ability to customize this however we want, if you remember when I talked about confirmable and lockable, this is where you could turn those features on. You could come here and uncomment these, then when you run the migration then all of that would work. Like I mentioned I don't really want that and the same thing for lockable. If that was something you wanted it is there by default and is commented out for you.

The changes I do want to make is to have a first name and a last name. I think those are kind of standard ones. I'm going to come here and give a comment

large

Let's type in rails db:migrate in the terminal, everything there worked. Now, if I type rails s to start up the real server this all should work.

I'm going to open up the browser and go to localhost:3000/users/sign_up, if everything works you should see something exactly like this.

large

I could type in test@test.com then type in a password and confirm it. Click sign up and now it says "Welcome! You've signed in successfully."

If I close the server and type rails c, and type User.last you can see that that created a user in the database.

If you did that fantastic job! You now have a site that allows users to register and log in.

type

  • git status
  • git add .
  • git commit -m 'Implemented basic authentication'
  • git push origin authentication

That is everything that we need to do, we can come up here to a pivotal tracker and say that we implemented the devise gem.

Great job, in the next guide we're going to see how we can customize our routes.

Resources