zoeys.computer/lib/zoeyscomputer_web/plugs/api_authentication.ex

40 lines
878 B
Elixir
Raw Normal View History

2024-10-22 16:51:56 -04:00
defmodule ZoeyscomputerWeb.Plugs.ApiAuthentication do
alias Zoeyscomputer.ApiKeys
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
case get_auth_token(conn) do
nil ->
handle_unauthorized(conn)
token ->
case ApiKeys.authenticate_api_key(token) do
nil ->
handle_unauthorized(conn)
user ->
conn
|> assign(:current_user, user)
|> assign(:authenticated_with_api_key, true)
end
end
end
defp get_auth_token(conn) do
case get_req_header(conn, "authorization") do
["Bearer " <> token] -> token
_ -> nil
end
end
defp handle_unauthorized(conn) do
conn
|> put_status(:unauthorized)
|> Phoenix.Controller.put_view(ZoeyscomputerWeb.ErrorJSON)
|> Phoenix.Controller.render(:"401")
|> halt()
end
end