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

Create dynamic sitemap on ruby on rails

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site. It’s basically a XML file describing all URLs in your page: The following example shows a Sitemap that contains just one URL and uses all optional tags. The optional tags are in italics. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">    <url>       <loc>http://www.example.com/</loc>       <lastmod>2005-01-01</lastmod>       <changefreq>monthly</changefreq>     ...

Omniauth Linked in Ruby On Rails

def get_linkedin_user_data      omniauth = request.env["omniauth.auth"]      dat=omniauth.extra.raw_info      linked_app_key = "xxxxxxx"      linkedin_secret_key = "yyyyyyy"      client = LinkedIn::Client.new(linked_app_key,linkedin_secret_key)      client.authorize_from_access(omniauth['credentials']['token'],omniauth['credentials']['secret'])      connections=client.connections(:fields => ["id", "first-name", "last-name","picture-url"])      uid=omniauth['uid']      token=omniauth["credentials"]["token"]      secret=omniauth["credentials"]["secret"]   #linked user data     omniauth = request.env["omniauth.auth"]      data             = omniauth.info      user_name...

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