Adds basic api-key auth in users, need to extract out
This commit is contained in:
1 parent
0e3131d866
commit
19934d8c3a
5 files changed
+43
-20
No files matched your search
@@ -7,13 +7,30 @@ type ResponseData = {
|
||||
data?: User[];
|
||||
error?: unknown;
|
||||
};
|
||||
const dateInPast = function (firstDate: Date, secondDate: Date) {
|
||||
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
const today = new Date();
|
||||
|
||||
export default async function user(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
|
||||
try {
|
||||
const users = await prisma.user.findMany();
|
||||
res.status(200).json({ data: { ...users } });
|
||||
} catch (error) {
|
||||
// FIXME: Add zod for validation/error handling
|
||||
res.status(400).json({ error: error });
|
||||
}
|
||||
const apiKey = req.query.apiKey as string;
|
||||
const apiInDb = await prisma.apiKey.findUnique({ where: { id: apiKey } });
|
||||
if (!apiInDb) throw new Error('API key not found');
|
||||
const { expiresAt } = apiInDb;
|
||||
// if (!apiInDb) res.status(400).json({ error: 'Your api key is not valid' });
|
||||
if (expiresAt && dateInPast(expiresAt, today)) {
|
||||
console.log(apiInDb)
|
||||
try {
|
||||
const users = await prisma.user.findMany();
|
||||
res.status(200).json({ data: { ...users } });
|
||||
} catch (error) {
|
||||
// FIXME: Add zod for validation/error handling
|
||||
res.status(400).json({ error: error });
|
||||
}
|
||||
} else res.status(400).json({ error: 'Your api key is not valid' });
|
||||
|
||||
}
|
||||
@@ -13,18 +13,14 @@ type ResponseData = {
|
||||
|
||||
async function createUser(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
|
||||
const { body, method } = req;
|
||||
if (method === "POST") {
|
||||
const safe = schemaUser.safeParse(body);
|
||||
if (safe.success && safe.data) {
|
||||
const safe = schemaUser.safeParse(body);
|
||||
if (method === "POST" && safe.success) {
|
||||
await prisma.user
|
||||
.create({ data: safe.data })
|
||||
.then((user) => res.status(201).json({ data: user }))
|
||||
.catch((error) => res.status(400).json({ message: "Could not create user type", error: error }));
|
||||
}
|
||||
} else {
|
||||
// Reject any other HTTP method than POST
|
||||
res.status(405).json({ error: "Only POST Method allowed" });
|
||||
}
|
||||
// Reject any other HTTP method than POST
|
||||
} else res.status(405).json({ error: "Only POST Method allowed" });
|
||||
}
|
||||
|
||||
export default withValidUser(createUser);
|
||||
Reference in new issue
Block a user