Merge branch 'update-service-files-of-openrc-and-systemd-to-new-recommended-paths...
[akkoma] / lib / pleroma / plugs / user_fetcher_plug.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.Plugs.UserFetcherPlug do
6 import Plug.Conn
7 alias Pleroma.Repo
8 alias Pleroma.User
9
10 def init(options) do
11 options
12 end
13
14 def call(conn, _options) do
15 with %{auth_credentials: %{username: username}} <- conn.assigns,
16 {:ok, %User{} = user} <- user_fetcher(username) do
17 conn
18 |> assign(:auth_user, user)
19 else
20 _ -> conn
21 end
22 end
23
24 defp user_fetcher(username_or_email) do
25 {
26 :ok,
27 cond do
28 # First, try logging in as if it was a name
29 user = Repo.get_by(User, %{nickname: username_or_email}) ->
30 user
31
32 # If we get nil, we try using it as an email
33 user = Repo.get_by(User, %{email: username_or_email}) ->
34 user
35 end
36 }
37 end
38 end