Skip to content

Instantly share code, notes, and snippets.

@timcheadle
Last active August 29, 2015 13:56
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 timcheadle/8864397 to your computer and use it in GitHub Desktop.
Save timcheadle/8864397 to your computer and use it in GitHub Desktop.
Devise + Omniauth + Google Apps (without passwords)
<% if user_signed_in? %>
<p><%= current_user.email %></p>
<%= link_to 'Log Out', destroy_user_session_path %>
<% else %>
<p>You are not signed in.</p>
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_apps) %>
<% end %>
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Omniauthable
t.string :provider, :null => false, :default => ""
t.string :uid, :null => false, :default => ""
t.string :email, :null => false, :default => ""
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.timestamps
end
add_index :users, :email, :unique => true
end
end
require 'omniauth-google-apps'
Devise.setup do |config|
# ...
# Omniauth for Google Apps SSO
config.omniauth :google_apps, domain: 'umbabox.com'
end
# Devise
gem 'devise', '~> 3.0.1'
# OpenID (for Google Apps SSO)
gem 'omniauth-google-apps'
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
skip_before_action :verify_authenticity_token
def google_apps
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_google_apps_oauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
else
session["devise.google_apps_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
devise_scope :user do
get 'sign_in', :to => 'pages#index', :as => :new_user_session
get 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
end
class User < ActiveRecord::Base
devise :rememberable, :trackable,
:omniauthable, :omniauth_providers => [:google_apps]
def self.find_for_google_apps_oauth(auth)
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
end
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.google_apps_data"] && session["devise.google_apps_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment