Rails and Devise
Rails 5.0 example application that provides authentication and user management.
- Devise for user management and authentication
- Bootstrap or Foundation front-end frameworks
Use this example application as a starter app for your own web applications. A complete Devise Tutorial is available.
You can build this application in only a few minutes using the Rails Composer tool, choosing either a Bootstrap or Foundation front-end framework, as well as many other options, such as Haml or Slim. You get login and signup pages (also “edit account” and “forgot password” pages) that are more attractive than the default Devise pages.
From the RailsApps Project
The RailsApps open source project offers starter applications and tutorials for Rails developers. Generate the applications with the Rails Composer tool.
All the code is explained in the Capstone Rails Tutorials. You can purchase the Capstone Rails Tutorials to support the project.
If You Are New to Rails
If you’re new to Rails, see What is Ruby on Rails?, the book Learn Ruby on Rails, and recommendations for a Rails tutorial.
Devise Tutorial
An in-depth Devise Tutorial is available from the RailsApps project. The tutorial describes the example application in detail, so there is no mystery code.
What Is Implemented — and What Is Not
The example application can be used as the basis for a website that provides a login page and user management. With knowledge of Rails, the website can be adapted and customized to your needs. Features include:
- Home page
- Navigation bar
- Sign up (create account)
- Login
- “Forgot password?” feature
- “Remember me” (stay logged in) feature
- Edit account (edit user profile)
- List of users
The list of users is visible to anyone. Use authentication to restrict it to the user who was created first, or implement authorization to restrict it to an administrator. See the rails-devise-pundit example application if you wish to add authorization.
Database
The application requires a database. The example application uses SQLite with Rails ActiveRecord. You can easily substitute PostgreSQL, MySQL, or other databases.
Front-end Framework
The example application (here in the GitHub repository) integrates Bootstrap for a navigation bar and flash messages. The rails_layout gem is included so you can switch to the Foundation front-end framework.
Similar Examples and Tutorials
This is one in a series of Rails example apps and tutorials from the RailsApps Project. See a list of additional Rails examples, tutorials, and starter apps. Related example applications may be useful:
- Learn Rails companion to the book Learn Ruby on Rails
- Foundation and Rails shows how to integrate Foundation
- Bootstrap and Rails shows to integrate Bootstrap
- OmniAuth and Rails uses OmniAuth for authentication
- Devise and Pundit and Rails uses Pundit for authorization
Accounts You Will Need
Devise provides a “Forgot Password?” feature that resets a password and sends instructions to the user. You’ll need an email service provider to send email from the application. You can use Gmail during development. You can get a free Gmail account if you don’t already have one. For production, Gmail is not robust. Use transactional email services, such as SendGrid, to send email in production. See the article Send Email with Rails for more information.
We provide instructions to deploy the application to Heroku which provides Rails application hosting. It costs nothing to set up a Heroku account and deploy as many applications as you want. To deploy an app to Heroku, you must have a Heroku account. Visit Heroku to set up an account.
Dependencies
Before generating your application, you will need:
- The Ruby language – version 2.3.1
- The Rails gem – version 5.0
See the article Installing Rails for instructions about setting up Rails and your development environment.
Getting the Application
Local
You have several options for getting the code on your own machine. You can fork, clone, or generate.
Fork
If you’d like to add features (or bug fixes) to improve the example application, you can fork the GitHub repo and make pull requests. Your code contributions are welcome!
Clone
If you want to copy and customize the app with changes that are only useful for your own project, you can clone the GitHub repo. You’ll need to search-and-replace the project name throughout the application. You probably should generate the app instead (see below). To clone:
$ git clone git://github.com/RailsApps/rails-devise.git
You’ll need git on your machine. See Rails and Git.
Generate
If you want to use the project as a starter application, use the Rails Composer tool to generate a new version of the example app. You’ll be able to give it your own project name when you generate the app. Generating the application gives you additional options.
To build the example application, Rails 5.0 must be installed in your development environment. Run the command:
$ rails new rails-devise -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb
The $
character indicates a shell prompt; don’t include it when you run the command.
This creates a new Rails app named rails-devise
on your computer. You can use a different name if you wish.
You’ll see a prompt:
option Build a starter application? 1) Build a RailsApps example application 2) Contributed applications 3) Custom application
Enter “1” to select Build a RailsApps example application. You’ll see a prompt:
option Choose a starter application. 1) learn-rails 2) rails-bootstrap 3) rails-foundation 4) rails-mailinglist-activejob 5) rails-omniauth 6) rails-devise 7) rails-devise-roles 8) rails-devise-pundit 9) rails-signup-download 10) rails-stripe-checkout
Choose rails-devise. The Rails Composer tool may give you other options (other applications may have been added since these notes were written).
The application generator template will ask you for additional preferences:
question Web server for development? 1) WEBrick (default) 2) Thin 3) Unicorn 4) Puma 5) Phusion Passenger (Apache/Nginx) 6) Phusion Passenger (Standalone) question Web server for production? 1) Same as development 2) Thin 3) Unicorn 4) Puma 5) Phusion Passenger (Apache/Nginx) 6) Phusion Passenger (Standalone) question Database used in development? 1) SQLite 2) PostgreSQL 3) MySQL question Template engine? 1) ERB 2) Haml 3) Slim question Test framework? 1) None 2) RSpec with Capybara question Front-end framework? 1) None 2) Bootstrap 3.3 3) Bootstrap 2.3 4) Zurb Foundation 5.5 5) Zurb Foundation 4.0 6) Simple CSS setup The Devise 'forgot password' feature requires email. question Add support for sending email? 1) None 2) Gmail 3) SMTP 4) SendGrid 5) Mandrill question Devise modules? 1) Devise with default modules 2) Devise with Confirmable module question Use a form builder gem? 1) None 2) SimpleForm extras Set a robots.txt file to ban spiders? (y/n) extras Create a GitHub repository? (y/n) extras Use or create a project-specific rvm gemset? (y/n)
Web Servers
If you plan to deploy to Heroku, select Unicorn as your production webserver. Unicorn is recommended by Heroku.
Database
Use SQLite for development on Mac or Linux, unless you already have PostgreSQL installed locally. Use PostgreSQL if you plan to deploy to Heroku. You can easily change the database later if you select SQLite to start.
Template Engine
The example application uses the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml or Slim. See instructions for Haml and Rails.
Testing
If you are a beginner, select “None.”
Front-end Framework
The example in the GitHub repository was built without a front-end framework. Use Zurb Foundation 5.5 or Bootstrap 3.3 if you like. Choosing either Foundation or Bootstrap will automatically install Devise views with attractive styling.
Choose Gmail for development if you already have a Gmail account. Choose SendGrid or Mandrill for production if your site will be heavily used.
Devise Modules
The example in the GitHub repository uses Devise with default modules.
Other Choices
Set a robots.txt file to ban spiders if you want to keep your new site out of Google search results.
If you choose to create a GitHub repository, the generator will prompt you for a GitHub username and password.
It is a good idea to use rvm, the Ruby Version Manager, and create a project-specific rvm gemset (not available on Windows). See Installing Rails.
Troubleshooting
If you get an error “OpenSSL certificate verify failed” or “Gem::RemoteFetcher::FetchError: SSL_connect” see the article OpenSSL errors and Rails.
README
Edit theIf you’re storing the app in a GitHub repository, please edit the README files to add a description of the app and your contact info. If you don’t change the README, people will think I am the author of your version of the application.
Getting Started
See the article Installing Rails to make sure your development environment is prepared properly.
RVM
UseI recommend using rvm, the Ruby Version Manager, to create a project-specific gemset for the application. If you generate the application with the Rails Composer tool, you can create a project-specific gemset.
Gems
Here are the gems used by the application:
- devise – authentication and user management
These gems make development easier:
- better_errors – helps when things go wrong
- rails_layout – generates files for an application layout
Your choice of front-end framework:
- bootstrap-sass – Bootstrap for CSS and JavaScript
- foundation-rails – Zurb Foundation for CSS and JavaScript
Install the Required Gems
If you used the Rails Composer tool to generate the example app, the application template script has already run the bundle install
command.
If not, you should run the bundle install
command to install the required gems on your computer:
$ bundle install
You can check which gems are installed on your computer with:
$ gem list
Keep in mind that you have installed these gems locally. When you deploy the app to another server, the same gems (and versions) must be available.
Front-end Framework
If you generate the application using the Rails Composer tool, you have the option to install either Bootstrap or Foundation. The folder app/views/devise/ will contain attractive view files that override the views provided in the Devise gem.
Changing the Front-end Framework
The version of the application in the repository includes Bootstrap. If you wish to install Foundation instead, use the rails_layout gem to generate new files. First add a gem to the Gemfile:
gem 'foundation-rails'
Use Bundler to install the gem:
$ bundle install
To create layout files for use with Zurb Foundation 5.5:
$ rails generate layout:install foundation5
The “layout:devise” Command
Devise provides a utility command rails generate devise:views
. The Devise command creates view files for signup, login, and related features. However, the views generated by Devise lack CSS styling.
Use the RailsLayout gem to generate Devise views with styling for Bootstrap or Foundation.
$ rails generate layout:devise bootstrap3
$ rails generate layout:devise foundation5
The command will create these files:
- app/views/devise/sessions/new.html.erb
- app/views/devise/passwords/new.html.erb
- app/views/devise/registrations/edit.html.erb
- app/views/devise/registrations/new.html.erb
Additionally, the command will update a file to append Sass mixins to accommodate Bootstrap or Foundation:
- app/assets/stylesheets/framework_and_overrides.css.scss
The Sass mixins allow any view to be used with either Bootstrap or Foundation (so we don’t have to maintain separate views for each front-end framework).
Configuration File
To consolidate configuration settings in a single location, we store credentials in the config/secrets.yml file. To keep your credentials private, use Unix environment variables to set your credentials. See the article Rails Environment Variables for more information.
Add your credentials to the file config/secrets.yml:
# Make sure the secrets in this file are kept private # if you're sharing your code publicly. development: admin_name: First User admin_email: [email protected] admin_password: changeme email_provider_username: <%= ENV["GMAIL_USERNAME"] %> email_provider_password: <%= ENV["GMAIL_PASSWORD"] %> domain_name: example.com secret_key_base: very_long_random_string test: secret_key_base: very_long_random_string domain_name: example.com # Do not keep production secrets in the repository, # instead read values from the environment. production: admin_name: <%= ENV["ADMIN_NAME"] %> admin_email: <%= ENV["ADMIN_EMAIL"] %> admin_password: <%= ENV["ADMIN_PASSWORD"] %> email_provider_username: <%= ENV["GMAIL_USERNAME"] %> email_provider_password: <%= ENV["GMAIL_PASSWORD"] %> domain_name: <%= ENV["DOMAIN_NAME"] %> secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
All configuration values in the config/secrets.yml file are available anywhere in the application as variables. For example, Rails.application.secrets.email_provider_username
will return the string set in the Unix environment variable GMAIL_USERNAME
.
For the Gmail username and password, enter the credentials you use to log in to Gmail when you check your inbox. See the article Send Email with Rails if you are using Google two factor authentication.
The values for admin_email
and admin_password
are used when the database is seeded. You will be able to log in to the application with these credentials. Note that it’s not necessary to personalize the config/secrets.yml file before you deploy your app. You can deploy the app with an example user and then use the application’s “Edit Account” feature to change email address and password after you log in. Use this feature to log in as an administrator and change the email and password to your own.
The variable domain_name
is used for sending email. You can use example.com
in development. If you already have a custom domain name you’ll use when you deploy the application, you can set domain_name
. If you deploy the application to Heroku, you’ll set domain_name
with the unique name you’ve given your application on Heroku. You’ll have to wait until you deploy to know the name you’ll use on Heroku.
If you don’t want to use Unix environment variables, you can set each value directly in the config/secrets.yml file. The file must be in your git repository when you deploy to Heroku. However, you shouldn’t save the file to a public GitHub repository where other people can see your credentials.
Database Seed File
The db/seeds.rb file initializes the database with default values.
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) user = CreateAdminService.new.call puts 'CREATED ADMIN USER: ' << user.email
CreateAdminService
is a service object that obtains admin_email
and admin_password
values from the config/secrets.yml file. You can examine the file app/services/create_admin_service.rb to see how a new user is created.
Set the Database
If you’ve used the Rails Composer tool to generate the application, the database is already set up with rake db:migrate
and rails db:seed
.
If you’ve cloned the repo, prepare the database and add the default user to the database by running the commands:
$ rails db:migrate $ rails db:seed
Use rails db:reset
if you want to empty and reseed the database.
Change your Application’s Secret Token
If you’ve used the Rails Composer tool to generate the application, the application’s secret token will be unique, just as with any Rails application generated with the rails new
command.
However, if you’ve cloned the application directly from GitHub, it is crucial that you change the application’s secret token before deploying your application in production mode. Otherwise, people could change their session information, and potentially access your site without permission. Your secret token should be at least 30 characters long and completely random.
Get a unique secret token:
$ rails secret
Edit the config/secrets.yml file to change the secret token.
Test the App
You can check that your application runs properly by entering the command:
$ rails server
To see your application in action, open a browser window and navigate to http://localhost:3000/.
You should see a home page with a navigation bar.
You should be able to click the navigation links for “Log in” and “Sign up.”
Stop the server with Control-C. If you test the app by starting the web server and then leave the server running while you install new gems, you’ll have to restart the server to see any changes. The same is true for changes to configuration files in the config folder. This can be confusing to new Rails developers because you can change files in the app folders without restarting the server. Stop the server each time after testing and you will avoid this issue.
RSpec Test Suite
The application contains a suite of RSpec feature tests. To run:
$ rspec
Deploy to Heroku
Heroku provides low cost, easily configured Rails application hosting.
From the Command Line
You can deploy from the command line.
$ git push origin master
If you’ve set configuration values in the config/secrets.yml file, you’ll need to set them as Heroku environment variables. You can set Heroku environment variables directly with heroku config:add
. For example:
$ heroku config:add ADMIN_NAME='First User' $ heroku config:add ADMIN_EMAIL='[email protected]' ADMIN_PASSWORD='changeme' $ heroku config:add GMAIL_USERNAME='[email protected]' GMAIL_PASSWORD='secret' $ heroku config:add DOMAIN_NAME='example.com'
See the Tutorial for Rails on Heroku for details.
Adding a Name Attribute
This example application shows how you can add a name
attribute to the User model. You’ll see the name
attribute in the partial used for the “sign up” and “update account” forms:
- app/views/users/_user.html.erb
When you add an attribute to the User model, you must list the attribute in the permitted parameters allowed by Devise. Permitted attributes are listed in the file:
- config/initializers/devise_permitted_parameters.rb
The Devise Tutorial includes a full explanation.
Troubleshooting
Problems? Check the issues.
Issues
Please create a GitHub issue if you identify any problems or have suggestions for improvements.
Where to Get Help
Your best source for help with problems is Stack Overflow. Your issue may have been encountered and addressed by others.
Use the tag “railsapps” on Stack Overflow for extra attention.
Contributing
If you make improvements to this application, please share with others.
Send the author a message, create an issue, or fork the project and submit a pull request.
If you add functionality to this application, create an alternative implementation, or build an application that is similar, please contact me and I’ll add a note to the README so that others can find your work.
Credits
Daniel Kehoe implemented the application and wrote the tutorial.
Is the app useful to you? Follow the project on Twitter: @rails_apps
and tweet some praise. I’d love to know you were helped out by what I’ve put together.
MIT License
Copyright ©2014-16 Daniel Kehoe