defmodule DaProductAppWeb.HostController do use DaProductAppWeb, :controller alias DaProductApp.Mypinpad @doc """ Mypinpad Auth Endpoint: POST /oauth/token """ def create(conn, params) do case params do %{"grant_type" => "client_credentials", "client_id" => client_id, "client_secret" => client_secret} -> # 1. Verify Host in DB case Mypinpad.get_host_by_client_id(client_id) do host when not is_nil(host) and host.client_secret == client_secret -> # 2. Generate Token access_token = Base.encode16(:crypto.strong_rand_bytes(32)) expires_at = DateTime.utc_now() |> DateTime.add(3600, :second) # 3. Save Token to DB with {:ok, _token} <- Mypinpad.create_token(%{ access_token: access_token, expires_at: expires_at, host_id: host.id }) do conn |> put_status(:ok) |> json(%{ access_token: access_token, token_type: "Bearer", expires_in: 3600 }) end _ -> conn |> put_status(:unauthorized) |> json(%{error: "unauthorized", message: "Invalid client_id or client_secret"}) end _ -> require Logger Logger.error("Invalid OAuth request params: #{inspect(params)}") conn |> put_status(:unauthorized) |> json(%{error: "invalid_grant", details: "Check if grant_type, client_id, and client_secret are provided in the root of the JSON body"}) end end end