1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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.Helpers, only: [fetch_credentials: 1, fetch_user: 1]
12 @behaviour Pleroma.Web.Auth.Authenticator
13 @base Pleroma.Web.Auth.PleromaAuthenticator
15 @connection_timeout 10_000
16 @search_timeout 10_000
18 defdelegate get_registration(conn), to: @base
19 defdelegate create_from_registration(conn, registration), to: @base
20 defdelegate handle_error(conn, error), to: @base
21 defdelegate auth_template, to: @base
22 defdelegate oauth_consumer_template, to: @base
24 def get_user(%Plug.Conn{} = conn) do
25 with {:ldap, true} <- {:ldap, Pleroma.Config.get([:ldap, :enabled])},
26 {:ok, {name, password}} <- fetch_credentials(conn),
27 %User{} = user <- ldap_user(name, password) do
38 defp ldap_user(name, password) do
39 ldap = Pleroma.Config.get(:ldap, [])
40 host = Keyword.get(ldap, :host, "localhost")
41 port = Keyword.get(ldap, :port, 389)
42 ssl = Keyword.get(ldap, :ssl, false)
43 sslopts = Keyword.get(ldap, :sslopts, [])
46 [{:port, port}, {:ssl, ssl}, {:timeout, @connection_timeout}] ++
47 if sslopts != [], do: [{:sslopts, sslopts}], else: []
49 case :eldap.open([to_charlist(host)], options) do
52 if Keyword.get(ldap, :tls, false) do
53 :application.ensure_all_started(:ssl)
55 case :eldap.start_tls(
57 Keyword.get(ldap, :tlsopts, []),
64 Logger.error("Could not start TLS: #{inspect(error)}")
68 bind_user(connection, ldap, name, password)
70 :eldap.close(connection)
74 Logger.error("Could not open LDAP connection: #{inspect(error)}")
75 {:error, {:ldap_connection_error, error}}
79 defp bind_user(connection, ldap, name, password) do
80 uid = Keyword.get(ldap, :uid, "cn")
81 base = Keyword.get(ldap, :base)
83 case :eldap.simple_bind(connection, "#{uid}=#{name},#{base}", password) do
85 case fetch_user(name) do
90 register_user(connection, base, uid, name)
98 defp register_user(connection, base, uid, name) do
99 case :eldap.search(connection, [
100 {:base, to_charlist(base)},
101 {:filter, :eldap.equalityMatch(to_charlist(uid), to_charlist(name))},
102 {:scope, :eldap.wholeSubtree()},
103 {:timeout, @search_timeout}
105 {:ok, {:eldap_search_result, [{:eldap_entry, _, attributes}], _, _}} ->
113 case List.keyfind(attributes, 'mail', 0) do
114 {_, [mail]} -> Map.put_new(params, :email, :erlang.list_to_binary(mail))
118 changeset = User.register_changeset_ldap(%User{}, params)
120 case User.register(changeset) do