Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.