Skip to content

Instantly share code, notes, and snippets.

@mallain
Created September 6, 2010 13:02
Show Gist options
  • Save mallain/567008 to your computer and use it in GitHub Desktop.
Save mallain/567008 to your computer and use it in GitHub Desktop.
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
before_filter :set_locale
# Scrub sensitive parameters from your log
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user, :current_agency, :current_time
before_filter :load_agency_time
layout 'application'
# def resource_controller_translated
# create.flash { "Création effectuée avec succès." }
# update.flash { "Mise à jour effectuée avec succès." }
# destroy.flash { "Suppréssion effectuée avec succès." }
# end
# Define the local for the app
def set_locale
## if params[:locale] is nil then I18n.default_locale will be used
session[:locale] = params[:locale] if params[:locale]
I18n.locale = session[:locale]
end
# Redirect to root_url if CanCan::AccessDenied exception raise
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = I18n.t('unauthorized_access')
redirect_to root_url
end
# Before filter for require a role 'admin'
def require_admin
authorize! :create, User
end
# Before filter for require a role 'poweruser'
def require_poweruser
authorize! :create, CollaboratorNumber
end
private
# Generate a edit or new path
# model as String
# submenu as Symbol
# return new_or_edit_path
def new_or_edit_ressource(model, submenu)
result = ''
@model = model.classify.constantize
@object = @model.by_agency_and_feedback(current_agency, current_time)
ressource = [submenu]
if @object.size == 0
ressource << @model.new
result = new_polymorphic_path(ressource)
else
ressource << @object.first
result = edit_polymorphic_path(ressource)
end
result
end
# Return the current user session
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
# Return the loggued current user
def current_user
return @current_user if defined?(@current_user)
p "Current_user Record : #{current_user_session.record if current_user_session}"
p "Current_user User : #{current_user_session.user if current_user_session}"
@current_user = current_user_session && current_user_session.user
end
# Return the selected agency
def current_agency
session[:agency] ? agency_id = session[:agency] : agency_id = current_user.own_agencies.first
@current_agency = Agency.find(agency_id)
return @current_agency if defined?(current_user)
end
# Return the selected current feedbacktime
def current_time
#TODO Initialize variable feedback_id from last validation feedback
session[:feedback] ? feedback_id = session[:feedback] : feedback_id = Feedback.last.id
@current_time = Feedback.find(feedback_id)
return @current_time if defined?(current_user)
end
# Load all agencies and feedbacks
def load_agency_time
@agencies = Agency.all
@feedbacks = Feedback.all
@min_feedback = Feedback.first_feedback.feedback_time.year
@max_feedback = Feedback.last_feedback.feedback_time.year
end
# Protect controller against no loggued users
def require_user
p "CURRENT USER : #{current_user}"
unless current_user
flash[:notice] = I18n.t('user_session_must_logged_in')
redirect_to login_path
return false
end
end
# Allow no loggued users
def require_no_user
if current_user
redirect_to root_url
return false
end
end
end
class User < ActiveRecord::Base
## Plugins ##
acts_as_authentic do |c|
c.logged_in_timeout = 15.minutes
c.validates_format_of :email, :with => Authlogic::Regex.bd_format_email
end
# Listing roles
ROLES = Ability.roles
## Callbacks ##
before_save :apply_default_password
## Relations ##
has_and_belongs_to_many :agencies
## Validates ##
validates_presence_of :email, :role
validates_inclusion_of :role, :in => ROLES
## Scopes ##
## Methods ##
# Define if the user have the role parameter
def role?(tmpRole)
role.include? tmpRole.to_s
end
# Define if the user have an admin role
def admin?
role? :admin
end
# Define if the user is active or not
def active?
role?(:admin) || role?(:poweruser)
end
# Retrieves user agencies
def own_agencies
result = []
if role?(:admin)
result = Agency.agencies
elsif role?(:poweruser)
result = self.agencies
end
result
end
# Detect if there are multiple agencies to manage
def manage_many_agencies?
own_agencies.count > 1
end
# Check if agency is manage by the user
# param agency_id is a number which represent a primary key id (integer)
def manage_agency?(agency_id)
result = false
begin
a = Agency.find(agency_id)
result = own_agencies.include?(a)
rescue Exception => e
result
end
end
# Define the Distinguished Name for account user on LDAP
def dn
"cn=#{self.email},ou=Persons,ou=B&D,dc=businessdecision,dc=com"
end
protected
# Define a password by default
def apply_default_password
self.password = "424242"
self.password_confirmation = "424242"
end
# Check if the user is authorized to connect on this App
def valid_ldap_credentials?(password_plaintext)
begin
ldap = LdapConnect.new.ldap
ldap.auth self.dn, password_plaintext
ldap.bind # will return false if authentication is NOT successful
rescue Net::LDAP::LdapError => e
#TODO Send a mail to inform the administrator
puts "------------------"
puts "Message: #{e.message}"
puts "------------------"
false
end
end
end
class UserSession < Authlogic::Session::Base
before_validation :check_if_ldap_is_online
# Check the given password with ldap services
verify_password_method :valid_ldap_credentials?
# Authlogic::Session::BruteForceProtection part
consecutive_failed_logins_limit 8
failed_login_ban_for 8.hours
private
def check_if_ldap_is_online
errors.add(I18n.t('ldap_server_offline')) unless LdapConnect.new.online?
end
end
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => :destroy
def index
redirect_to login_url
end
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
session[:feedback] = nil
session[:agency] = nil
flash[:notice] = I18n.t('login_successful')
redirect_to root_url
else
render :action => :new
end
end
def destroy
current_user_session.destroy
session[:feedback] = nil
session[:agency] = nil
flash[:notice] = I18n.t('logout_successful')
redirect_to root_url
end
end
@mallain
Copy link
Author

mallain commented Sep 6, 2010

Rails App about authentification with Authlogic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment