api-server/src/common/guards/jwt-auth.guard.ts
WangDL 5a7c21dd60
All checks were successful
Deploy API Server / build-and-deploy (push) Successful in 9s
feat: implement complete admin authentication system
- Add AdminRole enum (SUPER_ADMIN/ADMIN/OPERATIONS/DEVELOPER/READONLY) with hierarchy
- Add PasswordService (bcryptjs, 12 rounds), AdminTokenService (type=admin JWT)
- Add AdminAuthService: login/lockout/refresh/logout with audit logging
- Add AdminAuthController: /admin-api/auth/{login,refresh,logout,me}
- Add AdminAuthGuard: validates type=admin, user status, session, lockout
- Add AdminRolesGuard + @AdminRoles() decorator for RBAC
- Add AdminAuditService for audit log persistence
- Add AdminLoginRateLimit (10 req/15min per IP)
- Add prisma/seed.ts for SUPER_ADMIN initialization via env vars
- Update JwtAuthGuard to skip /admin-api/* and /internal/* paths
- Update main.ts to exclude admin-api/internal from global 'api' prefix
- Update jwt.config.ts with admin JWT secrets and expiry config

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:05:31 +08:00

58 lines
1.7 KiB
TypeScript

import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
private readonly 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 request = context.switchToHttp().getRequest<Request>();
// Admin and internal routes use their own auth guards
if (request.path.startsWith('/admin-api') || request.path.startsWith('/internal')) {
return true;
}
const token = this.extractToken(request);
if (!token) {
throw new UnauthorizedException('请先登录');
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('jwt.secret'),
});
request.user = { id: String(payload.sub), email: payload.email, role: payload.role };
return true;
} catch {
throw new UnauthorizedException('登录已过期,请重新登录');
}
}
private extractToken(request: Request): string | undefined {
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) return undefined;
return authHeader.split(' ')[1];
}
}