This commit is contained in:
zack 2024-10-22 16:51:56 -04:00
parent e2967f68b2
commit ef2a6c41b4
No known key found for this signature in database
GPG key ID: 5F873416BCF59F35
39 changed files with 2349 additions and 30 deletions

View file

@ -0,0 +1,39 @@
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