pollo/src/server/unkey.ts

31 lines
732 B
TypeScript
Raw Normal View History

2023-08-06 14:09:03 -06:00
import { Unkey } from "@unkey/api";
2023-08-17 16:40:09 -06:00
import { NextRequest } from "next/server";
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
2023-08-17 16:40:09 -06:00
export const validateRequest = async (req: NextRequest) => {
2023-08-14 01:18:35 -06:00
let isValidKey: boolean = false;
2023-08-17 16:40:09 -06:00
const authorization = req.headers.get("authorization");
2023-08-14 01:18:35 -06:00
// Get the auth bearer token if it exists
2023-08-17 16:40:09 -06:00
if (authorization) {
const key = authorization.split("Bearer ").at(1);
2023-08-14 01:18:35 -06:00
if (key) {
isValidKey = await validateApiKey(key);
}
}
return isValidKey;
};