62 lines
2.0 KiB
TypeScript
62 lines
2.0 KiB
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; mustChangePassword: boolean; role: 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() },
|
|
});
|
|
const membership = await this.prisma.brandMembership.findFirst({
|
|
where: { adminUserId: user.id, isEnabled: true },
|
|
orderBy: { createdAt: "asc" },
|
|
});
|
|
const activeMembership =
|
|
membership ??
|
|
(await this.prisma.brandMembership.create({
|
|
data: {
|
|
adminUserId: user.id,
|
|
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
role: "owner",
|
|
},
|
|
}));
|
|
return {
|
|
token: signIdentity({
|
|
subject: user.id,
|
|
brandId: activeMembership.brandId,
|
|
role: "admin",
|
|
}),
|
|
displayName: user.displayName,
|
|
mustChangePassword: user.mustChangePassword,
|
|
role: activeMembership.role,
|
|
};
|
|
}
|
|
|
|
async changePassword(
|
|
userId: string,
|
|
currentPassword: string,
|
|
newPassword: string,
|
|
): Promise<void> {
|
|
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
|
if (!user || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
|
|
throw new UnauthorizedException("当前密码不正确");
|
|
}
|
|
await this.prisma.adminUser.update({
|
|
where: { id: userId },
|
|
data: { passwordHash: await bcrypt.hash(newPassword, 12), mustChangePassword: false },
|
|
});
|
|
}
|
|
}
|