You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.4 KiB

  1. # frozen_string_literal: true
  2. require 'net/ldap'
  3. require 'devise/strategies/authenticatable'
  4. module Devise
  5. module Strategies
  6. class LdapAuthenticatable < Authenticatable
  7. def authenticate!
  8. if params[:user]
  9. ldap = Net::LDAP.new(
  10. host: Devise.ldap_host,
  11. port: Devise.ldap_port,
  12. base: Devise.ldap_base,
  13. encryption: {
  14. method: Devise.ldap_method,
  15. tls_options: tls_options,
  16. },
  17. auth: {
  18. method: :simple,
  19. username: Devise.ldap_bind_dn,
  20. password: Devise.ldap_password,
  21. },
  22. connect_timeout: 10
  23. )
  24. filter = format(Devise.ldap_search_filter, uid: Devise.ldap_uid, email: email)
  25. if (user_info = ldap.bind_as(base: Devise.ldap_base, filter: filter, password: password))
  26. user = User.ldap_get_user(user_info.first)
  27. success!(user)
  28. else
  29. return fail(:invalid)
  30. end
  31. end
  32. end
  33. def email
  34. params[:user][:email]
  35. end
  36. def password
  37. params[:user][:password]
  38. end
  39. def tls_options
  40. OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.tap do |options|
  41. options[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if Devise.ldap_tls_no_verify
  42. end
  43. end
  44. end
  45. end
  46. end
  47. Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)