taxonomy/lib/api-middlewares/with-current-user.ts

33 lines
875 B
TypeScript
Raw Permalink Normal View History

2022-10-26 13:18:06 +00:00
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
2022-11-08 04:35:26 +00:00
import { unstable_getServerSession } from "next-auth/next"
2022-10-26 13:18:06 +00:00
import * as z from "zod"
2022-11-07 12:37:47 +00:00
import { authOptions } from "@/lib/auth"
2022-10-26 13:18:06 +00:00
export const schema = z.object({
userId: z.string(),
})
2022-11-07 12:37:47 +00:00
export function withCurrentUser(handler: NextApiHandler) {
2022-10-26 13:18:06 +00:00
return async function (req: NextApiRequest, res: NextApiResponse) {
try {
const query = await schema.parse(req.query)
// Check if the user has access to this user.
2022-11-07 12:37:47 +00:00
const session = await unstable_getServerSession(req, res, authOptions)
2022-10-26 13:18:06 +00:00
if (query.userId !== session?.user.id) {
return res.status(403).end()
}
return handler(req, res)
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(422).json(error.issues)
}
return res.status(500).end()
}
}
}