Created
June 27, 2019 21:55
-
-
Save phil-monroe/345b5bfcac4e37df52429fa5e3f3aeab to your computer and use it in GitHub Desktop.
Authenticate Active Admin + Sidekiq w/ OmniAuth (Google)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Admin::OauthController < ApplicationController | |
def self.authenticated?(request) | |
session = request.session | |
session[:email].present? && session[:authenticated_at].present? && (Time.at(session[:authenticated_at]) + 24.hours).future? | |
end | |
def self.current_user(request) | |
session = request.session | |
OpenStruct.new(email: session[:email], | |
name: session[:name], | |
first_name: session[:first_name], | |
last_name: session[:last_name], | |
image: session[:image]) | |
end | |
def authenticate | |
session[:return_path] = request.fullpath | |
redirect_to '/auth/google_oauth2' | |
end | |
def google | |
auth = request.env['omniauth.auth'] | |
if auth.dig('extra', 'id_info', 'hd') == 'maven-labs.com' && auth.dig('extra', 'id_info', 'email_verified') | |
session[:uid] = auth.dig('uid') | |
session.merge!(auth.dig('info')) | |
session[:authenticated_at] = auth.dig('extra', 'id_info', 'iat') | |
redirect_to session.delete(:return_path) || admin_root_path | |
else | |
logout | |
end | |
end | |
def logout | |
session.clear | |
redirect_to 'https://sellwithami.com' | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.application.config.middleware.use OmniAuth::Builder do | |
provider :google_oauth2, ENV.fetch('GOOGLE_KEY'), ENV.fetch('GOOGLE_SECRET'), | |
scope: 'email, profile', hd: REQUIRED_GOOGLE_DOMAIN | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sidekiq/web' | |
Rails.application.routes.draw do | |
get 'auth/google_oauth2/callback', to: 'admin/oauth#google' | |
get 'auth/logout', to: 'admin/oauth#logout' | |
constraints(Admin::OauthController.method(:authenticated?)) do | |
ActiveAdmin.routes(self) | |
mount Sidekiq::Web => '/admin/sidekiq', as: 'sidekiq' | |
end | |
get '/admin', to: 'admin/oauth#authenticate' | |
get '/admin/*path', to: 'admin/oauth#authenticate' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment