omnics / apps /api /src /modules /auth /services /auth.service.ts
qf46578's picture
🦞 [记忆压缩#1] 轮次 1-10 已完成 + 全量代码同步 - 核心功能就绪
3fe8ff2 verified
Raw History Blame Contribute Delete
1.37 kB
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<LoginResult> {
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<any> {
try {
return this.jwtService.verify(token);
} catch {
throw new UnauthorizedException('Token无效');
}
}
}