frenzy/lib/frenzy_web/plug/fervor_authenticate.ex

50 lines
1.4 KiB
Elixir

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