feat: add admin authentication
This commit is contained in:
1 parent
b89853bc94
commit
bb5ccb1359
9 files changed
+85
-1
No files matched your search
@@ -0,0 +1,30 @@
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { compare } 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 } });
|
||||
// bcryptjs ships incomplete typings in this dependency version.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
if (!user || !user.isEnabled || !(await 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user