7 roles: TECHNICAL, MANNING, ACCOUNTS, MANAGER, SUPERUSER, AUDITOR, ADMIN. hasPermission / requirePermission helpers used across all server actions. Login page with email + bcrypt password auth. Middleware protects all portal routes.
61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
import NextAuth from "next-auth";
|
|
import Credentials from "next-auth/providers/credentials";
|
|
import bcrypt from "bcryptjs";
|
|
import { db } from "@/lib/db";
|
|
import { loginSchema } from "@/lib/validations/user";
|
|
import type { Role } from "@prisma/client";
|
|
|
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
|
session: { strategy: "jwt" },
|
|
pages: {
|
|
signIn: "/login",
|
|
error: "/login",
|
|
},
|
|
providers: [
|
|
Credentials({
|
|
credentials: {
|
|
email: { label: "Email", type: "email" },
|
|
password: { label: "Password", type: "password" },
|
|
},
|
|
async authorize(credentials) {
|
|
const parsed = loginSchema.safeParse(credentials);
|
|
if (!parsed.success) return null;
|
|
|
|
const user = await db.user.findUnique({
|
|
where: { email: parsed.data.email },
|
|
});
|
|
if (!user || !user.isActive) return null;
|
|
|
|
const valid = await bcrypt.compare(parsed.data.password, user.passwordHash);
|
|
if (!valid) return null;
|
|
|
|
return { id: user.id, email: user.email, name: user.name, role: user.role };
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
jwt({ token, user }) {
|
|
if (user) {
|
|
token.id = user.id;
|
|
token.role = (user as unknown as { role: Role }).role;
|
|
}
|
|
return token;
|
|
},
|
|
session({ session, token }) {
|
|
session.user.id = token.id as string;
|
|
session.user.role = token.role as Role;
|
|
return session;
|
|
},
|
|
},
|
|
});
|
|
|
|
declare module "next-auth" {
|
|
interface Session {
|
|
user: {
|
|
id: string;
|
|
name: string;
|
|
email: string;
|
|
role: Role;
|
|
};
|
|
}
|
|
}
|