Last updated 23 November 2012
For a Rails 4.2 example application with OmniAuth, see the rails-omniauth application, with an OmniAuth Tutorial.
This tutorial showis how to create a Rails 3.2 application using OmniAuth with Mongoid.
OmniAuth gives you ready-made authentication using a service provider such as Twitter or Facebook. Mongoid gives access to a MongoDB datastore for quick development without schemas or migrations. This tutorial also gives you the option of using Haml, RSpec and Cucumber, showing how to integrate each option.
This tutorial shows how to set up an application for sign-in with a single provider. For example, you may be creating an application just for Twitter users. Alternatively, it’s possible to create an application that lets a user log in using multiple providers. For these more complex applications, see other examples and tutorials listed below.
Any issues? Please create an Issue on GitHub.
Devise provides authentication using username (or email address) and password. If you don’t need the option of using a username/password, that is, if you wish to have all your users sign in using a service provider’s account (such as Twitter or Facebook), there’s no need to use Devise. Devise can be used in conjunction with the OmniAuth gem when you need to offer users the option of signing up for access to a website using an email address. For example, combine Devise with OmniAuth to accommodate users who want to log in with various service providers (Twitter, Facebook, etc.) as well as users who don’t have external accounts and want to sign up with just an email address. See suggestions below for tutorials and examples that combine Devise with OmniAuth.
You don’t need to ask a visitor for an email address when you build an application that allows a user to log in using a service provider such as Twitter or Facebook. You may consider that an advantage: if a user is logged in with Twitter or Facebook, they don’t need to enter an email address and password to access your application. However, the lack of an email address may be a business drawback, if you want the opportunity to stay in contact with the user by email. Some service providers provide the user’s email address to your application (Facebook). Some service providers only provide the email address at the user’s option (GitHub supplies it if the user has provided a public email address). And other service providers do not provide the email address at all (Twitter, Meetup, LinkedIn).
This example app shows how to request an email address from the user when he or she first requests access to your application. It is easy to remove this feature if you don’t require it.
Author | OmniAuth Example or Tutorial | Comments |
---|---|---|
Ryan Bates | Simple OmniAuth | screencast |
Markus Proske | OmniAuth Pure | example and tutorial for OmniAuth with multiple providers |
Markus Proske | Devise and OmniAuth | example and tutorial for OmniAuth and Devise with multiple providers |
Fernando Tapia Rico | Devise, OmniAuth, Mongoid | With tutorial, using MongoDB |
Author | Devise Example and Tutorial | Comments |
---|---|---|
Daniel Kehoe | Devise, RSpec, Cucumber | Detailed tutorial, app template, starter app, using SQLite |
Daniel Kehoe | Devise, Mongoid | Detailed tutorial, app template, starter app, using MongoDB |
See a list of additional Rails examples, tutorials, and starter apps.
Follow the project on Twitter: rails_apps. Tweet some praise if you like what you’ve found.
This tutorial documents each step that you must follow to create this application. Every step is documented concisely, so a complete beginner can create this application without any additional knowledge. However, no explanation is offered for any of the steps, so if you are a beginner, you’re advised to look for an introduction to Rails elsewhere. See recommendations for a Rails tutorial and resources for getting started with Rails.
If you follow this tutorial closely, you’ll have a working application that closely matches the example app in this GitHub repository. The example app is your reference implementation. If you find problems with the app you build from this tutorial, download the example app (in Git speak, clone it) and use a file compare tool to identify differences that may be causing errors. On a Mac, good file compare tools are FileMerge, DiffMerge, Kaleidoscope, or Ian Baird’s Changes.
If you clone and install the example app and find problems or wish to suggest improvements, please create a GitHub issue.
To improve this tutorial, please leave comments below.
Before beginning the tutorial, you may wish to contact the service provider you’ll use to obtain any required API keys. The tutorial assumes you will be using Twitter.
Visit https://dev.twitter.com/apps/new to register your application. When you register your application, use the following values:
Application Website | Callback URL | Notes |
---|---|---|
http://example.com | http://127.0.0.1:3000/ | http://localhost:3000/ doesn’t work |
Visit http://developers.facebook.com/setup to register your application.
Visit https://github.com/account/applications/new to register your application.
OmniAuth supports many other service providers. See the OmniAuth wiki for a List of Provider Strategies.
If you don’t have MongoDB installed on your computer, you’ll need to install it and set it up to be always running on your computer (run at launch). On Mac OS X, the easiest way to install MongoDB is to install Homebrew and then run the following:
brew install mongodb
Homebrew will provide post-installation instructions to get MongoDB running. The last line of the installation output shows you the MongoDB install location (for example, /usr/local/Cellar/mongodb/1.8.0-x86_64). You’ll find the MongoDB configuration file there. After an installation using Homebrew, the default data directory will be /usr/local/var/mongodb.
You have several options for getting the code. You can copy from the tutorial, fork, clone, or generate.
To create the application, you can cut and paste the code from the tutorial into your own files. It’s a bit tedious and error-prone but you’ll have a good opportunity to examine the code closely.
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!
If you want to copy and customize the app with changes that are only useful for your own project, you can download or 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).
You can 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, run the command:
$ rails new rails3-mongoid-omniauth -m https://raw.github.com/RailsApps/rails-composer/master/composer-Rails3_2.rb -T -O
Use the -T -O
flags to skip Test::Unit files and Active Record files.
The $
character indicates a shell prompt; don’t include it when you run the command.
This creates a new Rails app named rails3-mongoid-omniauth
on your computer. You can use a different name if you wish.
You’ll see a prompt:
question Install an example application? 1) I want to build my own application 2) rails3-bootstrap-devise-cancan 3) rails3-devise-rspec-cucumber 4) rails3-mongoid-devise 5) rails3-mongoid-omniauth 6) rails3-subdomains
Choose 5) rails3-mongoid-omniauth.
The application generator template will ask you for additional preferences.
For this tutorial, choose “WEBrick” for your development webserver.
You can choose to set a robots.txt file to ban spiders and keep your site out of Google search results.
If you are a Linux user and you haven’t installed node.js, you’ll need to answer “yes” to install the ‘therubyracer’ JavaScript runtime.
If you have installed rvm, the Ruby Version Manager, I recommend you answer “yes” to the prompt, “Use or create a project-specific rvm gemset?” See the article Installing Rails to learn about the benefits of using rvm.
Finally, the program will ask if you want to create a GitHub repository.
If you get an error “You have already activated (…) but your Gemfile requires (…)”, try deleting the rails3-mongoid-omniauth folder and running the command again.
Before beginning this tutorial, you need to install
Check that appropriate versions of Ruby and Rails are installed in your development environment:
$ ruby -v
$ rails -v
Be sure to read Installing Rails for detailed instructions and advice.
Beginning here, we show how to create the application from scratch.
(This has already been done for you if you use the the Rails Composer tool.)
Open a terminal, navigate to a folder where you have rights to create files, and type:
$ rails new rails3-mongoid-omniauth -T -O
Use the -T -O
flags to skip Test::Unit files and Active Record files. Add the -J
flag to skip Prototype files for Rails 3.0 (not needed for Rails 3.1).
You may give the app a different name if you are building it for your own use. For this tutorial, we’ll assume the name is “rails3-mongoid-omniauth.”
This will create a Rails application that uses a SQLite database for data storage. We’ll modify it to use MongoDB.
After you create the application, switch to its folder to continue work directly in that application:
$ cd rails3-mongoid-omniauth
If you’re open sourcing the app on GitHub, please edit the README file to add a description of the app and your contact info. Changing the README is important if you’re using a clone of the example app. I’ve been mistaken (and contacted) as the author of apps that are copied from my example.
If you’re creating an app for deployment into production, you’ll want to set up a source control repository at this point. If you are building a throw-away app for your own education, you may skip this step.
$ git init .
$ git add .
$ git commit -m 'Initial commit'
See detailed instructions for Using Git with Rails.
The application uses the following gems:
OmniAuth version 1.0 and later depends on external gems that implement access strategies for specific service providers. For example, if you want your users to authenticate using a Twitter account, you’ll need the omniauth-twitter
gem. See the OmniAuth wiki for a List of Provider Strategies to determine if gems are available for the services you wish to use. If you don’t see a service you want, try a RubyGems.org search for what you need.
This tutorial assumes you will be using Twitter so add the omniauth-twitter
gem to your Gemfile.
It’s a good idea to create a new gemset using rvm, the Ruby Version Manager, as described in the article Installing Rails.
See Example Gemfiles for Rails 3.2.
Open your Gemfile and replace the contents with the following:
Gemfile
source 'https://rubygems.org' gem 'rails', '3.2.13' group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'uglifier', '>= 1.0.3' end gem 'jquery-rails' gem "mongoid", ">= 3.0.3" gem "rspec-rails", ">= 2.11.0", :group => [:development, :test] gem "capybara", ">= 1.1.2", :group => :test gem "database_cleaner", ">= 0.8.0", :group => :test gem "mongoid-rspec", ">= 1.4.6", :group => :test gem "cucumber-rails", ">= 1.3.0", :group => :test, :require => false gem "launchy", ">= 2.1.2", :group => :test gem "factory_girl_rails", ">= 4.0.0", :group => [:development, :test] gem "omniauth", ">= 1.1.0" gem "omniauth-twitter"
Check for the current version of Rails and replace gem 'rails', '3.2.13'
accordingly.
Note: The RailsApps examples are generated with application templates created by the Rails Apps Composer Gem. For that reason, groups such as :development
or :test
are specified inline. You can reformat the Gemfiles to organize groups in an eye-pleasing block style. The functionality is the same.
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.
In this tutorial, we’ll use the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml. See instructions for Haml and Rails.
If you are creating an application template, this step uses the rspec recipe from the rails_apps_composer repository.
You don’t have to install RSpec. The example app will run without it. However, if you are planning to use the example app as a starter app for futher development, you really should install RSpec. RSpec is generally preferred to the Rails default TestUnit for unit testing.
The RSpec Book is the best reference for using RSpec.
Use the gem rspec-rails to set up the app for RSpec.
Add the following to your Gemfile file:
gem 'rspec-rails', :group => [:development, :test] gem 'database_cleaner', :group => :test gem 'factory_girl_rails', :group => :test gem 'mongoid-rspec', :group => :test
The gem rspec-rails
needs to be in the :development
group (as well as the :test
group) to expose generators and rake tasks during development.
The gems mongoid-rspec and factory_girl_rails add additional capabilities (described below).
Install the required gems on your computer:
$ bundle install
Use the rspec-rails generator to set up files needed for RSpec:
$ rails generate rspec:install
You can remove the test folder (it is not needed for RSpec):
$ rm -rf test/
You can also modify the config/application.rb file to remove the following:
require 'rails/test_unit/railtie'
When RSpec is installed, Rails generators create specs for views and helpers when the rails generate controller
or rails generate scaffold
commands are run. If you don’t want specs for views and helpers, modify the config/application.rb file to add the following:
class Application < Rails::Application config.generators do |g| g.view_specs false g.helper_specs false end
To use Mongoid with RSpec, you’ll need to remove ActiveRecord artifacts from the spec/spec_helper.rb file. Modify the file to comment out or remove:
# config.fixture_path = "#{::Rails.root}/spec/fixtures" # config.use_transactional_fixtures = true
Without this adjustment, when you run rake spec
with spec files that contain require 'spec_helper'
you’ll get an error undefined method `fixture_path='
.
RSpec needs to reset the database during testing. You’ll need to configure RSpec to inform Database Cleaner that you are using Mongoid.
Modify the file spec/spec_helper.rb to add this:
RSpec.configure do |config| # Other things # Clean up the database require 'database_cleaner' config.before(:suite) do DatabaseCleaner.strategy = :truncation DatabaseCleaner.orm = "mongoid" end config.before(:each) do DatabaseCleaner.clean end end
Matchers provide ready-made code for your specs, allowing you to quickly add tests for common features. If you are writing specs for ORM features such as validation in Rails models, you will need matchers customized for RSpec and Mongoid. Two similar gems are available: mongoid-rspec and remarkable_mongoid. We use mongoid-rspec in this example. You’ll need gem 'mongoid-rspec', :group => :test
in your Gemfile.
Create a file spec/support/mongoid.rb:
RSpec.configure do |config| config.include Mongoid::Matchers end
Now you can use the RSpec matchers for Mongoid when you write tests. Keep in mind that it may be worthwhile to test validations using ORM matchers but testing of associations is often redundant because Mongoid is well-tested. In general, it is preferable to use Cucumber scenarios to test higher-level functionality and reduce dependency on a specific ORM (see a discussion).
The Factory Girl gem is used to create default model objects for tests. For example, if a controller action requires finding a User object before displaying a “show” page, Factory Girl will create a user just for a test of the controller. You’ll need gem 'factory_girl_rails', :group => :test
in your Gemfile.
You’ll need a spec/factories.rb file to contain the factory definitions for any default objects used for testing. The example spec directory contains an implementation.
Run rake -T
to check that rake tasks for RSpec are available.
You should be able to run rake spec
to run all specs. If you haven’t written any specs, you’ll see the message “No examples matching ./spec//_spec.rb could be found”.
You can copy the files from the example spec directory to use our ready-made specs. If you run rake spec
after adding our ready-made specs, you’ll see an error such as Uninitialized constant ... (NameError)
because you haven’t created models or controllers. You’ll have to complete the tutorial before rake spec
will run successfully.
If you are creating an application template, this step uses the cucumber recipe from the rails_apps_composer repository.
It’s not necessary to add Cucumber (the example will run without it). However, it’s a recommended practice to specify use cases (“user stories”) as Cucumber scenarios. It’s a good way to plan development and, using Cucumber, you’ll have specifications for automated acceptance testing.
This tutorial shows how to set up Cucumber with OmniAuth.
Use the gem cucumber-rails to set up the app for Cucumber.
You should have the following gems in your Gemfile file:
group :test do gem 'cucumber-rails' gem 'capybara' gem 'database_cleaner' end
Install the required gems on your computer:
$ bundle install
Use the cucumber-rails generator to set up files needed for Cucumber:
$ rails generate cucumber:install --capybara --rspec --skip-database
The -–capybara
option specifies Capybara instead of the default Webrat for acceptance testing. The -–rspec
option enables RSpec matchers for your step definitions. If you used the -O
flag when you generated the application, the --skip-database
option will allow the Cucumber generator to proced without a database.yml file.
To reset your application database to a pristine state during testing, Cucumber makes use of Database Cleaner. You’ll need to configure Cucumber to inform Database Cleaner that you are using Mongoid.
Modify the file features/support/env.rb like this:
begin DatabaseCleaner.orm = 'mongoid' DatabaseCleaner.strategy = :truncation rescue NameError raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it." end
Run rake -T
to check that rake tasks for Cucumber are available.
You should be able to run rake cucumber
(or more simply, cucumber
) to run all Cucumber scenarios and steps. If you haven’t written any Cucumber scenarios and steps, you’ll see the message “0 scenarios, 0 steps”.
To learn more about using Cucumber, refer to The Cucumber Book or the free introduction to Cucumber, The Secret Ninja Cucumber Scrolls.
There are two approaches to writing Cucumber scenarios. The newest (and recommended) approach uses Capybara to write the code (“steps”) that turn Cucumber scenarios into executable specifications. Older versions of Cucumber provided a web_steps.rb
file that implemented common features. See the The Training Wheels Came Off by Aslak Hellesøy to understand why the web_steps.rb
approach is no longer recommended.
If you are creating an application template, this step uses the mongoid recipe from the rails_apps_composer repository.
Mongoid provides access to the MongoDB database from Rails.
You may want to check the current instructions for installing Mongoid.
Set up Mongoid with:
$ rails generate mongoid:config
You can use the default Mongoid configuration found in the file config/mongoid.yml.
The Mongoid generator automatically modifies the config/application.rb file to use Mongoid instead of the default ActiveRecord.
It will replace the line:
require 'rails/all'
with:
require "action_controller/railtie" require "action_mailer/railtie" require "active_resource/railtie"
If you are using RSpec, you don’t need the following. Be sure to comment it out unless you are using the default Test::Unit.
# require "rails/test_unit/railtie"
Now you can safely remove the file config/database.yml.
Note that it is no longer necessary (as of 9 June 2010) to modify config/application.rb for Mongoid. The necessary changes to the Rails generators are handled by the Mongoid gem. When you generate a model, Rails will generate a Mongoid Document.
There’s no need to set up the db/seeds.rb file for a default user. You can test the application without a default user.
During testing, if you wish to reset the MongoDB database you can run the command:
$ rake db:drop
Create indexes for the database with:
$ rake db:mongoid:create_indexes
If you’re not using rvm, you should preface each rake command with bundle exec
. You don’t need to use bundle exec
if you are using rvm version 1.11.0 or newer.
You can check that your app 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 the Rails default information page.
Stop the server with Control-C.
If you are creating an application template, this step uses the add_user recipe from the rails_apps_composer repository.
Use the Rails generator to generate a model for a User.
The User will have “name” and “email” attributes. You can add other attributes that you may need. You may also want to generate a controller and views if you are going to edit or delete User attributes. To keep the example simple, we’ll just create a User model without other attributes, controller, routes, or views.
$ rails generate model user provider:string uid:string name:string email:string
The Rails generator will recognize that Mongoid is installed and set up a User model that looks like this:
class User include Mongoid::Document field :provider, :type => String field :uid, :type => String field :name, :type => String field :email, :type => String end
You’ll want to prevent malicious hackers from creating fake web forms that would allow changing of attributes through the mass-assignment operations of update_attributes(attrs) and new(attrs). You’ll need to add this yourself. Modify the file app/models/user.rb and add:
attr_protected :provider, :uid, :name, :email
If you are creating an application template, this step uses the omniauth recipe from the rails_apps_composer repository.
This app uses OmniAuth for user management and authentication. OmniAuth is at https://github.com/intridea/omniauth.
We’ve already used the $ bundle install
command to install the omniauth
and omniauth-twitter
gems. This tutorial assumes you want to authenticate using Twitter. If you want to use other service providers (such as Facebook), you’ll need to install an appropriate gem.
You’ll need an OmniAuth initialization file config/initializers/omniauth.rb set up for the service provider you’ll use. For most service providers, you need to register your application and obtain API keys to use their authentication service. The arguments that you supply may not be the same for each OmniAuth strategy you use (check the documentation for each gem).
For Twitter:
Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, 'KEY', 'SECRET' end
See the OmniAuth wiki for a List of Provider Strategies to determine if gems are available for the services you wish to use. If you don’t see a service you want, try a RubyGems.org search for what you need.
Before you modify the config/initializers/omniauth.rb initialization file to add the API keys you’ve obtained from the service provider, make sure that the file will not be added to your GitHub repository. If you’ve created a public repository and you commit the file with your API Keys, anyone who browses your repo will be able to obtain your API keys and masquerade as your application.
Modify the .gitignore file before commiting the file with your API keys. Add:
config/initializers/omniauth.rb
You’ll need to keep a local copy of the file and recreate it if you replace your local repo with a clone from a remote Git repository.
We’ll use a SessionsController to create and destroy sessions to accommodate logging in and logging out. Use the Rails generator to create a SessionsController:
$ rails generate controller sessions
For now, we’ll set up the SessionsController to simply raise an exception and show the information returned by the service provider when authentication is succesful. Modify the file app/controllers/sessions_controller.rb to look like this:
class SessionsController < ApplicationController def create raise request.env["omniauth.auth"].to_yaml end end
OmniAuth supplies built-in routes for all its supported service providers. For example, the path /auth/twitter
will redirect to Twitter’s website and allow the user to authenticate using Twitter. After successful authentication, OmniAuth triggers a callback URL, such as /auth/twitter/callback
.
We’ll need to set a route for the callback URL. Edit the file config/routes.rb and add:
match '/auth/:provider/callback' => 'sessions#create'
This route redirects to the Sessions controller create
method.
It could be simplifed as match '/auth/twitter/callback' => 'sessions#create'
but by providing a :provider
parameter we can easily enhance the application to handle more than one provider if necessary.
We should also handle authentication failures. OmniAuth provides a failure URL /auth/failure
that we can route to our Sessions controller. Add the following route to the file config/routes.rb:
match '/auth/failure' => 'sessions#failure'
We also want to offer a feature that allows an authenticated user to log out. Add the following route to the file config/routes.rb:
match '/signout' => 'sessions#destroy', :as => :signout
Adding :as => :signout
to the route gives us a signout_path
helper to use in our views.
The next route we’ll add isn’t strictly necessary. We’ll use it for signing in to the application. OmniAuth allows us to directly initiate authentication by clicking a URL link such as /auth/twitter
in any view. However, for a more completely RESTful Sessions controller, we’ll have a new
method that redirects to /auth/twitter
in the Sessions controller. Add the corresponding route to the file config/routes.rb:
match '/signin' => 'sessions#new', :as => :signin
Adding :as => :signin
to the route gives us a signin_path
helper to use in our views.
You can check that your app 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 the default page.
Navigate to http://localhost:3000/auth/twitter and log in with Twitter. You should be redirected to an error page that shows information from the Twitter authentication.
Stop the server with Control-C.
If you are creating an application template, this step uses the omniauth recipe from the rails_apps_composer repository.
Each of the authentication services returns a hash to our application that provides information about the user. The dataset varies with each service provider. We will extract what we need from the hash we receive.
We’ll modify the User model and the Sessions controller to capture data provided by the service provider.
We need a method in the User model that saves a new user to the datastore. Each provider provides user data in a slightly different format, so you may need to modify the file app/models/user.rb accordingly. Add the following method:
def self.create_with_omniauth(auth) create! do |user| user.provider = auth['provider'] user.uid = auth['uid'] if auth['info'] user.name = auth['info']['name'] || "" user.email = auth['info']['email'] || "" end end end
When a visitor authenticates, we will check the datastore to determine if the user’s data has been recorded previously and, if not, we’ll create a new user record. In either case, we’ll add the user to the session and redirect to the application home page with a “Signed In” message.
Replace the create method in the file app/controllers/sessions_controller.rb:
def create auth = request.env["omniauth.auth"] user = User.where(:provider => auth['provider'], :uid => auth['uid']).first || User.create_with_omniauth(auth) session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!" end
We will provide a “Sign Out” feature for the user.
We’ve already added a signout
route to the file config/routes.rb.
Add the following method to the file app/controllers/sessions_controller.rb:
def destroy reset_session redirect_to root_url, :notice => 'Signed out!' end
We will provide a “Sign In” feature for the user.
We’ve already added a signin
route to the file config/routes.rb.
Add the following method to the file app/controllers/sessions_controller.rb:
def new redirect_to '/auth/twitter' end
We’ve already accommodated OmniAuth’s /auth/failure
route in the file config/routes.rb with a redirect to the Sessions controller failure
method. To handle authentication failure, add the following method to the file app/controllers/sessions_controller.rb:
def failure redirect_to root_url, :alert => "Authentication error: #{params[:message].humanize}" end
We need a way to access the currently logged-in user from any controller. We’ll also need helper methods for our views to distinguish anonymous visitors from users who are logged in. Devise offers the methods current_user
, user_signed_in?
, and authenticate_user!
. We’ll use the same method names for consistency.
Additionlly, we’ll add a helper method that restricts access to only th
Modify the file app/controllers/application_controller.rb to look like this:
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user helper_method :user_signed_in? helper_method :correct_user? private def current_user begin @current_user ||= User.find(session[:user_id]) if session[:user_id] rescue Mongoid::Errors::DocumentNotFound nil end end def user_signed_in? return true if current_user end def correct_user? @user = User.find(params[:id]) unless current_user == @user redirect_to root_url, :alert => "Access denied." end end def authenticate_user! if !current_user redirect_to root_url, :alert => 'You need to sign in for access to this page.' end end end
If you are creating an application template, this step uses the home_page recipe from the rails_apps_composer repository.
Delete the default home page from your application:
$ rm public/index.html
Create the first page of the application. Use the Rails generate command to create a “home” controller and a “views/home/index” page.
$ rails generate controller home index
If you’re using the default template engine, you’ll find an erb file with placeholder content:
app/views/home/index.html.erb
If you’re using Haml, you’ll find a haml file with placeholder content:
app/views/home/index.html.haml
Now, you have to set a route to your home page. Edit the file config/routes.rb and replace:
get "home/index"
with
root :to => 'home#index'
We’ll add some content to the home page in the next step.
You can check that your app 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 your new home page.
Stop the server with Control-C.
If you are creating an application template, this step uses the home_page_users recipe from the rails_apps_composer repository.
Modify the file controllers/home_controller.rb and add:
def index @users = User.all end
Modify the file app/views/home/index.html.erb and add:
<h3>Home</h3> <% @users.each do |user| %> <p>User: <%= user.name %> </p> <% end %>
At this point, you may want to know if an authenticated user is saved to the MongoDB database.
You can check that your app runs properly by entering the command
$ rails server
To see your application in action, open a browser window and navigate to http://localhost:3000/auth/twitter.
After authenticating with Twitter, you should see your user name on the home page.
Stop the server with Control-C.
If you are creating an application template, this step uses the html5 recipe from the rails_apps_composer repository
We’ll create a very simple stylesheet with styling for a horizontal menu and flash messages.
Rename the app/assets/stylesheets/application.css file as app/assets/stylesheets/application.css.scss.
Add stylesheet rules to the application.css.scss file:
header nav ul { list-style: none; margin: 0 0 2em; padding: 0; } header nav ul li { display: inline; } #flash_notice, #flash_alert { padding: 5px 8px; margin: 10px 0; } #flash_notice { background-color: #CFC; border: solid 1px #6C6; } #flash_alert { background-color: #FCC; border: solid 1px #C66; }
If you are creating an application template, this step uses the application_layout recipe from the rails_apps_composer repository.
Rails will use the layout defined in the file app/views/layouts/application.html.erb or app/views/layouts/application.html.haml as a default for rendering any page.
You’ll want to include flash messages for errors and notifications. Set up your application layout by modifying the default as described in the instructions for the Rails default application layout.
If you are adding navigation links, this step uses the navigation recipe from the rails_apps_composer repository.
You will want to add navigation links to the application layout for the sign-in and sign-out actions.
Create a app/views/shared/ directory. Then create the file app/views/shared/_navigation.html.erb and add:
<% if user_signed_in? %> <li> Logged in as <%= current_user.name %> </li> <li> <%= link_to('Logout', signout_path) %> </li> <% else %> <li> <%= link_to('Login', signin_path) %> </li> <% end %>
Then use these partials in your app/views/layouts/application.html.erb file, like this:
<body> <ul class="hmenu"> <%= render 'shared/navigation' %> </ul> <% flash.each do |name, msg| %> <% if msg.is_a?(String) %> <%= content_tag :div, msg, :id => "flash_#{name}" %> <% end %> <% end %> <%= yield %>
For Haml, modify app/views/layouts/application.html.haml like this:
%body %ul.hmenu = render 'shared/navigation' - flash.each do |name, msg| - if msg.is_a?(String) = content_tag :div, msg, :id => "flash_#{name}" = yield
Test the app with the command
$ rails server
Open a browser window and navigate to http://localhost:3000/.
You should see login and logout links on the home page.
Stop the server with Control-C.
You’ll want to see how authentication can be used to control access to restricted pages. We’ll add a user profile page and set up access control so only the authorized user can see his or her own profile.
If you are creating an application template, this step uses the users_page recipe from the rails_apps_composer repository.
Use the Rails generate command to create a “users” controller and a “views/user/show” page.
$ rails generate controller users show
Note that “users” is plural when you create the controller.
Modify the file controllers/users_controller.rb and add:
before_filter :authenticate_user! before_filter :correct_user? def show @user = User.find(params[:id]) end
The file config/routes.rb has already been modified to include:
get "users/show"
Remove that and replace it with:
resources :users
Modify the file app/views/users/show.html.erb to look like this:
<h3>User Profile</h3> <p>Name: <%= @user.name %></p> <p>Email: <%= @user.email if @user.email %></p>
For Haml, modify app/views/users/show.html.haml to look like this:
%h3 User Profile %p Name: #{@user.name} %p Email: #{@user.email if @user.email}
Modify the file app/views/home/index.html.erb to look like this:
<h3>Home</h3> <% @users.each do |user| %> <p>User: <%=link_to user.name, user %></p> <% end %>
For Haml, modify app/views/home/index.html.haml to look like this:
%h3 Home - @users.each do |user| %p User: #{link_to user.name, user}
Test the app with the command
$ rails server
Open a browser window and navigate to http://localhost:3000/.
If you log in, you should be able to click through to see your user profile page.
Stop the server with Control-C.
If you are creating an application template, this step uses the omniauth_email recipe from the rails_apps_composer repository.
Twitter and LinkedIn do not provide the user’s email address. GitHub only provides an email address if the user specified a public email address. If you need the user’s email address, you can add a feature to request it when they authenticate.
Modify the file controllers/users_controller.rb and add an edit
method:
def edit @user = User.find(params[:id]) end
Add an update
method:
def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) redirect_to @user else render :edit end end
There’s no need to modify the routes file to include the new actions. The edit
and update
actions are automatically generated by the resources :users
route in the file config/routes.rb.
Create a file app/views/users/edit.html.erb to look like this:
<%= form_for(@user) do |f| %> <%= f.label :email %> <%= f.text_field :email %> <br /> <%= f.submit "Sign in" %> <% end %>
For Haml, create a file app/views/users/edit.html.haml to look like this:
= form_for(@user) do |f| = f.label :email = f.text_field :email %br/ = f.submit "Sign in"
Change the create
method in the file app/controllers/sessions_controller.rb to look like this:
def create auth = request.env["omniauth.auth"] user = User.where(:provider => auth['provider'], :uid => auth['uid']).first || User.create_with_omniauth(auth) session[:user_id] = user.id if !user.email redirect_to edit_user_path(user), :alert => 'Please enter your email address.' else redirect_to root_url, :notice => 'Signed in!' end end
Test the app with the command
$ rails server
Open a browser window and navigate to http://localhost:3000/.
Log out and then log in. If you log in with Twitter, you should see a page requesting your email address.
Stop the server with Control-C.
Several unneeded files are generated in the process of creating a new Rails application.
Additionally, you may want to prevent search engines from indexing your website if you’ve deployed it publicly while still in development.
See instructions for cleaning up unneeded files in Rails and banning spiders.
If you are creating an application template, this step uses the cleanup recipe from the rails_apps_composer repository.
You can check that your app runs properly by entering the command
$ rails server
To see your application in action, open a browser window and navigate to http://localhost:3000/.
Stop the server with Control-C.
For your convenience, here are instructions for deploying your app to Heroku. Heroku provides low cost, easily configured Rails application hosting.
This concludes the tutorial for creating a Ruby on Rails web application that requires Rails 3 and uses Mongoid for data storage and OmniAuth for authentication.
Daniel Kehoe (http://danielkehoe.com/) implemented the application and wrote the tutorial.
Was this useful to you? Follow me on Twitter:
rails_apps
and tweet some praise. I’d love to know you were helped out by the tutorial.
Any issues? Please create an Issue on GitHub.
Comments
Is this helpful? Your encouragement fuels the project. Please tweet or add a comment. Couldn't get something to work? For the example apps and tutorials, it's best to open an issue on GitHub so we can help you.
comments powered by Disqus