Skip to content

Instantly share code, notes, and snippets.

@stevesohcot
Created January 30, 2016 19:18
Show Gist options
  • Save stevesohcot/b161cf3f88eb9b9da3d3 to your computer and use it in GitHub Desktop.
Save stevesohcot/b161cf3f88eb9b9da3d3 to your computer and use it in GitHub Desktop.
OmniAuth - Application Controller
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
#protect_from_forgery with: :exception
before_action :require_authentication # will happen for ALL controllers/actions
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
# this is a macro (trick) to allow you to use the to use the method in the view
helper_method(:current_user)
def login(user)
# used in both activate and sessions
session[:user_id] = user.id
# Track the user logged in - perhaps with Segment.IO / MixPanel
end
def logged_in?
!logged_out?
end
def logged_out?
current_user.nil?
end
def remember_me(user)
cookies.signed[:user_id] = { value: user.id, expires: 6.months.from_now }
cookies.signed[:user_hash] = { value: user.user_hash, expires: 6.months.from_now }
end
def check_if_remembered
# If the user is logged out, but the cookies indicate they could be logged in,
# then authenticate them
user_id_attempted = cookies.signed[:user_id]
user_hash_attempted = cookies.signed[:user_hash]
begin
u = User.find(user_id_attempted)
real_hash = u.user_hash
rescue StandardError
real_hash = ''
end
if user_hash_attempted == real_hash then
login(u)
end
end
def forget_me
cookies.delete :user_id
cookies.delete :user_hash
end
def require_authentication
if logged_out?
check_if_remembered
end
if current_user
# they're already logged in
else
# they're not logged in
redirect_to signup_url, :alert => "Please sign up or log in first"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment