Skip to content

Instantly share code, notes, and snippets.

@stevehanson
Created June 17, 2016 22:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevehanson/6871b01e34af4ca15fcbf9006d12feb2 to your computer and use it in GitHub Desktop.
Save stevehanson/6871b01e34af4ca15fcbf9006d12feb2 to your computer and use it in GitHub Desktop.
Rails -- Google Sign In
# Create an app in the Google API console and paste ID and secret here
GOOGLE_CLIENT_ID=xxxxx
GOOGLE_CLIENT_SECRET=xxxxx
class ApplicationController
before_action :set_user
protected
def require_authentication!
redirect_to root_path unless @current_user
end
def set_user
@current_user = User.find(session[:current_user_id]) if session[:current_user_id]
end
end
# add these gems
gem "omniauth"
gem "omniauth-google-oauth2"
# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
OmniAuth.config.logger = Rails.logger
end
class RandomController < ApplicationController
# this is how you secure your routes
before_action :require_authentication!
end
# config/routes.rb
# this is an omniauth-specific endpoint
get '/auth/:provider/callback', to: 'sessions#create'
class SessionsController < ApplicationController
def create
user = User.find_or_create_by(email: google_params[:info][:email]) do |user|
user.name = google_params[:info][:name],
user.domain = google_params[:extra][:raw_info][:hd],
user.uid = google_params[:uid],
user.avatar_url = google_params[:info][:image]
end
if user.valid_user?
session[:current_user_id] = user.id
redirect_to root_path
else
flash[:notice] = "Error logging in.<br>Please request access."
redirect_to login_path
end
end
private
def google_params
@google_params ||= request.env['omniauth.auth']
end
end
class User < ActiveRecord::Base
validates :name, presence: true
validates :email, presence: true, uniqueness: true
validates :uid, presence: true, uniqueness: true
def has_access?
email.end_with? "mydomain.com"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment