Implement authorization plug

This commit is contained in:
Nat 2023-06-13 10:07:45 -07:00
parent 7e16cd9ae0
commit 9a6b7eb518
Signed by: nat
GPG Key ID: B53AB05285D710D6
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,54 @@
defmodule HostasWeb.Plugs.Auth do
import Plug.Conn
use HostasWeb, :controller
import Ecto.Query, only: [from: 2]
alias Hostas.Repo
alias Hostas.Denizen
alias Hostas.Token
def init(default), do: default
def call(conn, _default) do
case get_req_header(conn, "authorization") |> List.first() do
nil -> conn
|> put_status(401)
|> json(%{"error" => "No API key provided"})
|> halt()
header_value ->
case header_value |> String.split() do
[method, key] ->
if method == "Bearer" do
case Token.get(key) do
{:ok, struct} ->
denizen = Repo.one!(from d in Denizen, where: d.id == ^struct.denizen_id)
conn
|> assign(:token, struct)
|> assign(:denizen, denizen)
{:error, :expired} ->
conn
|> put_status(401)
|> json(%{"error" => "Token expired"})
|> halt()
{:error, :unknown} ->
conn
|> put_status(401)
|> json(%{"error" => "API key not found"})
|> halt()
end
else
conn
|> put_status(401)
|> json(%{"error" => "Unknown authorization method"})
|> halt()
end
_ ->
conn
|> put_status(422)
|> json(%{"error" => "Malformed Authorization header"})
|> halt()
end
end
end
end

View File

@ -1,5 +1,6 @@
defmodule HostasWeb.Router do
use HostasWeb, :router
alias HostasWeb.Plugs
pipeline :browser do
plug :accepts, ["html"]
@ -14,6 +15,10 @@ defmodule HostasWeb.Router do
plug :accepts, ["json"]
end
pipeline :api_locked do
plug Plugs.Auth
end
scope "/", HostasWeb do
pipe_through :browser
@ -25,6 +30,8 @@ defmodule HostasWeb.Router do
# create, verify, renew, revoke
post "/auth/token", Auth.TokenController, :create
pipe_through :api_locked
get "/auth/token", Auth.TokenController, :verify
delete "/auth/token/:id", Auth.TokenController, :revoke
get "/auth/token/:id/renew", Auth.TokenController, :renew