Created
December 10, 2013 23:21
-
-
Save tatey/7902231 to your computer and use it in GitHub Desktop.
Splitting out authentication from the controller into a distinct class. Easier to unit test and minimises the footprint in ApplicationController.
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 | |
protect_from_forgery with: :exception | |
delegate :user, :user=, to: :authentication, prefix: 'current' | |
delegate :sign_in, :signed_in?, :sign_out, to: :authentication | |
helper_method :current_user | |
helper_method :signed_in? | |
private | |
def authentication | |
@authentication ||= Authentication.new session | |
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
# Sign in or sign out a user by persisting their +authentication_token+ | |
# in the session. | |
class Authentication | |
attr_reader :session | |
attr_writer :user | |
# Creates a new Authentication. | |
# | |
# @param session [ActionController::Session] Session from the request. | |
def initialize session, options = {} | |
@session = session | |
end | |
def signed_in? | |
user.present? | |
end | |
# Sign in the +user+ by persisting their +authentication_token+. | |
# | |
# @param user [User] The user to sign in. | |
# @return [User] The signed in user. | |
def sign_in user | |
user.generate_authentication_token | |
session[:authentication_token] = user.authentication_token | |
@user = user | |
end | |
# Sign out the +user+ by deleteing their +authentication_token+ | |
# from the session. | |
# | |
# @return [void]. | |
def sign_out | |
session.delete :authentication_token | |
@user = nil | |
end | |
# Finds the +user+ by their +authentication_token+. | |
# | |
# @return [User, nil] User if the user can be found, otherwise nil. | |
def user | |
@user ||= find_user_from_session | |
end | |
private | |
def find_user_from_session | |
User.find_by_authentication_token token if token? | |
end | |
def token | |
session[:authentication_token] | |
end | |
def token? | |
token.present? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment