51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
// guards/jwt-auth.guard.ts
|
|
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { Request } from 'express';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { AuthEntityType, AuthRequest, JwtPayload } from './auth.guard';
|
|
|
|
@Injectable()
|
|
export class AdminAuthGuard implements CanActivate {
|
|
constructor(
|
|
private readonly jwtService: JwtService,
|
|
private readonly configService: ConfigService,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext) {
|
|
const request = context.switchToHttp().getRequest<AuthRequest>();
|
|
|
|
try {
|
|
const secret = this.configService.get<string>('JWT_SECRET');
|
|
const token = this.extractTokenFromHeader(request);
|
|
|
|
if (!token) {
|
|
throw new UnauthorizedException();
|
|
}
|
|
|
|
try {
|
|
const payload = await this.jwtService.verifyAsync<JwtPayload>(token, {
|
|
secret,
|
|
});
|
|
|
|
if (payload.type !== AuthEntityType.ADMIN) {
|
|
throw new UnauthorizedException('Access denied. Admin rights required.');
|
|
}
|
|
// 💡 We're assigning the payload to the request object here
|
|
// so that we can access it in our route handlers
|
|
request['user'] = payload;
|
|
} catch {
|
|
throw new UnauthorizedException();
|
|
}
|
|
return true;
|
|
} catch (err) {
|
|
console.log('error in AuthGuard', err);
|
|
throw new UnauthorizedException('Invalid or expired token');
|
|
}
|
|
}
|
|
private extractTokenFromHeader(request: Request): string | undefined {
|
|
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
|
return type === 'Bearer' ? token : undefined;
|
|
}
|
|
}
|