rails/lib/authenticated_system.rb
module AuthenticatedSystem
protected
# Returns true or false if the user is logged in.
def logged_in?
!!current_user
end
# Accesses the current user from the session.
# Future calls avoid the database because nil is not equal to false.
def current_visitor
current_user || User.anonymous
end
# Redirect as appropriate when an access request fails.
#
# The default action is to redirect to the login screen.
#
# Override this method in your controllers if you want to have special
# behavior in case the user is not authorized
# to access the requested action. For example, a popup window might
# simply close itself.
def access_denied
respond_to do |format|
format.html do
# this is the warden way of failing a log in
throw(:warden)
end
# format.any doesn't work in rails version < http://dev.rubyonrails.org/changeset/8987
# you may want to change format.any to e.g. format.any(:js, :xml)
format.any do
request_http_basic_authentication 'Web Password'
end
end
end
# Store the URI of the current request in the session.
#
# We can return to this location by calling #redirect_back_or_default.
def store_location
session[:return_to] = request.fullpath
end
# Redirect to the URI stored by the most recent store_location call or
# to the passed default. Set an appropriately modified
# after_filter :store_location, :only => [:index, :new, :show, :edit]
# for any controller you want to be bounce-backable.
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
# Inclusion hook to make #current_visitor and #logged_in?
# available as ActionView helper methods.
def self.included(base)
base.send :helper_method, :current_visitor, :logged_in? if base.respond_to? :helper_method
end
#
# Logout
#
# This is ususally what you want; resetting the session willy-nilly wreaks
# havoc with forgery protection, and is only strictly necessary on login.
# However, **all session state variables should be unset here**.
def logout_keeping_session!
# when passed a specific scope, devise keeps the session
sign_out(:user)
# explicitly kill any other session variables you set
end
# The session should only be reset at the tail end of a form POST --
# otherwise the request forgery protection fails. It's only really necessary
# when you cross quarantine (logged-out to logged-in).
def logout_killing_session!
logout_keeping_session!
reset_session
end
end