-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
47 lines (41 loc) · 1.62 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
import { NextRequest, NextResponse } from "next/server";
import { isUserModel } from "./base/data/models/UserModel";
import { COOKIE_USER_AUTH } from "./app/helpers/Constants";
export const config = {
matcher: ["/write/", "/user/posts/", "/auth/", "/profile/"],
};
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
try {
const pathname = request.nextUrl.pathname.toLowerCase()+"/";
// check if user requested to access to protected routes without authenticating
// a.k.a tresspassing
// by checking their cookies
const auth = request.cookies.get(COOKIE_USER_AUTH) || "";
let isCookieValid;
try {
isCookieValid = isUserModel(JSON.parse(auth) as unknown);
} catch {
isCookieValid = false;
}
// matching requested route to the protected routes array
const isTresspassing =!!config.matcher.find((e)=>e.includes(pathname));
const onAuthPage = pathname.includes("/auth/");
// if invalid
if (!isCookieValid) {
// if tresspassing and not on auth page, then redirect to auth
if (isTresspassing && !onAuthPage)
return NextResponse.redirect(new URL("/auth", request.url));
// if not trespassing, then don't redirect
return NextResponse.next();
}
// if valid
// if valid and accessing /auth, then redirect to profile
if (onAuthPage) return NextResponse.redirect(new URL("/", request.url));
// if not accessing auth, then don't redirect
return NextResponse.next();
} catch (e) {
console.error(e);
NextResponse.redirect(new URL("/", request.url));
}
}