defmodule DaProductAppWeb.Plugs.ApiKeyAuth do @moduledoc """ Plug for validating API access using a shared secret key. Expects the Authorization header containing the API key. """ import Plug.Conn require Logger def init(opts), do: opts def call(conn, _opts) do expected_key = Application.get_env(:da_product_app, :api_access_key) authorization = get_req_header(conn, "authorization") |> List.first() Logger.debug("API Auth Check - Header Present: #{authorization != nil}") Logger.debug("API Auth Check - Expected Key: #{inspect(expected_key)}") Logger.debug("API Auth Check - Authorization Header: #{inspect(authorization)}") if is_binary(expected_key) && is_binary(authorization) && Plug.Crypto.secure_compare(authorization, expected_key) do Logger.info("API request authenticated successfully") conn else Logger.warning("Unauthorized API request - Invalid or missing key") conn |> put_status(:unauthorized) |> put_resp_content_type("application/json") |> send_resp(:unauthorized, Jason.encode!(%{ status: "error", code: "UNAUTHORIZED", message: "Invalid or missing API key. Please provide a valid Authorization header." })) |> halt() end end end