2019-03-31 14:52:56 +00:00
|
|
|
defmodule FrenzyWeb.Plug.FervorAuthenticate do
|
|
|
|
import Plug.Conn
|
2019-05-21 00:05:54 +00:00
|
|
|
alias Frenzy.{Repo, User, ApprovedClient}
|
2019-03-31 14:52:56 +00:00
|
|
|
|
|
|
|
def init(opts), do: opts
|
|
|
|
|
|
|
|
def call(conn, _opts) do
|
2019-05-21 00:05:54 +00:00
|
|
|
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
|
2019-03-31 14:52:56 +00:00
|
|
|
case get_req_header(conn, "authorization") do
|
|
|
|
[authorization | _] ->
|
2019-05-21 00:05:54 +00:00
|
|
|
{conn, authorization}
|
2019-03-31 14:52:56 +00:00
|
|
|
|
|
|
|
_ ->
|
2019-05-21 00:05:54 +00:00
|
|
|
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}
|
2019-03-31 14:52:56 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|