111 lines
2.8 KiB
TypeScript
111 lines
2.8 KiB
TypeScript
import { AuthOptions, getServerSession as getNextAuthServerSession } from "next-auth";
|
|
import { PrismaAdapter } from "@next-auth/prisma-adapter";
|
|
import Credentials from "next-auth/providers/credentials";
|
|
import { prisma } from "@repo/db";
|
|
import bcrypt from "bcryptjs";
|
|
import oldUser from "./var.User.json";
|
|
import { createNewUserFromOld, OldUser } from "../../../../types/oldUser";
|
|
import { sendVerificationLink } from "(app)/admin/user/action";
|
|
|
|
export const options: AuthOptions = {
|
|
providers: [
|
|
Credentials({
|
|
credentials: {
|
|
email: { label: "Email", type: "email", placeholder: "E-Mail" },
|
|
password: { label: "Password", type: "password" },
|
|
},
|
|
async authorize(credentials) {
|
|
try {
|
|
if (!credentials) throw new Error("No credentials provided");
|
|
const user = await prisma.user.findFirst({
|
|
where: {
|
|
email: {
|
|
contains: credentials.email,
|
|
mode: "insensitive",
|
|
},
|
|
},
|
|
});
|
|
const v1User = (oldUser as OldUser[]).find(
|
|
(u) => u.email.toLowerCase() === credentials.email,
|
|
);
|
|
if (!user && v1User) {
|
|
if (bcrypt.compareSync(credentials.password, v1User.password)) {
|
|
const newUser = await createNewUserFromOld(v1User);
|
|
await sendVerificationLink(newUser.id);
|
|
return newUser;
|
|
}
|
|
}
|
|
if (!user) return null;
|
|
|
|
if (bcrypt.compareSync(credentials.password, user.password)) {
|
|
return user;
|
|
}
|
|
return null;
|
|
} catch (error) {
|
|
console.error("Error during authorization:", error);
|
|
return null;
|
|
}
|
|
},
|
|
}),
|
|
],
|
|
|
|
secret: process.env.AUTH_HUB_SECRET,
|
|
session: {
|
|
strategy: "jwt",
|
|
maxAge: 30 * 24 * 60 * 60,
|
|
},
|
|
cookies: {
|
|
sessionToken: {
|
|
name: `${process.env.AUTH_HUB_COOKIE_PREFIX}-next-auth.session-token`, // Ändere den Namen für App 1
|
|
options: {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === "production",
|
|
path: "/",
|
|
},
|
|
},
|
|
csrfToken: {
|
|
name: `${process.env.AUTH_HUB_COOKIE_PREFIX}-next-auth.csrf-token`,
|
|
options: {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === "production",
|
|
path: "/",
|
|
},
|
|
},
|
|
},
|
|
adapter: PrismaAdapter(prisma),
|
|
callbacks: {
|
|
jwt: async ({ token, user }) => {
|
|
if (user && "firstname" in user) {
|
|
return {
|
|
...token,
|
|
...user,
|
|
};
|
|
}
|
|
return token;
|
|
},
|
|
session: async ({ session, token }) => {
|
|
const dbUser = await prisma.user.findUnique({
|
|
where: {
|
|
id: token?.sub,
|
|
},
|
|
});
|
|
if (!dbUser) {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
return null as any;
|
|
}
|
|
return {
|
|
...session,
|
|
user: dbUser,
|
|
};
|
|
},
|
|
},
|
|
pages: {
|
|
signIn: "/login",
|
|
signOut: "/logout",
|
|
error: "/authError",
|
|
newUser: "/register",
|
|
},
|
|
} satisfies AuthOptions;
|
|
|
|
export const getServerSession = async () => getNextAuthServerSession(options);
|