2021-09-01 12:43:55 +00:00
|
|
|
defmodule ArchitexWeb.Client.Plug.AuthenticateClient do
|
|
|
|
import ArchitexWeb.Error
|
2021-06-25 22:29:33 +00:00
|
|
|
import Plug.Conn
|
|
|
|
|
2021-09-01 12:43:55 +00:00
|
|
|
alias Architex.Account
|
2021-06-25 22:29:33 +00:00
|
|
|
alias Plug.Conn
|
|
|
|
|
2021-06-25 23:14:09 +00:00
|
|
|
def init(opts), do: opts
|
2021-06-25 22:29:33 +00:00
|
|
|
|
|
|
|
def call(%Conn{params: %{"access_token" => access_token}} = conn, _opts) do
|
|
|
|
authenticate(conn, access_token)
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(%Conn{req_headers: headers} = conn, _opts) do
|
|
|
|
case List.keyfind(headers, "authorization", 0) do
|
|
|
|
{_, "Bearer " <> access_token} ->
|
|
|
|
authenticate(conn, access_token)
|
|
|
|
|
|
|
|
_ ->
|
2021-06-25 23:14:09 +00:00
|
|
|
put_error(conn, :missing_token)
|
2021-06-25 22:29:33 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp authenticate(conn, access_token) do
|
2021-06-27 20:24:54 +00:00
|
|
|
case Account.by_access_token(access_token) do
|
|
|
|
{account, device} ->
|
2021-06-25 22:29:33 +00:00
|
|
|
conn
|
|
|
|
|> assign(:account, account)
|
|
|
|
|> assign(:device, device)
|
|
|
|
|
|
|
|
nil ->
|
2021-06-25 23:14:09 +00:00
|
|
|
put_error(conn, :unknown_token)
|
2021-06-25 22:29:33 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|