2019-03-14 01:13:42 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-12-01 11:00:41 +00:00
|
|
|
module User::LdapAuthenticable
|
2019-03-14 01:13:42 +00:00
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2019-09-24 02:35:36 +00:00
|
|
|
class_methods do
|
|
|
|
def authenticate_with_ldap(params = {})
|
|
|
|
ldap = Net::LDAP.new(ldap_options)
|
2023-04-04 10:42:38 +00:00
|
|
|
filter = format(Devise.ldap_search_filter, uid: Devise.ldap_uid, mail: Devise.ldap_mail, email: Net::LDAP::Filter.escape(params[:email]))
|
2019-03-14 01:13:42 +00:00
|
|
|
|
2019-09-24 02:35:36 +00:00
|
|
|
if (user_info = ldap.bind_as(base: Devise.ldap_base, filter: filter, password: params[:password]))
|
|
|
|
ldap_get_user(user_info.first)
|
|
|
|
end
|
|
|
|
end
|
2019-03-14 01:13:42 +00:00
|
|
|
|
|
|
|
def ldap_get_user(attributes = {})
|
2019-12-01 06:21:28 +00:00
|
|
|
safe_username = attributes[Devise.ldap_uid.to_sym].first
|
2021-06-21 15:07:30 +00:00
|
|
|
|
2019-12-01 06:21:28 +00:00
|
|
|
if Devise.ldap_uid_conversion_enabled
|
|
|
|
keys = Regexp.union(Devise.ldap_uid_conversion_search.chars)
|
|
|
|
replacement = Devise.ldap_uid_conversion_replace
|
|
|
|
safe_username = safe_username.gsub(keys, replacement)
|
|
|
|
end
|
|
|
|
|
2024-05-28 14:11:31 +00:00
|
|
|
resource = joins(:account).merge(Account.with_username(safe_username)).take
|
2019-03-14 01:13:42 +00:00
|
|
|
|
|
|
|
if resource.blank?
|
2024-02-13 17:14:49 +00:00
|
|
|
resource = new(
|
|
|
|
email: attributes[Devise.ldap_mail.to_sym].first,
|
|
|
|
agreement: true,
|
|
|
|
account_attributes: {
|
|
|
|
username: safe_username,
|
|
|
|
},
|
|
|
|
external: true,
|
|
|
|
confirmed_at: Time.now.utc
|
|
|
|
)
|
2019-09-24 02:35:36 +00:00
|
|
|
resource.save!
|
2019-03-14 01:13:42 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
resource
|
|
|
|
end
|
2019-09-24 02:35:36 +00:00
|
|
|
|
|
|
|
def ldap_options
|
|
|
|
opts = {
|
|
|
|
host: Devise.ldap_host,
|
|
|
|
port: Devise.ldap_port,
|
|
|
|
base: Devise.ldap_base,
|
|
|
|
|
|
|
|
auth: {
|
|
|
|
method: :simple,
|
|
|
|
username: Devise.ldap_bind_dn,
|
|
|
|
password: Devise.ldap_password,
|
|
|
|
},
|
|
|
|
|
|
|
|
connect_timeout: 10,
|
|
|
|
}
|
|
|
|
|
|
|
|
if [:simple_tls, :start_tls].include?(Devise.ldap_method)
|
|
|
|
opts[:encryption] = {
|
|
|
|
method: Devise.ldap_method,
|
|
|
|
tls_options: OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.tap { |options| options[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if Devise.ldap_tls_no_verify },
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
opts
|
|
|
|
end
|
2019-03-14 01:13:42 +00:00
|
|
|
end
|
|
|
|
end
|