Skip to content

Instantly share code, notes, and snippets.

@stevehanson
Last active February 4, 2021 23:06
Show Gist options
  • Save stevehanson/f55fd75b669d8c79a1ef to your computer and use it in GitHub Desktop.
Save stevehanson/f55fd75b669d8c79a1ef to your computer and use it in GitHub Desktop.
Rails – Simple Google Login
class AdminController < ApplicationController
before_filter :set_user, :authorized?
layout "admin"
private
def set_user
@current_user = User.find(session[:current_user_id]) if admin?
end
def current_user
set_user unless @current_user
@current_user
end
def authorized?
#unless current_user.has_role? :admin
unless admin?
flash[:error] = "You are not authorized to view this page."
redirect_to admin_login_path
end
end
def admin?
session[:current_user_id]
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :uid
t.string :email
t.string :domain
t.string :image_url
t.timestamps
end
end
end
gem "omniauth"
gem "omniauth-google-oauth2"
# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
OmniAuth.config.logger = Rails.logger
end
get '/auth/:provider/callback', to: 'sessions#create'
class SessionsController < ApplicationController
skip_before_action :validate_user, only: :create
def create
user = User.find_or_create_by(email: google_params[:info][:email]) do |user|
user.name = google_params[:info][:name],
user.domain = google_params[:extra][:raw_info][:hd],
user.uid = google_params[:uid],
user.avatar_url = google_params[:info][:image]
end
if user.valid_user?
session[:current_user_id] = user.id
redirect_to :admin_root
else
flash[:notice] = "Error logging in.<br>Please request access."
redirect_to :admin_login
end
end
private
def google_params
@google_params ||= request.env['omniauth.auth']
end
end
class User < ActiveRecord::Base
validates :name, presence: true
validates :email, presence: true, uniqueness: true
validates :uid, presence: true, uniqueness: true
validates :domain, presence: true, inclusion: {
in: ["mycompany.com"]
}
def valid_user?
valid? && has_access?
end
def has_access?
User.admin_emails.include?(email)
end
def can_post?
User.super_admin_emails.include?(email)
end
private
def self.super_admin_emails
[
"[email protected]",
"[email protected]"
] + admin_super_env_emails
end
def self.admin_emails
[
"[email protected]",
"[email protected]"
] + admin_env_emails + super_admin_emails
end
def self.admin_env_emails
ENV["HAS_ADMIN_ACCESS"].to_s.split(",").map(&:strip)
end
def self.admin_super_env_emails
ENV["HAS_SUPER_ACCESS"].to_s.split(",").map(&:strip)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment