-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
103 lines (85 loc) · 2.28 KB
/
middleware.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { NextRequest, NextResponse } from "next/server";
import { Routes } from "@/app/routes";
// Routes that only authenticated users can access
const authRoutes = [
Routes.DASHBOARD,
Routes.PROFILE,
Routes.MANAGE_CONTESTS,
Routes.MANAGE_CONTESTS,
];
const authRoutesWithId = [`${Routes.CONTESTS}/:id/register`];
// Routes that only non-authenticated users can access
const nonAuthRoutes = [Routes.LOGIN, Routes.REGISTER];
const isAuthorised = (request: NextRequest) => {
if (
authRoutes.some((route) => request.nextUrl.pathname.startsWith(route)) &&
!request.cookies.has("token")
) {
return false;
}
for (let i = 0; i < authRoutesWithId.length; i++) {
const route = authRoutesWithId[i];
const routeParts = route.split("/");
const requestParts = request.nextUrl.pathname.split("/");
if (routeParts.length !== requestParts.length) {
continue;
}
let match = true;
for (let i = 0; i < routeParts.length; i++) {
if (routeParts[i] === ":id") {
continue;
}
if (routeParts[i] !== requestParts[i]) {
match = false;
break;
}
}
if (match && !request.cookies.has("token")) {
return false;
}
}
return true;
};
const isNonAuthorised = (request: NextRequest) => {
if (
!nonAuthRoutes.some((route) => request.nextUrl.pathname.startsWith(route))
) {
return true;
}
if (
nonAuthRoutes.some((route) => request.nextUrl.pathname.startsWith(route)) &&
request.cookies.has("token")
) {
return false;
}
return true;
};
export function middleware(request: NextRequest) {
// Special case for the home page
if (request.nextUrl.pathname === "/") {
if (request.cookies.has("token")) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
if (!isAuthorised(request)) {
return NextResponse.redirect(
new URL(`/login?redirect=${request.nextUrl.pathname}`, request.url)
);
}
if (!isNonAuthorised(request)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/",
"/login",
"/register",
"/dashboard",
"/profile",
"/contests/:path*",
"/contests/manage/:path*",
],
};