-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
69 lines (59 loc) · 2.06 KB
/
Copy pathmiddleware.ts
File metadata and controls
69 lines (59 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { NextResponse, NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
// Chemins publics qui ne nécessitent pas d'authentification
const publicPaths = [
'/',
'/register',
'/api/register',
'/favicon.ico',
'/images/icon-dark.svg',
'/images/icon-light.svg',
];
// Fonction pour vérifier si le chemin est public
const isPublicPath = (path: string) => {
if (
path.startsWith('/_next') ||
path.startsWith('/api/auth') ||
path.startsWith('/api/public') ||
path.startsWith('/favicon') ||
path.match(/^\/(icon).*\.(svg)$/)
) {
return true;
}
return publicPaths.includes(path);
};
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Si le chemin est public, on laisse passer
if (isPublicPath(pathname)) {
return NextResponse.next();
}
// Récupérer le token JWT depuis les cookies
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET
});
// Si pas de token, rediriger vers la page de connexion
if (!token) {
//console.log(`[Middleware] Non authentifié, redirection depuis ${pathname} vers la page de connexion`);
const url = new URL('/', request.url);
// Ajouter le chemin d'origine comme callback URL pour rediriger après connexion
url.searchParams.set('callbackUrl', request.url);
return NextResponse.redirect(url);
}
// Vérifier les autorisations pour les chemins admin
if (pathname.startsWith('/admin')) {
const isAdmin = token.isAdmin === true;
if (!isAdmin) {
//console.log(`[Middleware] Accès admin refusé pour ${token.number}, redirection vers le dashboard`);
// Rediriger vers le tableau de bord si l'utilisateur n'est pas admin
return NextResponse.redirect(new URL('/dashboard', request.url));
}
}
// Si tout est en ordre, on laisse passer
return NextResponse.next();
}
// Configuration pour indiquer sur quels chemins le middleware doit s'exécuter
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};