public
Created

Rails Omniauth Google

  • Download Gist
application_controller.rb
Ruby
1 2 3 4
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
homepage.rb
Ruby
1
=link_to "Login", '/auth/google', class: "btn btn-large btn-primary"
omniauth.rb
Ruby
1 2 3
Rails.application.config.middleware.use OmniAuth::Builder do
provider :open_id, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id'
end
routes.rb
Ruby
1
match 'auth/google/callback', to: 'sessions#create'
session_controller.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class SessionsController < ApplicationController
 
def create
user = User.from_omniauth(env["omniauth.auth"]["info"])
if user.save
sign_in user
redirect_to user, flash: { success: "You have successfully signed in."}
else
redirect_to root_path, flash: { error: "You failed to sign in" }
end
end
 
def destroy
sign_out
redirect_to root_path
end
 
end
sessions_helper.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class SessionsController < ApplicationController
 
def create
user = User.from_omniauth(env["omniauth.auth"]["info"])
if user.save
sign_in user
redirect_to user, flash: { success: "You have successfully signed in."}
else
redirect_to root_path, flash: { error: "You must sign in with your Maluuba account." }
end
end
 
def destroy
sign_out
redirect_to root_path
end
 
end
user.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
class User < ActiveRecord::Base
 
before_save :create_remember_token
 
validates :name, presence: true
 
validates :email, presence:true,
uniqueness: { case_sensitive: false }
 
 
def self.from_omniauth(auth_info)
where(auth_info.slice("email", "name")).first ||
create_from_omniauth(auth_info)
end
 
def self.create_from_omniauth(auth_info)
new do |user|
user.email = auth_info[:email]
user.name = auth_info[:name]
end
end
 
private
 
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.