Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Authenticate Active Admin + Sidekiq w/ OmniAuth (Google)
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
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
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