import { getApiKeyByToken } from "./db";

// Returns the user's email address or throws an error if unauthenticated
export default async function apiAuth(request: Request, callback: (request: Request, user: string) => Response | Promise<Response>) {
  let authToken = request.headers.get("authorization");
  if (!authToken) return new Response("Unauthorized", { status: 401 });
  const token = authToken.replace(/^Bearer /, ""); // the annoying prefix should be optional

  const key = await getApiKeyByToken(token);
  if (!key) return new Response("Unauthorized", { status: 401 });

  const res = callback(request, key.address);;

  if (res instanceof Promise) {
    return await res;
  } else {
    return res;
  }
};
