frenzy/lib/frenzy_web/plug/fervor_authenticate.ex

72 lines
1.9 KiB
Elixir

defmodule FrenzyWeb.Plug.FervorAuthenticate do
import Plug.Conn
alias Frenzy.{Repo, User, ApprovedClient}
def init(opts), do: opts
def call(conn, _opts) do
with {conn, authorization} when authorization != nil <- get_auth_header(conn),
{conn, access_token} when access_token != nil <- get_access_token(conn, authorization),
{conn, approved_client} when approved_client != nil <-
get_approved_client(conn, access_token) do
assign(conn, :user, Repo.get(User, approved_client.user_id))
else
{conn, _} ->
conn
end
end
defp get_auth_header(conn) do
case get_req_header(conn, "authorization") do
[authorization | _] ->
{conn, authorization}
_ ->
conn =
conn
|> put_status(401)
|> Phoenix.Controller.json(%{
error: "Missing authorization",
error_description: "No Authorization header was provided"
})
|> halt()
{conn, nil}
end
end
defp get_access_token(conn, "Bearer " <> access_token), do: {conn, access_token}
defp get_access_token(conn, _authorization) do
conn =
conn
|> put_status(401)
|> Phoenix.Controller.json(%{
error: "Invalid authorization",
error_description: "The provided Authorization header does not match the expected format"
})
|> halt()
{conn, nil}
end
defp get_approved_client(conn, access_token) do
case Repo.get_by(ApprovedClient, access_token: access_token) do
nil ->
conn =
conn
|> put_status(400)
|> Phoenix.Controller.json(%{
error: "Invalid authorization",
error_description: "The provided access token is not valid"
})
|> halt()
{conn, nil}
approved_client ->
{conn, approved_client}
end
end
end