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.

53 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. if (user_info = ldap.bind_as(base: Devise.ldap_base, filter: "(#{Devise.ldap_uid}=#{email})", password: password))
  25. user = User.ldap_get_user(user_info.first)
  26. success!(user)
  27. else
  28. return fail(:invalid_login)
  29. end
  30. end
  31. end
  32. def email
  33. params[:user][:email]
  34. end
  35. def password
  36. params[:user][:password]
  37. end
  38. def tls_options
  39. OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.tap do |options|
  40. options[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if Devise.ldap_tls_no_verify
  41. end
  42. end
  43. end
  44. end
  45. end
  46. Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)