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,2 +1,3 @@
NEXT_PUBLIC_HUB_URL= NEXT_PUBLIC_HUB_URL=
NEXT_PUBLIC_SERVICE_ID= NEXT_PUBLIC_SERVICE_ID=
NEXTAUTH_SECRET=

View File

@@ -1,60 +1,68 @@
'use client'; "use client";
import { signIn } from 'next-auth/react'; import { signIn, useSession } from "next-auth/react";
import { useSearchParams } from 'next/navigation'; import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from 'react'; import { useEffect, useState } from "react";
import { Toaster } from 'react-hot-toast'; import { Toaster } from "react-hot-toast";
export const Login = () => { export const Login = () => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { data: session } = useSession();
const navigate = useRouter();
useEffect(() => { useEffect(() => {
const signInWithCode = async () => { if (session) {
const code = searchParams.get('code'); navigate.push("/");
if (code) { }
setIsLoading(true); }, [session, navigate]);
await signIn('credentials', {
code: code,
callbackUrl: '/',
});
setIsLoading(false);
}
};
signInWithCode();
}, [searchParams]);
return ( useEffect(() => {
<div className="card-body"> const signInWithCode = async () => {
<div> const code = searchParams.get("code");
<Toaster position="top-center" reverseOrder={false} /> if (code) {
</div> setIsLoading(true);
<h1 className="text-3xl font-bold">Login</h1> await signIn("credentials", {
<span className="text-sm font-medium"> code: code,
Noch keinen Account? Zur{' '} callbackUrl: "/",
<a });
href={`${process.env.NEXT_PUBLIC_HUB_URL}/register`} setIsLoading(false);
className="link link-accent link-hover" }
> };
Registrierung signInWithCode();
</a> }, [searchParams]);
</span>
<div className="form-control mt-6"> return (
<a <div className="card-body">
href={`${process.env.NEXT_PUBLIC_HUB_URL}/oauth?service=${encodeURIComponent(process.env.NEXT_PUBLIC_SERVICE_ID || '')}&redirect_uri=${encodeURIComponent(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/login`)}`} <div>
> <Toaster position="top-center" reverseOrder={false} />
<button </div>
className="btn btn-primary" <h1 className="text-3xl font-bold">Login</h1>
name="loginBtn" <span className="text-sm font-medium">
disabled={isLoading} Noch keinen Account? Zur{" "}
> <a
{isLoading && ( href={`${process.env.NEXT_PUBLIC_HUB_URL}/register`}
<span className="loading loading-spinner loading-sm"></span> className="link link-accent link-hover"
)} >
Login{isLoading && '...'} Registrierung
</button> </a>
</a> </span>
</div>
</div> <div className="form-control mt-6">
); <a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/oauth?service=${encodeURIComponent(process.env.NEXT_PUBLIC_SERVICE_ID || "")}&redirect_uri=${encodeURIComponent(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/login`)}`}
>
<button
className="btn btn-primary"
name="loginBtn"
disabled={isLoading}
>
{isLoading && (
<span className="loading loading-spinner loading-sm"></span>
)}
Login{isLoading && "..."}
</button>
</a>
</div>
</div>
);
}; };

View File

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