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 @behaviour Pleroma.Web.Auth.Authenticator
11 @base Pleroma.Web.Auth.PleromaAuthenticator
13 @connection_timeout 10_000
14 @search_timeout 10_000
16 defdelegate get_registration(conn, params), to: @base
18 defdelegate create_from_registration(conn, params, registration), to: @base
20 def get_user(%Plug.Conn{} = conn, params) do
21 if Pleroma.Config.get([:ldap, :enabled]) do
24 %{"authorization" => %{"name" => name, "password" => password}} ->
27 %{"grant_type" => "password", "username" => name, "password" => password} ->
31 case ldap_user(name, password) do
35 {:error, {:ldap_connection_error, _}} ->
36 # When LDAP is unavailable, try default authenticator
37 @base.get_user(conn, params)
43 # Fall back to default authenticator
44 @base.get_user(conn, params)
48 def handle_error(%Plug.Conn{} = _conn, error) do
52 def auth_template, do: nil
54 defp ldap_user(name, password) do
55 ldap = Pleroma.Config.get(:ldap, [])
56 host = Keyword.get(ldap, :host, "localhost")
57 port = Keyword.get(ldap, :port, 389)
58 ssl = Keyword.get(ldap, :ssl, false)
59 sslopts = Keyword.get(ldap, :sslopts, [])
62 [{:port, port}, {:ssl, ssl}, {:timeout, @connection_timeout}] ++
63 if sslopts != [], do: [{:sslopts, sslopts}], else: []
65 case :eldap.open([to_charlist(host)], options) do
68 if Keyword.get(ldap, :tls, false) do
69 :application.ensure_all_started(:ssl)
71 case :eldap.start_tls(
73 Keyword.get(ldap, :tlsopts, []),
80 Logger.error("Could not start TLS: #{inspect(error)}")
84 bind_user(connection, ldap, name, password)
86 :eldap.close(connection)
90 Logger.error("Could not open LDAP connection: #{inspect(error)}")
91 {:error, {:ldap_connection_error, error}}
95 defp bind_user(connection, ldap, name, password) do
96 uid = Keyword.get(ldap, :uid, "cn")
97 base = Keyword.get(ldap, :base)
99 case :eldap.simple_bind(connection, "#{uid}=#{name},#{base}", password) do
101 case User.get_by_nickname_or_email(name) do
106 register_user(connection, base, uid, name, password)
114 defp register_user(connection, base, uid, name, password) do
115 case :eldap.search(connection, [
116 {:base, to_charlist(base)},
117 {:filter, :eldap.equalityMatch(to_charlist(uid), to_charlist(name))},
118 {:scope, :eldap.wholeSubtree()},
119 {:attributes, ['mail', 'email']},
120 {:timeout, @search_timeout}
122 {:ok, {:eldap_search_result, [{:eldap_entry, _, attributes}], _}} ->
123 with {_, [mail]} <- List.keyfind(attributes, 'mail', 0) do
125 email: :erlang.list_to_binary(mail),
129 password_confirmation: password
132 changeset = User.register_changeset(%User{}, params)
134 case User.register(changeset) do
140 Logger.error("Could not find LDAP attribute mail: #{inspect(attributes)}")
141 {:error, :ldap_registration_missing_attributes}