Skip to content

Instantly share code, notes, and snippets.

@zosiu
Last active August 29, 2015 14:08
Show Gist options
  • Save zosiu/4ce3d9cd56e0ade478e3 to your computer and use it in GitHub Desktop.
Save zosiu/4ce3d9cd56e0ade478e3 to your computer and use it in GitHub Desktop.
Rails 4 & devise & google oauth2
  • register a new project here
  • set the followings under APIs & auth:
    • Consent screen: fill out the requires fields
    • APIs: Contacts API & Google+ API
    • Creditentials: create a new OAuth client ID
      • AUTHORIZED JAVASCRIPT ORIGINS: HOST (your app host) (protocol prefixed!)
      • AUTHORIZED REDIRECT URI: HOST/auth/google/callback (protocol prefixed!)
  • sign in url is user_omniauth_authorize_path(:google)
Devise.setup do |config|
# ==> OmniAuth Configuration
config.omniauth :google_oauth2,
ENV['GOOGLE_CLIENT_ID'],
ENV['GOOGLE_CLIENT_SECRET'],
name: 'google',
scope: 'email, profile',
prompt: 'select_account',
image_aspect_ratio: 'square',
image_size: 50,
provider_ignores_state: true # hack, see: https://github.com/intridea/omniauth-oauth2/issues/58
# ...
end
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google
@user = User.apply_google_auth request.env['omniauth.auth'], current_user
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
sign_in_and_redirect @user, event: :authentication
end
protected
def new_session_path
root_path
end
def after_omniauth_failure_path_for(_resource_name)
root_path
end
end
Rails.application.routes.draw do
devise_for :users,
path: '',
controllers: { omniauth_callbacks: 'omniauth_callbacks' }
devise_scope :user do
delete 'logout' => 'devise/sessions#destroy', as: 'logout'
end
# ...
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) not null
# admin :boolean default(FALSE)
# active :boolean default(FALSE)
# name :string(255)
# image_url :string(255)
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
devise :omniauthable, omniauth_providers: [:google]
validates :email, :name, :image_url, presence: true
validates :email, uniqueness: true
def self.apply_google_auth(omniauth, _signed_in_resource = nil)
user_info = omniauth.info
User.where(email: user_info['email'])
.first_or_create name: user_info['name'],
image_url: user_info['image']
end
def active_for_authentication?
super && active?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment