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,21 +1,29 @@
'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(() => {
if (session) {
navigate.push("/");
}
}, [session, navigate]);
useEffect(() => { useEffect(() => {
const signInWithCode = async () => { const signInWithCode = async () => {
const code = searchParams.get('code'); const code = searchParams.get("code");
if (code) { if (code) {
setIsLoading(true); setIsLoading(true);
await signIn('credentials', { await signIn("credentials", {
code: code, code: code,
callbackUrl: '/', callbackUrl: "/",
}); });
setIsLoading(false); setIsLoading(false);
} }
@@ -30,7 +38,7 @@ export const Login = () => {
</div> </div>
<h1 className="text-3xl font-bold">Login</h1> <h1 className="text-3xl font-bold">Login</h1>
<span className="text-sm font-medium"> <span className="text-sm font-medium">
Noch keinen Account? Zur{' '} Noch keinen Account? Zur{" "}
<a <a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/register`} href={`${process.env.NEXT_PUBLIC_HUB_URL}/register`}
className="link link-accent link-hover" className="link link-accent link-hover"
@@ -41,7 +49,7 @@ export const Login = () => {
<div className="form-control mt-6"> <div className="form-control mt-6">
<a <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`)}`} 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 <button
className="btn btn-primary" className="btn btn-primary"
@@ -51,7 +59,7 @@ export const Login = () => {
{isLoading && ( {isLoading && (
<span className="loading loading-spinner loading-sm"></span> <span className="loading loading-spinner loading-sm"></span>
)} )}
Login{isLoading && '...'} Login{isLoading && "..."}
</button> </button>
</a> </a>
</div> </div>

View File

@@ -1,21 +1,20 @@
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,
@@ -31,21 +30,34 @@ export const options: AuthOptions = {
return user; return user;
} catch (error) { } catch (error) {
console.error(error);
return null; return null;
} }
}, },
}), }),
], ],
secret: process.env.NEXTAUTH_SECRET, 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: "/",
},
},
},
session: { session: {
strategy: 'jwt', strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, maxAge: 30 * 24 * 60 * 60,
}, },
adapter: PrismaAdapter(prisma as any), adapter: PrismaAdapter(prisma as any),
callbacks: { callbacks: {
jwt: async ({ token, user }) => { jwt: async ({ token, user }) => {
if (user && 'firstname' in user) { if (user && "firstname" in user) {
return { return {
...token, ...token,
...user, ...user,
@@ -61,9 +73,9 @@ export const options: AuthOptions = {
}, },
}, },
pages: { pages: {
signIn: '/login', signIn: "/login",
signOut: '/logout', signOut: "/logout",
error: '/authError', error: "/authError",
}, },
} satisfies AuthOptions; } satisfies AuthOptions;