Skip to content

Instantly share code, notes, and snippets.

@efalcao
Created December 8, 2008 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efalcao/33540 to your computer and use it in GitHub Desktop.
Save efalcao/33540 to your computer and use it in GitHub Desktop.
module Authentication
def self.included(base)
base.class_eval <<-EVAL
before_filter :authenticate
include InstanceMethods
helper_method :current_user
helper_method :current_account
helper_method :current_account_user
EVAL
end
module InstanceMethods
def authenticate
if current_user && current_user.confirmation_key?
flash[:notice] = "Please set a password before continuing"
redirect_to edit_password_path
end
unless current_user
if [Mime::ATOM, Mime::RSS, Mime::JSON, Mime::XML].include? request.format
logger.debug "#{current_user.inspect}"
request_http_basic_authentication and return false
else
flash[:error] = "Please login"
redirect_to new_session_path
end
return false
end
current_user
end
def current_user
@current_user ||= if session[:user_id]
User.find(session[:user_id])
elsif cookies[:auth_token]
user = User.find_by_auth_token(cookies[:auth_token])
return false unless user
session[:user_id] = user.id
user
elsif params[:token] && [Mime::RSS, Mime::ATOM].include?(request.format)
User.find_by_rss_token(params[:token])
elsif [Mime::ATOM, Mime::RSS, Mime::JSON, Mime::XML].include? request.format
authenticate_with_http_basic {|e,p| User.authenticate_by_email_and_password(e,p)}
else
false
end
end
def current_account
@current_account ||= if current_user
if current_user.accounts.size == 1
current_user.accounts.first
elsif controller_name == "accounts" && params[:id]
current_user.accounts.find(params[:id])
elsif params[:account_id]
current_user.accounts.find(params[:account_id])
end
end
end
def current_account_user
@current_account_user ||= if current_account
current_account.account_users.find(:first, :conditions => {:user_id => current_user.id})
else
false
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment