Fixed login bug when one app users the jwt of the other

This commit is contained in:
PxlLoewe
2025-03-11 20:07:53 -07:00
parent 638c561211
commit 3362c98781
3 changed files with 137 additions and 116 deletions

View File

@@ -1,70 +1,82 @@
import {
AuthOptions,
getServerSession as getNextAuthServerSession,
} from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import Credentials from 'next-auth/providers/credentials';
import { PrismaClient } from '@repo/db';
const prisma = new PrismaClient();
AuthOptions,
getServerSession as getNextAuthServerSession,
} from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import Credentials from "next-auth/providers/credentials";
import { prisma, PrismaClient } from "@repo/db";
export const options: AuthOptions = {
providers: [
Credentials({
credentials: {
code: { label: 'code', type: 'code' },
},
async authorize(credentials, req) {
try {
if (!credentials) throw new Error('No credentials provided');
const code = await prisma.oAuthToken.findFirstOrThrow({
where: {
accessToken: credentials.code,
},
});
const user = await prisma.user.findFirstOrThrow({
where: {
id: code.userId,
},
});
providers: [
Credentials({
credentials: {
code: { label: "code", type: "code" },
},
async authorize(credentials, req) {
try {
if (!credentials) throw new Error("No credentials provided");
const code = await prisma.oAuthToken.findFirstOrThrow({
where: {
accessToken: credentials.code,
},
});
const user = await prisma.user.findFirstOrThrow({
where: {
id: code.userId,
},
});
if (!user) return null;
if (!user) return null;
return user;
} catch (error) {
return null;
}
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60,
},
return user;
} catch (error) {
console.error(error);
return null;
}
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
cookies: {
sessionToken: {
name: `next-auth.session-token-${process.env.NEXTAUTH_URL}`,
options: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
},
},
},
adapter: PrismaAdapter(prisma as any),
callbacks: {
jwt: async ({ token, user }) => {
if (user && 'firstname' in user) {
return {
...token,
...user,
};
}
return token;
},
session: async ({ session, user, token }) => {
return {
...session,
user: token,
};
},
},
pages: {
signIn: '/login',
signOut: '/logout',
error: '/authError',
},
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60,
},
adapter: PrismaAdapter(prisma as any),
callbacks: {
jwt: async ({ token, user }) => {
if (user && "firstname" in user) {
return {
...token,
...user,
};
}
return token;
},
session: async ({ session, user, token }) => {
return {
...session,
user: token,
};
},
},
pages: {
signIn: "/login",
signOut: "/logout",
error: "/authError",
},
} satisfies AuthOptions;
export const getServerSession = async () => getNextAuthServerSession(options);