forked from activeadmin/activeadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
Log in through OAuth providers
andrewtheskills edited this page Nov 18, 2020
·
2 revisions
Using this gem: https://github.com/zquestz/omniauth-google-oauth2
Your::Application.routes.draw do
devise_config = ActiveAdmin::Devise.config
devise_config[:controllers][:omniauth_callbacks] = 'omniauth_callbacks'
devise_for :users, devise_config
ActiveAdmin.routes(self)
end
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
user = User.from_omniauth request.env["omniauth.auth"]
if user.persisted?
flash.notice = "Signed in!"
sign_in_and_redirect user
else
flash.notice = "We couldn't sign you in because: " + user.errors.full_messages.to_sentence
redirect_to new_user_session_url
end
end
alias_method :google_oauth2, :all
end
class User < ActiveRecord::Base
devise :omniauthable, omniauth_providers: %i[google_oauth2]
# Devise override to ignore the password requirement if the user is authenticated with Google
def password_required?
provider.present? ? false : super
end
def self.from_omniauth(auth)
user = where(email: auth.info.email).first || where(auth.slice(:provider, :uid)).first || new
user.update_attributes provider: auth.provider,
uid: auth.uid,
email: auth.info.email
user.name ||= auth.info.name # note: Devise seems to wrap this in the DB write for session info
user
end
end