Files
bidding_watcher/src/common/auth/auth.guard.ts
dmy f08c513bbe feat: 添加环境变量配置并优化部署路径
添加开发和生产环境变量文件
更新前端构建命令以使用不同模式
优化部署脚本中的前端部署路径
在认证守卫中添加日志记录
2026-01-18 15:44:37 +08:00

73 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { UsersService } from '../../users/users.service';
@Injectable()
export class AuthGuard implements CanActivate {
private readonly logger = new Logger(AuthGuard.name);
constructor(
private configService: ConfigService,
private usersService: UsersService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
// 检查是否启用 Basic Auth
const enableBasicAuth =
this.configService.get<string>('ENABLE_BASIC_AUTH') === 'true';
this.logger.log(`Basic Auth enabled: ${enableBasicAuth}`);
if (!enableBasicAuth) {
// 如果未启用 Basic Auth允许所有访问
return true;
}
// 解析 Authorization header
const authHeader = request.headers['authorization'] as string;
if (!authHeader || !authHeader.startsWith('Basic ')) {
this.logger.warn('Missing or invalid Authorization header');
throw new UnauthorizedException('Missing or invalid Authorization header');
}
// 解码 Basic Auth
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString(
'utf-8',
);
const [username, password] = credentials.split(':');
if (!username || !password) {
this.logger.warn('Invalid credentials format');
throw new UnauthorizedException('Invalid credentials format');
}
this.logger.log(`Attempting login for user: ${username}`);
// 验证用户
const user = await this.usersService.validateUser(username, password);
if (!user) {
this.logger.warn(`Login failed for user: ${username} - Invalid username or password`);
throw new UnauthorizedException('Invalid username or password');
}
this.logger.log(`User ${username} logged in successfully`);
// 将用户信息附加到请求对象
(request as any).user = user;
return true;
}
}