Files
link-free/src/middlewares/auth.middleware.ts

35 lines
785 B
TypeScript
Raw Normal View History

2021-12-15 15:38:39 -03:00
import jwt from 'jsonwebtoken'
2021-12-26 01:02:23 -03:00
import { env } from 'constants/env'
2021-12-19 20:03:59 -03:00
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) {
2021-12-26 01:02:23 -03:00
const { JWT_SECRET } = env
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()
}