29 lines
967 B
TypeScript
29 lines
967 B
TypeScript
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
|
import bcrypt from "bcryptjs";
|
|
import { PrismaService } from "./prisma.service.js";
|
|
import { signIdentity } from "./auth.js";
|
|
|
|
@Injectable()
|
|
export class AdminAuthService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
async login(username: string, password: string): Promise<{ token: string; displayName: string }> {
|
|
const user = await this.prisma.adminUser.findUnique({ where: { username } });
|
|
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
|
|
throw new UnauthorizedException("账号或密码错误");
|
|
}
|
|
await this.prisma.adminUser.update({
|
|
where: { id: user.id },
|
|
data: { lastLoginAt: new Date() },
|
|
});
|
|
return {
|
|
token: signIdentity({
|
|
subject: user.id,
|
|
brandId: process.env.DEFAULT_BRAND_ID ?? "",
|
|
role: "admin",
|
|
}),
|
|
displayName: user.displayName,
|
|
};
|
|
}
|
|
}
|