|
| 1 | +require 'devise_imapable/strategy' |
| 2 | + |
| 3 | +module Devise |
| 4 | + module Models |
| 5 | + # LDAP Module, responsible for validating the user credentials via LDAP. |
| 6 | + # |
| 7 | + # Examples: |
| 8 | + # |
| 9 | + # User.authenticate('[email protected]', 'password123') # returns authenticated user or nil |
| 10 | + # User.find(1).valid_password?('password123') # returns true/false |
| 11 | + # |
| 12 | + module LdapAuthenticatable |
| 13 | + def self.included(base) |
| 14 | + base.class_eval do |
| 15 | + extend ClassMethods |
| 16 | + |
| 17 | + attr_accessor :password |
| 18 | + end |
| 19 | + end |
| 20 | + |
| 21 | + # Set password to nil |
| 22 | + def clean_up_passwords |
| 23 | + self.password = nil |
| 24 | + end |
| 25 | + |
| 26 | + # Checks if a resource is valid upon authentication. |
| 27 | + def valid_ldap_authentication?(password) |
| 28 | + Devise::LdapAdapter.valid_credentials?(self.login, password) |
| 29 | + end |
| 30 | + |
| 31 | + module ClassMethods |
| 32 | + # Authenticate a user based on configured attribute keys. Returns the |
| 33 | + # authenticated user if it's valid or nil. |
| 34 | + def authenticate_with_ldap(attributes={}) |
| 35 | + return unless attributes[:login].present? |
| 36 | + conditions = attributes.slice(:login) |
| 37 | + |
| 38 | + unless conditions[:login] && conditions[:login].include?('@') |
| 39 | + conditions[:login] = "#{conditions[:login]}" |
| 40 | + end |
| 41 | + |
| 42 | + resource = find_for_ldap_authentication(conditions) || new(conditions) |
| 43 | + |
| 44 | + if resource.try(:valid_ldap_authentication?, attributes[:password]) |
| 45 | + resource.new_record? ? create(conditions) : resource |
| 46 | + end |
| 47 | + end |
| 48 | + |
| 49 | + protected |
| 50 | + |
| 51 | + # Find first record based on conditions given (ie by the sign in form). |
| 52 | + # Overwrite to add customized conditions, create a join, or maybe use a |
| 53 | + # namedscope to filter records while authenticating. |
| 54 | + # Example: |
| 55 | + # |
| 56 | + # def self.find_for_imap_authentication(conditions={}) |
| 57 | + # conditions[:active] = true |
| 58 | + # find(:first, :conditions => conditions) |
| 59 | + # end |
| 60 | + # |
| 61 | + def find_for_ldap_authentication(conditions) |
| 62 | + find(:first, :conditions => conditions) |
| 63 | + end |
| 64 | + end |
| 65 | + end |
| 66 | + end |
| 67 | +end |
0 commit comments