This commit is contained in:
2025-11-10 12:39:41 +03:30
parent 06f814b331
commit 45ca2fde06
24 changed files with 794 additions and 586 deletions
@@ -0,0 +1,50 @@
// 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;
}
}