2023-08-06 14:09:03 -06:00
|
|
|
import { Unkey } from "@unkey/api";
|
2023-08-14 01:18:35 -06:00
|
|
|
import { NextApiRequest, NextApiResponse } from "next";
|
2023-08-06 14:09:03 -06:00
|
|
|
import { env } from "~/env.mjs";
|
|
|
|
|
|
|
|
export const unkey = new Unkey({ token: env.UNKEY_ROOT_KEY });
|
|
|
|
|
|
|
|
export const validateApiKey = async (key: string) => {
|
|
|
|
try {
|
|
|
|
const res = await unkey.keys.verify({
|
|
|
|
key,
|
|
|
|
});
|
|
|
|
return res.valid;
|
|
|
|
} catch {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|
2023-08-14 01:18:35 -06:00
|
|
|
|
|
|
|
export const validateRequest = async (
|
|
|
|
req: NextApiRequest,
|
|
|
|
res: NextApiResponse
|
|
|
|
) => {
|
|
|
|
let isValidKey: boolean = false;
|
|
|
|
// Get the auth bearer token if it exists
|
|
|
|
if (req.headers.authorization) {
|
|
|
|
const key = req.headers.authorization.split("Bearer ").at(1);
|
|
|
|
if (key) {
|
|
|
|
isValidKey = await validateApiKey(key);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isValidKey) {
|
|
|
|
res.status(403).json({ error: "UNAUTHORIZED" });
|
|
|
|
}
|
|
|
|
|
|
|
|
return isValidKey;
|
|
|
|
};
|