philomena/lib/philomena_web/plugs/api_token_plug.ex

26 lines
509 B
Elixir
Raw Normal View History

2019-12-01 00:11:24 +01:00
defmodule PhilomenaWeb.ApiTokenPlug do
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"])
|> assign_user()
2019-12-01 00:11:24 +01:00
end
defp maybe_find_user(conn, nil), do: {conn, nil}
defp maybe_find_user(conn, key) do
user = Users.get_by(authentication_token: key)
2019-12-01 00:11:24 +01:00
{conn, user}
end
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