Last active
December 15, 2016 10:39
-
-
Save zmajstor/095ad8a1ce683b7c145de46872563ef3 to your computer and use it in GitHub Desktop.
current_user helpers without Devise
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 ApplicationController < ActionController::Base | |
include SessionsHelper | |
Unauthorized = Class.new(StandardError) | |
def authorize_user! | |
raise Unauthorized unless current_user | |
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
# ... | |
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' | |
# ... |
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
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