72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
import NextAuth from "next-auth";
|
|
import Credentials from "next-auth/providers/credentials";
|
|
import { prisma } from "./prisma";
|
|
import bcrypt from "bcryptjs";
|
|
import type { Role } from "@/prisma/generated/prisma/client";
|
|
|
|
export const { handlers, signIn, signOut, auth } = NextAuth({
|
|
trustHost: true,
|
|
providers: [
|
|
Credentials({
|
|
credentials: {
|
|
email: { label: "Email", type: "email" },
|
|
password: { label: "Password", type: "password" },
|
|
},
|
|
authorize: async (credentials) => {
|
|
if (!credentials?.email || !credentials?.password) {
|
|
return null;
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { email: credentials.email as string },
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const isPasswordValid = await bcrypt.compare(
|
|
credentials.password as string,
|
|
user.password
|
|
);
|
|
|
|
if (!isPasswordValid) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
username: user.username,
|
|
role: user.role,
|
|
};
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
jwt: async ({ token, user }) => {
|
|
if (user) {
|
|
token.id = user.id;
|
|
token.username = user.username;
|
|
token.role = user.role;
|
|
}
|
|
return token;
|
|
},
|
|
session: async ({ session, token }) => {
|
|
if (session.user && token) {
|
|
session.user.id = token.id as string;
|
|
session.user.username = token.username as string;
|
|
session.user.role = token.role as Role;
|
|
}
|
|
return session;
|
|
},
|
|
},
|
|
pages: {
|
|
signIn: "/login",
|
|
},
|
|
session: {
|
|
strategy: "jwt",
|
|
},
|
|
});
|
|
|