1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Auth.LDAPAuthenticator do
10 import Pleroma.Web.Auth.Authenticator,
11 only: [fetch_credentials: 1, fetch_user: 1]
13 @behaviour Pleroma.Web.Auth.Authenticator
14 @base Pleroma.Web.Auth.PleromaAuthenticator
16 @connection_timeout 10_000
17 @search_timeout 10_000
19 defdelegate get_registration(conn), to: @base
20 defdelegate create_from_registration(conn, registration), to: @base
21 defdelegate handle_error(conn, error), to: @base
22 defdelegate auth_template, to: @base
23 defdelegate oauth_consumer_template, to: @base
25 def get_user(%Plug.Conn{} = conn) do
26 with {:ldap, true} <- {:ldap, Pleroma.Config.get([:ldap, :enabled])},
27 {:ok, {name, password}} <- fetch_credentials(conn),
28 %User{} = user <- ldap_user(name, password) do
31 {:error, {:ldap_connection_error, _}} ->
32 # When LDAP is unavailable, try default authenticator
43 defp ldap_user(name, password) do
44 ldap = Pleroma.Config.get(:ldap, [])
45 host = Keyword.get(ldap, :host, "localhost")
46 port = Keyword.get(ldap, :port, 389)
47 ssl = Keyword.get(ldap, :ssl, false)
48 sslopts = Keyword.get(ldap, :sslopts, [])
51 [{:port, port}, {:ssl, ssl}, {:timeout, @connection_timeout}] ++
52 if sslopts != [], do: [{:sslopts, sslopts}], else: []
54 case :eldap.open([to_charlist(host)], options) do
57 if Keyword.get(ldap, :tls, false) do
58 :application.ensure_all_started(:ssl)
60 case :eldap.start_tls(
62 Keyword.get(ldap, :tlsopts, []),
69 Logger.error("Could not start TLS: #{inspect(error)}")
73 bind_user(connection, ldap, name, password)
75 :eldap.close(connection)
79 Logger.error("Could not open LDAP connection: #{inspect(error)}")
80 {:error, {:ldap_connection_error, error}}
84 defp bind_user(connection, ldap, name, password) do
85 uid = Keyword.get(ldap, :uid, "cn")
86 base = Keyword.get(ldap, :base)
88 case :eldap.simple_bind(connection, "#{uid}=#{name},#{base}", password) do
90 case fetch_user(name) do
95 register_user(connection, base, uid, name, password)
103 defp register_user(connection, base, uid, name, password) do
104 case :eldap.search(connection, [
105 {:base, to_charlist(base)},
106 {:filter, :eldap.equalityMatch(to_charlist(uid), to_charlist(name))},
107 {:scope, :eldap.wholeSubtree()},
108 {:attributes, ['mail', 'email']},
109 {:timeout, @search_timeout}
111 {:ok, {:eldap_search_result, [{:eldap_entry, _, attributes}], _}} ->
112 with {_, [mail]} <- List.keyfind(attributes, 'mail', 0) do
114 email: :erlang.list_to_binary(mail),
118 password_confirmation: password
121 changeset = User.register_changeset(%User{}, params)
123 case User.register(changeset) do
129 Logger.error("Could not find LDAP attribute mail: #{inspect(attributes)}")
130 {:error, :ldap_registration_missing_attributes}