Skip to main content

Rails 3, Devise, Omniauth, and Google

Getting authentication through Google in a Rails application is a breeze with the right tools. To get a simple, no-frills authentication system up and running in a Rails 3 application, all you really need is Devise, Omniauth, and a Google API account.

Step 1: Signing up for Google API access

Before being able to wire up authentication in your rails app, you will need to set up a Google App. First, get your API key at:  https://code.google.com/apis/console
If you don’t already have a Google account, you will need to set one up, after that create a project and give it any name you like.


Once you create a project, click on “API Access” and provide details for your OAuth Client. For development purposes, the Home Page URL can be “localhost”.


After all of the details have been set, you will then get access to the screen with all of the information you will for your Rails app. For now, locate the section that contains your Client ID and Client Secret, you will need these later to configure your Rails application. Also make sure you have a redirect URI set to http://localhost:3000//users/auth/google_auth2/callback (unless you are using a different port or local server, in which case, use your computer’s address)

Step 2: Setting up your Rails app

You will need to add the following to your app’s gemfile:

gem 'devise'
gem 'omniauth-google-oauth2'

bundle the new gems and then setup up devise from the command line:

rails g devise:install
rails g devise User

Step 3: Configure the user model and Devise



class User < ActiveRecord::Base

devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable, :omniauth_providers => [:google_oauth2]

attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :provider, :uid, :avatar
end


Adding the Google Omniauth scheme to the app is as simple as adding the following to devise.rb

config.omniauth :google_oauth2, 'APP_ID', 'APP_SECRET'


Where ‘APP_ID’ and ‘APP_SECRET’ are replaced with your app’s actual keys from step 1.
Step 4: Setting up the Routes and Callback Controller

 

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash.notice = "Signed in Through Google!"
sign_in_and_redirect user
else
session["devise.user_attributes"] = user.attributes
flash.notice = "You are almost Done! Please provide a password to finish setting up your account"
redirect_to new_user_registration_url
end
end
end


As you can see from the above code, the OmniauthCallbacksController has only the one ‘google_oauth2′ method. This method instantiates a user from the information retrieved from the omniauth hash that came back from Google. It relies on the “from_omniauth” method that we will have to create on the User model in a moment, but for now it is important to understand that what this method does is, it checks for an existing user with the same credentials, if it finds one, it signs that user in, if it does not, then it redirects to Devise’s new_user_registration_url to complete the registration process because this user does not yet exist.

Next, adjusting the routes to handle this callback is as simple as adding the following to your routes file:

devise_for :users, controllers: { omniauth_callbacks: "omniauth_callbacks" }


Step 5: Finishing up the User Model

Our work is not yet complete, we still need to handle the “from_omniauth” check necessary for the OmniauthCallbacksController in the User model.


class User < ActiveRecord::Base

devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable, :omniauth_providers => [:google_oauth2]

attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :provider, :uid, :avatar
# METHODS ---------------------------------------------
def self.from_omniauth(auth)
if user = User.find_by_email(auth.info.email)
user.provider = auth.provider
user.uid = auth.uid
user
else
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.username = auth.info.name
user.email = auth.info.email
user.avatar = auth.info.image
end
end
end
end


As you can see from the above code, I added one method to the user model to get all of the functionality working properly. The ‘from_omniauth’ method checks to see if a user exists based the on the information retrieved from the auth hash that Omniauth gives us. If a user already exits, the method returns the user and the controller then signs that user in.

If that user does not yet exist, it creates a new user based on the information from Omniauth.
Step 6: Configuring the Views

The final step in this process is to add the login, register, logout, and “sign in with Google” functionality. A basic solution to this is as simple as adding something like the following to your application layout file.


!!!
%html
%head
%title Doris
= stylesheet_link_tag "application", :media => "all"
= javascript_include_tag "application"
= csrf_meta_tags
%body
.login
- if !current_user
= link_to "Sign In", new_user_session_path
\|
= link_to "Register", new_user_registration_path
\| or
= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2)
- else
=current_user.email
\|
= link_to "Log out", destroy_user_session_path, method: :delete
%p.notice= notice
%p.alert= alert
= yield

Comments

Popular posts from this blog

Rails Migration Difference between Text and String

Rails Migration Difference between Text and String ? While working with Rails Migration Difference between Text and String is important to be known to every developer. Columns and their data types are finalized while deciding Table structure. This tutorial will help understand difference between String and Text column type and illustrate how to write Rails Migration implementing the same. You might want to read about database.yml files for specifying database configuration for Rails Application. 1. Concepts When String or Text data type is required?     Whenever you require your column to store information which is lengthy in size (Many characters), you need to consider String or Text data type for the column.     Both of them let you store Many(How Many - will see later) characters Difference between String and Text Considering MySQL database Feature     String     Text Length     1 to 255     ...

Error malloc(): memory corruption nginx with passenger?

Error malloc(): memory corruption nginx with passenger Passenger issue resolving steps :  sudo gem uninstall passenger(uninstall all passenger) sudo gem install passenger sudo passenger-install-nginx-module --auto --auto-download --prefix=/opt/nginx --extra-configure-flags=none Update nginx config file with new passenger version and restart the nginx

rake db migrate with down, up, redo, rollback options in rails

rake db migrate with down, up, redo, rollback options ? rake db migrate - This can be used to migrate your production/test database using various options like up, down, step, redo, version etc. In this tutorial we will learn how all these options can be used with rake tool to migrate the database. What is rake? rake is basically ruby make. i.e. make tool for ruby It has similar functionality to the make tool that you may have used on unix based systems for comopiling running some kind of script. rake allows you to ruby particular task in the environment that you specify. How to Install rake? You can install rake by installing gem 'rake' as, gem install rake Above command will install the latest version of rake tool avaialable. Various rake db migrate commands Operation     Command     Description General     rake db:migrate     This will migrate your database by running migrations that are not run yet Running specific Migra...