1
Fork 0
mirror of https://github.com/Steffo99/festa.git synced 2024-12-23 07:04:22 +00:00
festa/utils/authorizeUser.ts

35 lines
970 B
TypeScript
Raw Normal View History

2022-05-31 03:03:48 +00:00
import { User } from "@prisma/client"
import { NextApiRequest, NextApiResponse } from "next"
2022-05-31 14:46:06 +00:00
import { database } from "./prismaClient"
2022-05-31 03:03:48 +00:00
import { Interrupt } from "./interrupt"
2022-05-31 14:41:58 +00:00
/**
* Find the user who is authenticating in a request.
*
* _For API route usage._
*
* @param req The request performed by the user.
* @returns The user.
*/
export async function authorizeUser(req: NextApiRequest): Promise<User> {
2022-05-31 03:03:48 +00:00
const authorization = req.headers.authorization
if (!authorization) {
throw new Interrupt(401, {error: "Missing Authorization header" })
}
const token = authorization.match(/^Bearer (\S+)$/)?.[1]
if(!(token)) {
throw new Interrupt(401, {error: "Invalid Authorization header" })
}
2022-05-31 14:46:06 +00:00
const dbToken = await database.token.findUnique({where: {token}, include: {user: true}})
2022-05-31 03:03:48 +00:00
if(!(dbToken)) {
throw new Interrupt(401, {error: "No such Authorization token" })
}
return dbToken.user
}