-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
102 lines (86 loc) · 2.19 KB
/
middleware.ts
File metadata and controls
102 lines (86 loc) · 2.19 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
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
import { getToken } from 'next-auth/jwt';
import { NextRequest, NextResponse } from 'next/server';
// https://github.com/TusharVashishth/Nextjs_Authentication/blob/main/src/middleware.ts
export async function middleware(req: NextRequest) {
const unprotectedRoutes = [
"/",
"/landing",
"/signup",
"/login"
];
const unprotectedBeginningRoutes = [
"/favicon.ico",
"/_next/static",
"/_next/image",
"/api/auth",
"/public"
];
const unprotectedEndingRoutes = [
".jpeg",
".jpg",
".png"
];
//console.log("middleware is here");
const { pathname } = req.nextUrl;
//console.log("PATHNAME: ", pathname)
// console.log(req.url)
// console.log(pathname);
if (pathname == "/api/auth/signin") {
//console.log("signin page!")
return NextResponse.next();
}
const token = await getToken({ req });
if (token == null) {
//console.log("NO TOKEN!!!!!!!")
if (
!(
unprotectedRoutes.includes(pathname) ||
pathnameBeginsWithAny(pathname, unprotectedBeginningRoutes) ||
pathnameEndsWithAny(pathname, unprotectedEndingRoutes)
)
) {
//console.log("NO TOKEN BLOCKED: ", pathname);
return NextResponse.redirect(
new URL(
"/api/auth/signin", req.url
)
);
}
else {
//console.log("NO TOKEN ALLOWED: ", pathname);
return NextResponse.next();
}
}
//console.log("signed in! going to ", pathname)
// Is signed in, and trying to access landing page
if (
unprotectedRoutes.includes(pathname)
) {
//console.log("IN SECOND")
return NextResponse.next();
}
//console.log("END OF CHECKS!!!")
return NextResponse.next();
}
function addCallbackURL(pathname: string, base:string, callbackURL: string) {
const inputURL = new URL (pathname, base);
inputURL.searchParams.set('callbackURL', callbackURL);
//console.log("Callback Added: ", inputURL.toString())
return inputURL;
}
function pathnameBeginsWithAny(pathname: string, routeBeginnings: string[]) {
for (let prefix of routeBeginnings) {
if (pathname.startsWith(prefix)) {
return true;
}
}
return false;
}
function pathnameEndsWithAny(pathname: string, routeBeginnings: string[]) {
for (let postfix of routeBeginnings) {
if (pathname.endsWith(postfix)) {
return true;
}
}
return false;
}