From 4f91848e0c8b7bbfce9fa18c18432b7026411d61 Mon Sep 17 00:00:00 2001 From: Lukas Date: Fri, 17 May 2024 09:23:17 +0200 Subject: [PATCH] :bug: Fix session management and api calls --- frontend-react/src/app/api/apiService.ts | 16 ++- frontend-react/src/app/lib/dal.ts | 3 +- frontend-react/src/app/lib/session.ts | 1 + frontend-react/src/app/login/page.tsx | 14 ++- frontend-react/src/app/middleware.ts | 16 +-- frontend-react/src/app/page.tsx | 135 +++------------------- frontend-react/src/app/timetable/page.tsx | 5 +- 7 files changed, 56 insertions(+), 134 deletions(-) diff --git a/frontend-react/src/app/api/apiService.ts b/frontend-react/src/app/api/apiService.ts index d253763..7dc4e02 100644 --- a/frontend-react/src/app/api/apiService.ts +++ b/frontend-react/src/app/api/apiService.ts @@ -11,13 +11,19 @@ export interface ApiResponse { export async function apiRequest(endpoint: string, method: string, body?: any): Promise { const session = await verifySession() - const bearer = session.session + const bearer = session?.session + + let headers: Record = { + 'Content-Type': 'application/json' + }; + + if (bearer) { + headers['Authorization'] = `Bearer ${bearer}`; + } + const response = await fetch(`${API_BASE_URL}/${endpoint}`, { method, - headers: { - 'Content-Type': 'application/json', - Authorization: bearer ? `Bearer ${bearer}` : '', - }, + headers, body: body ? JSON.stringify(body) : null, }); diff --git a/frontend-react/src/app/lib/dal.ts b/frontend-react/src/app/lib/dal.ts index ab9091f..5dcac04 100644 --- a/frontend-react/src/app/lib/dal.ts +++ b/frontend-react/src/app/lib/dal.ts @@ -2,7 +2,6 @@ import {cookies} from 'next/headers' import {decrypt} from '@/app/lib/session' -import {redirect} from "next/navigation"; import {cache} from 'react'; import {apiRequest} from "@/app/api/apiService"; @@ -13,7 +12,7 @@ export const verifySession = cache(async () => { if (!session?.userId) { - redirect('/login') + return null; } return { isAuth: true, userId: session.userId, session: cookie } diff --git a/frontend-react/src/app/lib/session.ts b/frontend-react/src/app/lib/session.ts index 4c10714..a78d508 100644 --- a/frontend-react/src/app/lib/session.ts +++ b/frontend-react/src/app/lib/session.ts @@ -14,6 +14,7 @@ export async function decrypt(session: string | undefined = '') { }) return payload } catch (error) { + console.log(error) console.log('Failed to verify session') } } diff --git a/frontend-react/src/app/login/page.tsx b/frontend-react/src/app/login/page.tsx index 13e9b15..4e2eec3 100644 --- a/frontend-react/src/app/login/page.tsx +++ b/frontend-react/src/app/login/page.tsx @@ -1,12 +1,13 @@ // src/app/login/page.tsx "use client"; -import React, {useState} from 'react'; +import React, {useEffect, useState} from 'react'; import LoginForm from './form/LoginForm'; import {Credentials, InvalidCredentialsError, login} from './services/loginService'; import Toast from '../../app/components/toasts'; import {useRouter} from 'next/navigation'; import {createSession} from "@/app/lib/session"; +import {verifySession} from "@/app/lib/dal"; const LoginPage = () => { const router = useRouter(); @@ -16,6 +17,17 @@ const LoginPage = () => { const [toastType, setToastType] = useState<'success' | 'error'>('success'); const [connectionError, setConnectionError] = useState(false); + // Vérifiez la session dès que le composant est monté + useEffect(() => { + const checkSession = async () => { + const session = await verifySession(); + if (session) { + router.push('/users'); + } + }; + checkSession().then(r => r); + }, [router]); + const handleLogin = async (credentials: Credentials) => { try { const token = await login(credentials); diff --git a/frontend-react/src/app/middleware.ts b/frontend-react/src/app/middleware.ts index c3cc01d..6d8fb72 100644 --- a/frontend-react/src/app/middleware.ts +++ b/frontend-react/src/app/middleware.ts @@ -3,8 +3,8 @@ import {decrypt} from '@/app/lib/session' import {cookies} from 'next/headers' -const protectedRoutes = ['/timetable', '/users'] -const publicRoutes = ['/login', '/register', '/'] +const protectedRoutes = ['/timetable', '/users', '/'] +const publicRoutes = ['/login', '/register'] export default async function middleware(req: NextRequest) { @@ -22,12 +22,12 @@ export default async function middleware(req: NextRequest) { } - if ( - isPublicRoute && - session?.userId && - !req.nextUrl.pathname.startsWith('/timetable') - ) { - return NextResponse.redirect(new URL('/timetable', req.nextUrl)) + if (isPublicRoute && session?.userId) { + if (req.nextUrl.pathname === '/') { + return NextResponse.redirect(new URL('/users', req.nextUrl)) + } else if (!req.nextUrl.pathname.startsWith('/timetable')) { + return NextResponse.redirect(new URL('/timetable', req.nextUrl)) + } } return NextResponse.next() diff --git a/frontend-react/src/app/page.tsx b/frontend-react/src/app/page.tsx index 0aea6a0..8022c99 100644 --- a/frontend-react/src/app/page.tsx +++ b/frontend-react/src/app/page.tsx @@ -1,120 +1,21 @@ -import Image from "next/image"; +"use client"; +import { useEffect } from 'react'; +import { verifySession } from '@/app/lib/dal'; +import {redirect} from "next/navigation"; -export default function Home() { - return ( -
-
-

- Get started by editing  +export default function HomePage() { - src/app/page.tsx -

- -
+ useEffect(() => { + const checkSession = async () => { + const session = await verifySession(); + if (!session) { + console.log('No session'); + } else { + redirect('/users') + } + }; + checkSession().then(r => r); + }, []); -
- Next.js Logo -
- - -
- ); -} + return
Loading...
; +} \ No newline at end of file diff --git a/frontend-react/src/app/timetable/page.tsx b/frontend-react/src/app/timetable/page.tsx index 98570fd..1a3074a 100644 --- a/frontend-react/src/app/timetable/page.tsx +++ b/frontend-react/src/app/timetable/page.tsx @@ -10,6 +10,7 @@ import Arrow from "@/app/components/arrows"; import {getUser, verifySession} from "@/app/lib/dal"; import {getClassGroupById} from "@/app/api/services/classgroupService"; import {User} from "@/app/models/user"; +import {router} from "next/client"; export default function Timetable() { @@ -18,7 +19,7 @@ export default function Timetable() { const fullYear = new Date().getFullYear(); // e.g., 2024 const lastTwoDigits = fullYear % 100; // e.g., 24 const [currentYear] = useState(lastTwoDigits); - const [user, setUser] = useState(null); + const [, setUser] = useState(null); useEffect(() => { verifySession().then(session => { @@ -34,6 +35,8 @@ export default function Timetable() { }; fetchTimeTable(); }); + } else { + router.push('/login').then(r => r); } }); }, []);