OpenLDAP support
[akkoma] / lib / pleroma / ldap.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.LDAP do
6 alias Pleroma.User
7
8 require Logger
9
10 @connection_timeout 10_000
11 @search_timeout 10_000
12
13 def get_user(name, password) do
14 ldap = Pleroma.Config.get(:ldap, [])
15 host = Keyword.get(ldap, :host, "localhost")
16 port = Keyword.get(ldap, :port, 389)
17 ssl = Keyword.get(ldap, :ssl, false)
18 sslopts = Keyword.get(ldap, :sslopts, [])
19
20 options =
21 [{:port, port}, {:ssl, ssl}, {:timeout, @connection_timeout}] ++
22 if sslopts != [], do: [{:sslopts, sslopts}], else: []
23
24 case :eldap.open([to_charlist(host)], options) do
25 {:ok, connection} ->
26 try do
27 uid = Keyword.get(ldap, :uid, "cn")
28 base = Keyword.get(ldap, :base)
29
30 case :eldap.simple_bind(connection, "#{uid}=#{name},#{base}", password) do
31 :ok ->
32 case User.get_by_nickname_or_email(name) do
33 %User{} = user ->
34 user
35
36 _ ->
37 register_user(connection, base, uid, name, password)
38 end
39
40 error ->
41 error
42 end
43 after
44 :eldap.close(connection)
45 end
46
47 {:error, error} ->
48 Logger.error("Could not open LDAP connection: #{inspect(error)}")
49 {:error, {:ldap_connection_error, error}}
50 end
51 end
52
53 def register_user(connection, base, uid, name, password) do
54 case :eldap.search(connection, [
55 {:base, to_charlist(base)},
56 {:filter, :eldap.equalityMatch(to_charlist(uid), to_charlist(name))},
57 {:scope, :eldap.wholeSubtree()},
58 {:timeout, @search_timeout}
59 ]) do
60 {:ok, {:eldap_search_result, [{:eldap_entry, _, attributes}], _}} ->
61 with {_, [mail]} <- List.keyfind(attributes, 'mail', 0) do
62 params = %{
63 email: :erlang.list_to_binary(mail),
64 name: name,
65 nickname: name,
66 password: password,
67 password_confirmation: password
68 }
69
70 changeset = User.register_changeset(%User{}, params)
71
72 case User.register(changeset) do
73 {:ok, user} -> user
74 error -> error
75 end
76 else
77 _ -> {:error, :ldap_registration_missing_attributes}
78 end
79
80 error ->
81 error
82 end
83 end
84 end