/lib/devise_ldap_authenticatable/model.rb

https://github.com/nreckart/devise_ldap_authenticatable · Ruby · 90 lines · 63 code · 16 blank · 11 comment · 8 complexity · 0df9847db5192b876e2814a64d54b91a MD5 · raw file

  1. require 'devise_ldap_authenticatable/strategy'
  2. module Devise
  3. module Models
  4. # LDAP Module, responsible for validating the user credentials via LDAP.
  5. #
  6. # Examples:
  7. #
  8. # User.authenticate('email@test.com', 'password123') # returns authenticated user or nil
  9. # User.find(1).valid_password?('password123') # returns true/false
  10. #
  11. module LdapAuthenticatable
  12. extend ActiveSupport::Concern
  13. included do
  14. attr_reader :current_password, :password
  15. attr_accessor :password_confirmation
  16. end
  17. def login_with
  18. @login_with ||= Devise.mappings[self.class.to_s.downcase.to_sym].to.authentication_keys.first
  19. self[@login_with]
  20. end
  21. def reset_password!(new_password, new_password_confirmation)
  22. if new_password == new_password_confirmation && ::Devise.ldap_update_password
  23. Devise::LdapAdapter.update_password(login_with, new_password)
  24. end
  25. clear_reset_password_token if valid?
  26. save
  27. end
  28. def password=(new_password)
  29. @password = new_password
  30. end
  31. # Checks if a resource is valid upon authentication.
  32. def valid_ldap_authentication?(password)
  33. if Devise::LdapAdapter.valid_credentials?(login_with, password)
  34. return true
  35. else
  36. return false
  37. end
  38. end
  39. def ldap_groups
  40. Devise::LdapAdapter.get_groups(login_with)
  41. end
  42. def ldap_dn
  43. Devise::LdapAdapter.get_dn(login_with)
  44. end
  45. def ldap_get_param(login_with, param)
  46. Devise::LdapAdapter.get_ldap_param(login_with,param)
  47. end
  48. module ClassMethods
  49. # Authenticate a user based on configured attribute keys. Returns the
  50. # authenticated user if it's valid or nil.
  51. def authenticate_with_ldap(attributes={})
  52. auth_key = self.authentication_keys.first
  53. return nil unless attributes[auth_key].present?
  54. # resource = find_for_ldap_authentication(conditions)
  55. resource = where(auth_key => attributes[auth_key]).first
  56. if (resource.blank? and ::Devise.ldap_create_user)
  57. resource = new
  58. resource[auth_key] = attributes[auth_key]
  59. resource.password = attributes[:password]
  60. end
  61. if resource.try(:valid_ldap_authentication?, attributes[:password])
  62. resource.save if resource.new_record?
  63. return resource
  64. else
  65. return nil
  66. end
  67. end
  68. def update_with_password(resource)
  69. puts "UPDATE_WITH_PASSWORD: #{resource.inspect}"
  70. end
  71. end
  72. end
  73. end
  74. end