2019-12-01 00:11:24 +01:00
|
|
|
defmodule PhilomenaWeb.ApiTokenPlug do
|
2019-12-24 18:14:58 +01:00
|
|
|
alias Philomena.Users
|
2019-12-01 00:11:24 +01:00
|
|
|
alias Pow.Plug
|
|
|
|
|
|
|
|
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
|
|
|
|
2019-12-01 00:11:24 +01:00
|
|
|
defp maybe_find_user(conn, key) do
|
2019-12-24 18:14:58 +01:00
|
|
|
user = Users.get_by(authentication_token: key)
|
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
|
2019-12-01 00:11:24 +01:00
|
|
|
config = Plug.fetch_config(conn)
|
|
|
|
|
|
|
|
Plug.assign_current_user(conn, user, config)
|
|
|
|
end
|
2019-12-20 18:44:45 +01:00
|
|
|
end
|