Adds basic api-key auth in users, need to extract out

pull/9078/head
Agusti Fernandez Pardo 2022-03-28 02:51:40 +02:00
parent 0e3131d866
commit 19934d8c3a
5 changed files with 43 additions and 20 deletions

View File

@ -1,7 +1,4 @@
export const stringifyISODate = (date: Date|undefined): string => { export const stringifyISODate = (date: Date|undefined): string => {
return `${date?.toISOString()}` return `${date?.toISOString()}`
} }
// FIXME: debug this, supposed to take an array/object and auto strinfy date-like values // TODO: create a function that takes an object and returns a stringified version of dates of it.
export const autoStringifyDateValues = ([key, value]: [string, unknown]): [string, unknown] => {
return [key, typeof value === "object" && value instanceof Date ? stringifyISODate(value) : value]
}

12
pages/_middleware.ts Normal file
View File

@ -0,0 +1,12 @@
import { NextRequest, NextResponse } from 'next/server'
// Not much useful yet as prisma.client can't be used in the middlewares (client is not available)
// For now we just throw early if no apiKey is passed,
// but we could also check if the apiKey is valid if we had prisma here.
export async function middleware({ nextUrl }: NextRequest, res: NextResponse) {
const response = NextResponse.next()
const apiKey = nextUrl.searchParams.get('apiKey');
if (apiKey) return response
// if no apiKey is passed, we throw early
else throw new Error('You need to pass an apiKey as query param: https://api.cal.com/resource?apiKey=<your-api-key>')
}

View File

@ -7,13 +7,30 @@ type ResponseData = {
data?: User[]; data?: User[];
error?: unknown; 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>) { export default async function user(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
try { const apiKey = req.query.apiKey as string;
const users = await prisma.user.findMany(); const apiInDb = await prisma.apiKey.findUnique({ where: { id: apiKey } });
res.status(200).json({ data: { ...users } }); if (!apiInDb) throw new Error('API key not found');
} catch (error) { const { expiresAt } = apiInDb;
// FIXME: Add zod for validation/error handling // if (!apiInDb) res.status(400).json({ error: 'Your api key is not valid' });
res.status(400).json({ error: error }); 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' });
} }

View File

@ -13,18 +13,14 @@ type ResponseData = {
async function createUser(req: NextApiRequest, res: NextApiResponse<ResponseData>) { async function createUser(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { body, method } = req; const { body, method } = req;
if (method === "POST") { const safe = schemaUser.safeParse(body);
const safe = schemaUser.safeParse(body); if (method === "POST" && safe.success) {
if (safe.success && safe.data) {
await prisma.user await prisma.user
.create({ data: safe.data }) .create({ data: safe.data })
.then((user) => res.status(201).json({ data: user })) .then((user) => res.status(201).json({ data: user }))
.catch((error) => res.status(400).json({ message: "Could not create user type", error: error })); .catch((error) => res.status(400).json({ message: "Could not create user type", error: error }));
} // Reject any other HTTP method than POST
} else { } else res.status(405).json({ error: "Only POST Method allowed" });
// Reject any other HTTP method than POST
res.status(405).json({ error: "Only POST Method allowed" });
}
} }
export default withValidUser(createUser); export default withValidUser(createUser);

View File

@ -21,7 +21,8 @@
"jsx": "preserve", "jsx": "preserve",
"paths": { "paths": {
"@api/*": ["pages/api/*"], "@api/*": ["pages/api/*"],
"@lib/*": ["lib/*"] "@lib/*": ["lib/*"],
"@/*": ["*"]
}, },
}, },