123 lines
4.1 KiB
TypeScript
123 lines
4.1 KiB
TypeScript
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
|
|
import bcrypt from "bcryptjs";
|
|
import type { FastifyRequest } from "fastify";
|
|
import { AdminAccessService } from "./admin-access.service.js";
|
|
import { PrismaService } from "./prisma.service.js";
|
|
import { signIdentity } from "./auth.js";
|
|
|
|
export type AdminLoginSession = {
|
|
displayName: string;
|
|
role: string;
|
|
platformTemplateRole: "none" | "template_admin";
|
|
mustChangePassword: boolean;
|
|
};
|
|
|
|
export type AdminCurrentSession = AdminLoginSession & { authenticated: true };
|
|
|
|
@Injectable()
|
|
export class AdminAuthService {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly access: AdminAccessService,
|
|
) {}
|
|
|
|
async login(
|
|
username: string,
|
|
password: string,
|
|
): Promise<{ session: AdminLoginSession; token: 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" },
|
|
});
|
|
if (!membership) throw new ForbiddenException("管理员没有品牌权限,请先联系平台负责人分配");
|
|
return {
|
|
session: {
|
|
displayName: user.displayName,
|
|
mustChangePassword: user.mustChangePassword,
|
|
role: membership.role,
|
|
platformTemplateRole: user.platformTemplateRole,
|
|
},
|
|
token: signIdentity({
|
|
subject: user.id,
|
|
brandId: membership.brandId,
|
|
role: "admin",
|
|
tokenVersion: user.tokenVersion,
|
|
}),
|
|
};
|
|
}
|
|
|
|
async currentSession(request: FastifyRequest): Promise<AdminCurrentSession> {
|
|
// current 必须能返回首次登录态;不能先执行 requireBrand 把 mustChangePassword 用户挡在登录页。
|
|
const access = await this.access.requireToken(request);
|
|
const [user, membership] = await Promise.all([
|
|
this.prisma.adminUser.findUniqueOrThrow({
|
|
where: { id: access.subject },
|
|
select: {
|
|
displayName: true,
|
|
mustChangePassword: true,
|
|
platformTemplateRole: true,
|
|
},
|
|
}),
|
|
this.prisma.brandMembership.findUnique({
|
|
where: {
|
|
adminUserId_brandId: { adminUserId: access.subject, brandId: access.brandId },
|
|
},
|
|
}),
|
|
]);
|
|
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
|
|
return {
|
|
authenticated: true,
|
|
displayName: user.displayName,
|
|
mustChangePassword: user.mustChangePassword,
|
|
platformTemplateRole: user.platformTemplateRole,
|
|
role: membership.role,
|
|
};
|
|
}
|
|
|
|
async logout(userId: string): Promise<void> {
|
|
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
|
if (!user?.isEnabled) throw new UnauthorizedException("管理员登录态无效或已过期");
|
|
await this.prisma.adminUser.update({
|
|
where: { id: userId },
|
|
data: { tokenVersion: { increment: 1 } },
|
|
});
|
|
}
|
|
|
|
async changePassword(
|
|
userId: string,
|
|
brandId: string,
|
|
currentPassword: string,
|
|
newPassword: string,
|
|
): Promise<{ token: string }> {
|
|
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
|
if (!user?.isEnabled || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
|
|
throw new UnauthorizedException("当前密码不正确");
|
|
}
|
|
const updated = await this.prisma.adminUser.update({
|
|
where: { id: userId },
|
|
data: {
|
|
passwordHash: await bcrypt.hash(newPassword, 12),
|
|
mustChangePassword: false,
|
|
tokenVersion: { increment: 1 },
|
|
},
|
|
select: { tokenVersion: true },
|
|
});
|
|
return {
|
|
token: signIdentity({
|
|
subject: user.id,
|
|
brandId,
|
|
role: "admin",
|
|
tokenVersion: updated.tokenVersion,
|
|
}),
|
|
};
|
|
}
|
|
}
|