Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Last active December 15, 2016 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmajstor/095ad8a1ce683b7c145de46872563ef3 to your computer and use it in GitHub Desktop.
Save zmajstor/095ad8a1ce683b7c145de46872563ef3 to your computer and use it in GitHub Desktop.
current_user helpers without Devise
class ApplicationController < ActionController::Base
include SessionsHelper
Unauthorized = Class.new(StandardError)
def authorize_user!
raise Unauthorized unless current_user
end
end
# ...
match '/auth/logout', to: 'sessions#destroy', via: [:get, :delete], as: 'logout'
match '/auth/failure', to: 'sessions#auth_failure', via: [:get, :post]
match '/error', to: 'sessions#auth_failure', via: [:get, :post]
match '/auth/:provider/callback', to: 'sessions#create', via: [:get, :post], as: :auth_callback
# Omniauth login with provider path: auth_path('twitter')
get '/auth/:provider', to: -> env { [404, {}, ["Not Found"]] }, as: 'auth'
# ...
module SessionsHelper
def sign_in(user)
reset_session
self.current_user = user
end
def sign_out
self.current_user = nil
reset_session
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user = user
if user.present? && user.persisted?
session[:user_id] = user.id
else
session.delete(:user_id)
nil
end
end
def current_user
@current_user ||= User.find_by(id: session[:user_id])
rescue ActiveRecord::RecordNotFound
self.current_user = nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment