import { Injectable, Logger, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { UserService } from '../users/services/user.service'; export interface LoginResult { accessToken: string; user: { id: string; username: string; role: string; displayName: string; }; } /** * 认证服务 */ @Injectable() export class AuthService { private readonly logger = new Logger(AuthService.name); constructor( private readonly userService: UserService, private readonly jwtService: JwtService, ) {} /** * 登录 */ async login(username: string, password: string): Promise { const user = await this.userService.validateUser(username, password); if (!user) { throw new UnauthorizedException('用户名或密码错误'); } const payload = { sub: user.id, username: user.username, role: user.role, }; return { accessToken: this.jwtService.sign(payload), user: { id: user.id, username: user.username, role: user.role, displayName: user.displayName, }, }; } /** * 验证Token */ async validateToken(token: string): Promise { try { return this.jwtService.verify(token); } catch { throw new UnauthorizedException('Token无效'); } } }