-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.ts
45 lines (41 loc) · 1.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
import type { NextRequest } from "next/server";
import axios from "axios";
import { apiURL } from "./app/components/apiURL";
export async function middleware(request: NextRequest) {
if (
request.nextUrl.pathname === "/dashboard" ||
request.nextUrl.pathname === "/login"
) {
let currentUser = false;
let results;
let token = request.cookies.get("token")?.value;
try {
results = await axios({
method: "post",
url: apiURL + "/auth/verifyToken",
headers: { Authorization: "Bearer " + token },
});
} catch (err: any) {
results = err.response;
}
if (results?.status === 200) {
currentUser = true;
} else {
currentUser = false;
}
if (currentUser && !request.nextUrl.pathname.startsWith("/dashboard")) {
return Response.redirect(new URL("/dashboard", request.url));
}
if (currentUser && request.nextUrl.pathname.startsWith("/login")) {
return Response.redirect(new URL("/dashboard", request.url));
}
} else if (request.nextUrl.pathname === "/") {
let token = request.cookies.get("token")?.value;
if (token) {
return Response.redirect(new URL("/dashboard", request.url));
}
}
}
export const config = {
matcher: ["/dashboard", "/login", "/", "/portfolio"],
};