2021-12-15 15:38:39 -03:00
|
|
|
import jwt from 'jsonwebtoken'
|
|
|
|
|
|
2021-12-19 20:03:59 -03:00
|
|
|
import { authConstants } from 'constants/auth'
|
|
|
|
|
import { ExceptionError } from 'utils/error'
|
2021-12-15 15:38:39 -03:00
|
|
|
|
2021-12-19 20:03:59 -03:00
|
|
|
import type { NextApiRequest, NextApiResponse } from 'next'
|
2021-12-24 11:48:37 -03:00
|
|
|
import type { Role } from '@prisma/client'
|
2021-12-15 15:38:39 -03:00
|
|
|
|
|
|
|
|
type Token = {
|
|
|
|
|
sub: string
|
2021-12-24 11:48:37 -03:00
|
|
|
role: Role
|
2021-12-15 15:38:39 -03:00
|
|
|
}
|
|
|
|
|
|
2021-12-19 20:03:59 -03:00
|
|
|
export async function authMiddleware(req: NextApiRequest, _res: NextApiResponse, next: () => void) {
|
|
|
|
|
const { JWT_SECRET } = authConstants
|
2021-12-15 15:38:39 -03:00
|
|
|
const token = req.headers['authorization']
|
|
|
|
|
|
|
|
|
|
if (!token) {
|
|
|
|
|
throw new ExceptionError('No token provided', 401)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const [, tokenValue] = token.split(' ')
|
|
|
|
|
|
2021-12-19 20:03:59 -03:00
|
|
|
const isValidToken = jwt.verify(tokenValue, JWT_SECRET!) as Token
|
2021-12-15 15:38:39 -03:00
|
|
|
|
|
|
|
|
if (!isValidToken) {
|
|
|
|
|
throw new ExceptionError('Invalid token', 401)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.userId = isValidToken.sub
|
|
|
|
|
req.userRole = isValidToken.role
|
|
|
|
|
|
|
|
|
|
next()
|
|
|
|
|
}
|