1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Part 3: Installing Devise

By

Part 3: Installing Devise

Reddit isn't anything without its users. Everything on Reddit is user-generated content, there's very little that admins simple push to the users. You also can't have votes, proper posts or comments (arguably the best part of Reddit) without proper users, so in this article we'll tackle implementing users using Devise, a popular Rails plugin for authentication.

Why use a canned solution? Authentication is an extremely popular feature. Virtually every single application you'll write needs authentication in one form or another. Even if it's just a small group of admins logging in to publish content, you still need authentication. While it may seem more efficient to simply roll your own every time you need authentication, there are a few things to consider.

First, writing your own authentication is tedious. Every time you make an app, you need to hack in your own authentication? That's not fun (or efficient) at all. Second, that's error-prone. Authentication is something that, when it goes wrong, can not only damage your web application and its data, but your users as well. For example, using improper password hashing you leave your user's passwords at risk, any attacker that steals your database possibly has access too all your user's email accounts if they used the same passwords there. And finally, these are rather mundane details you probably don't want to be thinking about. You just want it so users can log in and interact with the web application, so it most likely makes sense for you to be using a plugin like Devise.

Installing and Setting up Devise

Like always, I like to start a new branch for the task at hand, so let's do that first.


$ git checkout -b add_devise
Switched to a new branch 'add_devise'

Devise couldn't be easier to install. It's a gem, so we just install it using bundler. Open up your Gemfile file and add the line gem 'devise' and then run bundle install.

Next we need to generate a few config files for Devise. The command to do this is rails generate devise:install. This will generate an initializer, as well as a locale file for the Devise messages. You'll get a message instructing you to perform a few more setup tasks. You'll be adding a line to config/environments/development.rb for the mailer, making sure that the root of the application points to something (we did that in a previous article) and adding flash messages to display errors (just stick that the top of the body in app/views/layouts/application.rb.

Once these changes are made, it's time to generate the User model. Or, in our case, add the required columns to our existing (dummy) User model. This is done by running rails generate devise User, this will do a few things.


$ rails generate devise User
     invoke  active_record
     create    db/migrate/20121219011615_add_devise_to_users.rb
     insert    app/models/user.rb
      route  devise_for :users

This added a migration, we'll take a look at that in a moment, inserted lines into our app model and added a special devise_for route. The most important thing to be looking at here is our new migration, so open that up in your editor. You'll see a lot of new columns being added to the User model, each in their own section with names like Database Authenticatable or Trackable. These are the Devise modules, each of which can be disabled or replaced. In versions past, the Confirmable module was enabled by default, which was the first thing many people disabled. As you can see it's disabled now, its lines are commented out. Leave it like that, everything here is already just how we want it. However, I mention this because if you do enable it, be sure to enable its confirmation token line in the bottom part of the migration as well as the module in the app/models/user.rb file. Also, this is by default an irreversible migration. So make sure it's what you really want (or your development database doesn't have anything important in it) before continuing.

So once you're all ready, go ahead and rake db:migrate.


$ rake db:migrate
==  AddDeviseToUsers: migrating ===============================================
-- change_table(:users)
  -> 0.0274s
-- add_index(:users, :email, {:unique=>true})
  -> 0.0009s
-- add_index(:users, :reset_password_token, {:unique=>true})
  -> 0.0005s
==  AddDeviseToUsers: migrated (0.0291s) ======================================

Oh, and since you added a gem to your project, if you have any server running you'll need to restart them in order for it to take effect, or all you'll get is error messages. So go to your server window, hit Ctrl C and run rails server again.

So where does the magic happen? We didn't see or talk about any controllers, how do users log in? These are handled by the plugin itself. Note that in config/routes.rb, the line devise_for :users was added, and the actual logic is handled by the plugin itself. This code will not appear in your app/controllers directory. So, to see which routes it added, run rake routes. Since this is such a small application, most of the routes you see will have to do with the Users controller, and you'll see actions for things like signing up, signing in and out, changing passwords, etc. You can immediately start using this by going to http://localhost:3000/users/sign_up, filling in the form and submitting it. That'll sign you up and log you in. Fire up the console and we'll confirm that it did what we wanted.

To get the last-created object from a model, the easiest way is to fire up rails console and call (in this case) u = User.last. Examining this user, we'll see that it has the email and password that we used when registering, the password is encrypted, and everything looks just as it should. So, we created a dummy user last time, let's remove it. Fire up rails console and run User.first.destroy and p = Post.first; p.user = User.first; p.save. Now our test user is gone and our test post is owned by the new user you created with Devise.

  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. Creating a Reddit Clone with Rails
  6. Part 3: Installing Devise

©2014 About.com. All rights reserved.