2019-12-01 00:11:24 +01:00
|
|
|
defmodule PhilomenaWeb.ApiTokenPlug do
|
2019-12-24 18:14:58 +01:00
|
|
|
alias Philomena.Users
|
2020-07-28 22:56:26 +02:00
|
|
|
alias Plug.Conn
|
2019-12-01 00:11:24 +01:00
|
|
|
|
|
|
|
def init([]), do: []
|
|
|
|
|
|
|
|
def call(conn, _opts) do
|
|
|
|
conn
|
|
|
|
|> maybe_find_user(conn.params["key"])
|
2019-12-24 18:14:58 +01:00
|
|
|
|> assign_user()
|
2019-12-01 00:11:24 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
defp maybe_find_user(conn, nil), do: {conn, nil}
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2020-07-28 22:56:26 +02:00
|
|
|
defp maybe_find_user(conn, token) do
|
|
|
|
user = Users.get_user_by_authentication_token(token)
|
2019-12-01 00:11:24 +01:00
|
|
|
|
|
|
|
{conn, user}
|
|
|
|
end
|
|
|
|
|
2019-12-24 18:14:58 +01:00
|
|
|
defp assign_user({conn, user}) do
|
2020-07-28 22:56:26 +02:00
|
|
|
Conn.assign(conn, :current_user, user)
|
2019-12-01 00:11:24 +01:00
|
|
|
end
|
2019-12-20 18:44:45 +01:00
|
|
|
end
|