refactor: some adjustments

This commit is contained in:
Daniel Soares
2021-12-19 20:03:59 -03:00
parent a9ff01aa52
commit e4b037f273
52 changed files with 417 additions and 481 deletions

View File

@@ -1,19 +1,17 @@
import jwt from 'jsonwebtoken'
import { authConstants } from 'constants/auth'
import { ExceptionError } from 'utils/error'
import type { NextApiRequest, NextApiResponse } from 'next'
import { ExceptionError } from './error'
interface Request extends NextApiRequest {
userId: string
userRole: string
}
type Token = {
sub: string
role: string
}
export async function authMiddleware(req: Request, _res: NextApiResponse, next: () => void) {
export async function authMiddleware(req: NextApiRequest, _res: NextApiResponse, next: () => void) {
const { JWT_SECRET } = authConstants
const token = req.headers['authorization']
if (!token) {
@@ -22,13 +20,7 @@ export async function authMiddleware(req: Request, _res: NextApiResponse, next:
const [, tokenValue] = token.split(' ')
const { JWT_SECRET } = process.env
if (!JWT_SECRET) {
throw new ExceptionError('JWT_SECRET is not defined')
}
const isValidToken = jwt.verify(tokenValue, JWT_SECRET) as Token
const isValidToken = jwt.verify(tokenValue, JWT_SECRET!) as Token
if (!isValidToken) {
throw new ExceptionError('Invalid token', 401)