Building a Simple Addressbook with Authentication using Devise
Assumptions: You are using Rails 3, even though I tried to accomodate Rails 2 as well.
In this Tutorial / Recipe, l go through creating a very simple “Addressbook” with Devise as its Authentication system.
This Addressbook only contains two fields name and phone.
A User model is generated with authentication using the Devise gem.
I also use the nifty-scaffold and nifty-layout to make it look prettier than pages created via Rails’ default scaffold.
Create your Rails application
rails new contact
Install the nifty-generators gem
gem install nifty-generators
Add the following to your Gemfile:
gem 'nifty-generators', '>= 0.4.2'
Install the nifty-generators gem via Bundler
bundle install
Create the Address Nifty Scaffold and Nifty Layout
rails generate nifty:scaffold Address name:string phone:string rails generate nifty:layout
OR
Use the regular Scaffold, if you prefer
rails generate scaffold Address name:string phone:string
Install the Devise gem
sudo gem install devise (Rails 3) sudo gem install devise --version=1.0.6 (Rails 2)
Note the devise version that was installed with gem install command above
Add Devise to your Gemfile (1.1.5 is the version I installed. Replace with your version)
gem 'devise', '1.1.5'
Install Devise gem via Bundler
bundle install
Install Devise Initializer
rails g devise:install create config/initializers/devise.rb create config/locales/devise.en.yml ================================== Some setup you must do manually if you haven't yet: 1. Setup default url options for your specific environment. Here is an example of development environment: config.action_mailer.default_url_options = { :host => 'localhost:3000' } This is a required Rails configuration. In production it must be the actual host of your application 2. Ensure you have defined root_url to *something* in your config/routes.rb. For example: root :to => "home#index" 3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example: <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p>
Step 1 – Add Devise default url options to your mailer
Add the following to your development.rb file as instructed by rails g devise:install command above.
*Note: you should set this in production.rb as well but be sure to set the host value to your domain name!
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
Step 2 – Set up Root URL
Add this to your config/routes.rb file:
root :to => "addresses#index"
Step 3 – Add Notice and Alert to your Application Layout File
* Note: This step is NOT needed if you are using the Nifty Scaffold and Layout.
Do this only if you are using the default Scaffold.
Add the following to your app/views/layouts/application.html.erb file, maybe somewhere on top of the <%= yield %>.
<p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p>
Then be sure to delete your public/index.html file!
To create a User model using the Devise generator
rails generate devise User invoke active_record create app/models/user.rb invoke test_unit create test/unit/user_test.rb create test/fixtures/users.yml create db/migrate/20101201224007_devise_create_users.rb inject app/models/user.rb route devise_for :users
This generates the User model, migration file and routes for the authentication.
In the User model, a call to devise is included which includes a list of Devise modules which can be customized.
Some of the devise authentication modules which are called out by default are :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
Other modules which are available are: :token_authenticatable, :confirmable, :lockable and :timeoutable
Here are descriptions of each of the 12 modules, from Devise’s Readme:
- Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of an user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
- Token Authenticatable: signs in a user based on an authentication token (also known as “single access token”). The token can be given both through query string or HTTP Basic Authentication.
- Omniauthable: adds Omniauth (github.com/intridea/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 no activity 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.
- Encryptable: adds support of other authentication mechanisms besides the built-in Bcrypt (the default).
The User model which Devise generated also contains a line which sets up a list of fields email, password, password confirmation and remember_me which are writable via mass-assignment, thus can be set from within a form. Be sure to add form fields to this list if you have added custom columns in your users table which you want the user to enter.
Take a look at the migration file the devise generator created for the creating the users table. If you add or remove devise modules from your User model, be sure to add or remove the columns you need or don’t need from this migration file. You may need to add or remove indices to/from the migration file as well.
Migrate the Database Changes
rake db:migrate
Start up the Server
rails server
Hit the Server’s Sign Up, Sign Out Pages
http://localhost:3000/users/sign_up
http://localhost:3000/users/sign_out
Add Navigation Links
To add navigation links to Sign Up, Sign Out and Sign In, you must determine if the user is already signed in.
Add the following to the top of your flash message in your layout/application.html.erb file:
<div> <% if user_signed_in? %> <%= current_user.email %> is logged in. If user is not you, click <%= link_to "Sign Out", destroy_user_session_path %> <% else %> <%= link_to "Register", new_user_registration_path %> or <%= link_to "Sign In", new_user_session_path %> <% end %> </div>
Devise provides the following helper methods, currently, as of version 1.1.5
- authenticate_user! # Signs user in or redirect
- authenticate_admin! # Signs admin in or redirect
- user_signed_in? # Checks whether there is an user signed in or not
- admin_signed_in? # Checks whether there is an admin signed in or not
- current_user # Current signed in user
- current_admin # Current signed in admin
- user_session # Session data available only to the user scope
- admin_session # Session data available only to the admin scope
One Comment to “Building a Simple Addressbook with Authentication using Devise”