Files
liandong-crm/src/lib/auth.ts
T

74 lines
2.3 KiB
TypeScript
Raw Normal View History

import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { authConfig } from "@/lib/auth.config";
/**
* 读取某个后台账号的角色名与权限码(走现有 spatie 关联表)。
*/
async function loadAcl(adminId: number) {
const modelRoles = await prisma.modelHasRole.findMany({
where: { modelId: adminId, modelType: "App\\Model\\Admin" },
select: { roleId: true },
});
const roleIds = modelRoles.map((r) => r.roleId);
if (roleIds.length === 0) return { roles: [], permissions: [] };
const [roles, rolePerms] = await Promise.all([
prisma.role.findMany({ where: { id: { in: roleIds } }, select: { name: true } }),
prisma.roleHasPermission.findMany({
where: { roleId: { in: roleIds } },
select: { permissionId: true },
}),
]);
const permIds = [...new Set(rolePerms.map((p) => p.permissionId))];
const perms = permIds.length
? await prisma.permission.findMany({
where: { id: { in: permIds } },
select: { name: true },
})
: [];
return {
roles: roles.map((r) => r.name),
permissions: perms.map((p) => p.name),
};
}
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
credentials: {
username: { label: "用户名" },
password: { label: "密码", type: "password" },
},
authorize: async (credentials) => {
const username = String(credentials?.username ?? "").trim();
const password = String(credentials?.password ?? "");
if (!username || !password) return null;
const admin = await prisma.admin.findUnique({ where: { username } });
// 软删除账号不允许登录
if (!admin || admin.deletedAt) return null;
// 复用 Laravel bcrypt($2y$)哈希,老账号密码原样可登录
const ok = await bcrypt.compare(password, admin.password);
if (!ok) return null;
const acl = await loadAcl(admin.id);
return {
id: String(admin.id),
name: admin.nickname || admin.username,
username: admin.username,
image: admin.face ?? null,
roles: acl.roles,
permissions: acl.permissions,
};
},
}),
],
});