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

Get the Current url in ruby on rails

request.refererrequest.fullpathrequest.fullpath.split("?")[0]request.referer or request.env['HTTP_REFERER'] your controller to get the referer url. 

--------------------
request.original_url
request.url
request.host_with_port
<link rel="canonical" href="<%= request.url %>" />
<%=request.path%>
How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri only returns the relative URL.
request.env['REQUEST_URI']

 For Rails 3.2 or Rails 4 you should use request.original_url to get the current URL. More detail.

For Rails 3: You want "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2: You want request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).?

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).) In rails?


1)change the gemfile in mysql version
 gem 'mysql2'

2)Change to mysql2 version
 gem 'mysql2','0.3.20'

Active Scaffold : Add radio buttons to your form ruby on rails ?

Active Scaffold : Add radio buttons to your form ruby on rails ?

The way to add radio buttons to your active scaffold create/update from is as shown below

#Controller

class UsersController < ApplicationController
active_scaffold :user do |config|
config.label = “Users”
config.columns = [:name, :gender]
config.columns[:gender].form_ui = :radio
config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']]
end
end