Created
July 22, 2014 09:56
-
-
Save Driptap/e053593eeca829fd9e33 to your computer and use it in GitHub Desktop.
Current user concern used in various Ruby on Rails projects
This file contains 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 CurrentUser | |
extend ActiveSupport::Concern | |
included do | |
helper_method :current_user | |
end | |
def current_user | |
return @current_user if defined?(@current_user) | |
@current_user = User.find_by(id: session[:id]) | |
end | |
def sign_in(user) | |
user_id = user.respond_to?(:id) ? user.id : user | |
session[:id] = user_id | |
end | |
def sign_out | |
session[:id] = nil | |
cookies[:auth_token] = nil | |
end | |
def require_user | |
redirect_to user_not_required_path, notice: "You must be logged in to access this page" if current_user.blank? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment