Skip to content

Commit

Permalink
🐛 Fix session management and api calls
Browse files Browse the repository at this point in the history
  • Loading branch information
PHPLukaas committed May 17, 2024
1 parent 9c2c40d commit 4f91848
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 134 deletions.
16 changes: 11 additions & 5 deletions frontend-react/src/app/api/apiService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,19 @@ export interface ApiResponse {

export async function apiRequest(endpoint: string, method: string, body?: any): Promise<ApiResponse> {
const session = await verifySession()
const bearer = session.session
const bearer = session?.session

let headers: Record<string, string> = {
'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,
});

Expand Down
3 changes: 1 addition & 2 deletions frontend-react/src/app/lib/dal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -13,7 +12,7 @@ export const verifySession = cache(async () => {

if (!session?.userId) {

redirect('/login')
return null;
}

return { isAuth: true, userId: session.userId, session: cookie }
Expand Down
1 change: 1 addition & 0 deletions frontend-react/src/app/lib/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export async function decrypt(session: string | undefined = '') {
})
return payload
} catch (error) {
console.log(error)
console.log('Failed to verify session')
}
}
Expand Down
14 changes: 13 additions & 1 deletion frontend-react/src/app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -16,6 +17,17 @@ const LoginPage = () => {
const [toastType, setToastType] = useState<'success' | 'error'>('success');
const [connectionError, setConnectionError] = useState<boolean>(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);
Expand Down
16 changes: 8 additions & 8 deletions frontend-react/src/app/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Expand All @@ -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()
Expand Down
135 changes: 18 additions & 117 deletions frontend-react/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex">
<p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30">
Get started by editing&nbsp;
export default function HomePage() {

<code className="font-mono font-bold">src/app/page.tsx</code>
</p>
<div
className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:size-auto lg:bg-none">
<a
className="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0"
href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
By{" "}
<Image
src="/vercel.svg"
alt="Vercel Logo"
className="dark:invert"
width={100}
height={24}
priority
/>
</a>
</div>
</div>
useEffect(() => {
const checkSession = async () => {
const session = await verifySession();
if (!session) {
console.log('No session');
} else {
redirect('/users')
}
};
checkSession().then(r => r);
}, []);

<div
className="relative z-[-1] flex place-items-center before:absolute before:h-[300px] before:w-full before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-full after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 sm:before:w-[480px] sm:after:w-[240px] before:lg:h-[360px]">
<Image
className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert"
src="/next.svg"
alt="Next.js Logo"
width={180}
height={37}
priority
/>
</div>

<div className="mb-32 grid text-center lg:mb-0 lg:w-full lg:max-w-5xl lg:grid-cols-4 lg:text-left">
<a
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Docs{" "}
<span
className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Find in-depth information about Next.js features and API.
</p>
</a>

<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Learn{" "}
<span
className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Learn about Next.js in an interactive course with&nbsp;quizzes!
</p>
</a>

<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Templates{" "}
<span
className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Explore starter templates for Next.js.
</p>
</a>

<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Deploy{" "}
<span
className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-balance text-sm opacity-50">
Instantly deploy your Next.js site to a shareable URL with Vercel.
</p>
</a>
</div>
</main>
);
}
return <div>Loading...</div>;
}
5 changes: 4 additions & 1 deletion frontend-react/src/app/timetable/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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() {

Expand All @@ -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<number>(lastTwoDigits);
const [user, setUser] = useState<User | null>(null);
const [, setUser] = useState<User | null>(null);

useEffect(() => {
verifySession().then(session => {
Expand All @@ -34,6 +35,8 @@ export default function Timetable() {
};
fetchTimeTable();
});
} else {
router.push('/login').then(r => r);
}
});
}, []);
Expand Down

0 comments on commit 4f91848

Please sign in to comment.