ldap_authenticable.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. module User::LdapAuthenticable
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def authenticate_with_ldap(params = {})
  6. ldap = Net::LDAP.new(ldap_options)
  7. filter = format(Devise.ldap_search_filter, uid: Devise.ldap_uid, mail: Devise.ldap_mail, email: Net::LDAP::Filter.escape(params[:email]))
  8. if (user_info = ldap.bind_as(base: Devise.ldap_base, filter: filter, password: params[:password]))
  9. ldap_get_user(user_info.first)
  10. end
  11. end
  12. def ldap_get_user(attributes = {})
  13. safe_username = attributes[Devise.ldap_uid.to_sym].first
  14. if Devise.ldap_uid_conversion_enabled
  15. keys = Regexp.union(Devise.ldap_uid_conversion_search.chars)
  16. replacement = Devise.ldap_uid_conversion_replace
  17. safe_username = safe_username.gsub(keys, replacement)
  18. end
  19. resource = joins(:account).find_by(accounts: { username: safe_username })
  20. if resource.blank?
  21. resource = new(email: attributes[Devise.ldap_mail.to_sym].first, agreement: true, account_attributes: { username: safe_username }, admin: false, external: true, confirmed_at: Time.now.utc)
  22. resource.save!
  23. end
  24. resource
  25. end
  26. def ldap_options
  27. opts = {
  28. host: Devise.ldap_host,
  29. port: Devise.ldap_port,
  30. base: Devise.ldap_base,
  31. auth: {
  32. method: :simple,
  33. username: Devise.ldap_bind_dn,
  34. password: Devise.ldap_password,
  35. },
  36. connect_timeout: 10,
  37. }
  38. if [:simple_tls, :start_tls].include?(Devise.ldap_method)
  39. opts[:encryption] = {
  40. method: Devise.ldap_method,
  41. tls_options: OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.tap { |options| options[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if Devise.ldap_tls_no_verify },
  42. }
  43. end
  44. opts
  45. end
  46. end
  47. end