Files
psp_api/src/modules/auth/jwt-auth.guard.ts
T

58 lines
1.6 KiB
TypeScript
Raw Normal View History

import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { JwtService } from '@nestjs/jwt'
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator'
import { IWithJWTPayloadRequest } from '../../common/models/token-model'
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private jwt: JwtService,
private reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
])
if (isPublic) return true
const req = context.switchToHttp().getRequest<IWithJWTPayloadRequest>()
let token: string | undefined = req.cookies?.accessToken
if (!token) {
const authHeader = (req.headers.authorization || req.headers.Authorization) as
| string
| undefined
if (authHeader && authHeader.startsWith('Bearer ')) {
token = authHeader.slice(7)
}
}
if (!token) throw new UnauthorizedException('Missing access token')
try {
const payload = this.jwt.verify(token, {
secret: process.env.JWT_SECRET || 'secret',
})
if (payload.type !== 'POS')
throw new UnauthorizedException('Invalid or expired token')
// Set the typed dataPayload to the request
req.dataPayload = payload
return true
} catch (err) {
console.log(err)
throw new UnauthorizedException('Invalid or expired token')
}
}
}