Monday, 11 May 2015

Simple Google Authentication using Omniauth & oauth2 - Part 2

In my last post we saw how we can set up omniauth for our rails application, now we'll see how we can implement the login and logout functionality using google account. If you haven't read the first part, you might want to take a look at that first.

In your view, we'll be doing it in the index view, paste this line

<%= link_to "Login with Google", "/auth/google" %>

and in your routes.rb file, you need to add this line

match "/auth/:provider/callback" => "sessions#create"

Now generate a sessions controller, and we'll have to define a create method in the sessions_controller.rb file

def create
auth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!"
end

We still have to define the create_with_omniauth method in User model. So first, lets generate a User model with provider, uid, and name (all three of string datatype). Now in the user.rb file, add

def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
end 
end

Now in your controller's index method, assign the user to a variable @current_user, so that we can access it from our index view

def index
@current_user = User.find(session[:user_id]) if session[:user_id]
end

Update your index view to show the logged in user's name

<% if @current_user %>
Welcome <%= current_user.name %>!  
<% else %> 
<%= link_to "Login with Google", "/auth/google" %> 
<% end %>

You can go ahead and try the login feature in your application. Next what we would want to do is a logging out functionality, which is quite simple. Head over to your routes.rb file and add this line

match "/logout" => "sessions#destroy", :as => :logout

Add a destroy method in your sessions controller

def destroy
session[:user_id] = nil
redirect_to root_url, :notice => "Signed out!" 
end

And now the final piece of the puzzle, update your index view to reflect the changes.

<% if @current_user %>
Welcome <%= current_user.name %>!  
<%= link_to "logout", logout_path %>
<% else %> 
<%= link_to "Login with Google", "/auth/google" %> 
<% end %>

No comments:

Post a Comment