1 module AuthenticatedSystem
7 # Accesses the current user from the session.
9 @current_user ||= session[:user] ? User.find_by_id(session[:user]) : nil
12 # Store the given user in the session.
13 def current_user=(new_user)
14 session[:user] = new_user.nil? ? nil : new_user.id
15 @current_user = new_user
18 # Check if the user is authorized.
20 # Override this method in your controllers if you want to restrict access
21 # to only a few actions or if you want to check if the user
22 # has the correct rights.
26 # # only allow nonbobs
27 # def authorize?(user)
34 # Check whether or not to protect an action.
36 # Override this method in your controllers if you only want to protect
41 # # don't protect the login and the about method
42 # def protect?(action)
43 # if ['action', 'about'].include?(action)
53 # Filter method to enforce a login requirement.
55 # To require logins for all actions, use this in your controllers:
57 # before_filter :login_required
59 # To require logins for specific actions, use this in your controllers:
61 # before_filter :login_required, :only => [ :edit, :update ]
63 # To skip this in a subclassed controller:
65 # skip_before_filter :login_required
68 # Skip this filter if the requested action is not protected
69 return true unless protect?(action_name)
71 # Check if user is logged in and authorized
72 return true if logged_in? and authorized?(current_user)
74 # Store current location so that we can redirect back after login
77 # Call access_denied for an appropriate redirect and stop the filter
79 access_denied and return false
82 # Redirect as appropriate when an access request fails.
84 # The default action is to redirect to the login screen.
86 # Override this method in your controllers if you want to have special
87 # behavior in case the user is not authorized
88 # to access the requested action. For example, a popup window might
89 # simply close itself.
91 redirect_to :controller => 'user', :action => 'login'
94 # Store the URI of the current request in the session.
96 # We can return to this location by calling #redirect_back_or_default.
98 session[:return_to] = request.request_uri
101 # Redirect to the URI stored by the most recent store_location call or
102 # to the passed default.
103 def redirect_back_or_default(default)
104 session[:return_to] ? redirect_to_url(session[:return_to]) : redirect_to(default)
105 session[:return_to] = nil
108 # Inclusion hook to make #current_user and #logged_in?
109 # available as ActionView helper methods.
110 def self.included(base)
111 base.send :helper_method, :current_user, :logged_in?