-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
82 lines (69 loc) · 2.41 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
import { NextResponse, NextRequest } from "next/server";
import { verify } from "@/helpers/jwt_sign_verify";
export async function middleware(request: NextRequest) {
let path = request.nextUrl.pathname;
const isPublicPath =
path === "/signin" || path === "/signup" || path === "/welcome";
const excludedEndpoints = ["/api/logout", "/api/signin", "/api/signup"];
const token = request.cookies.get("token")?.value || "";
const secretKey = process.env.JWT_SECRET_KEY!;
if (!path.startsWith("/api")) {
if ((isPublicPath || path === "/") && token) {
try {
await verify(token, secretKey);
const redirectTo = new URL("/dashboard/home", request.nextUrl);
return NextResponse.redirect(redirectTo);
} catch (error) {
console.error("Error during token verification:", error);
}
}
// that will run if the user is already complited his profile and trying to access the complete Profile page again
if (path == "/completeProfile") {
try {
const {
payload: { isCompleted, type },
}: any = await verify(token, secretKey);
console.log(isCompleted);
console.log(type);
if (type == "freelancer" && isCompleted == true) {
return NextResponse.redirect(
new URL("/dashboard/home", request.nextUrl)
);
}
} catch (error) {}
}
// that condition will run if the user as type freelancer not complited his registration
if (path == "/dashboard/home") {
try {
const {
payload: { isCompleted, type },
}: any = await verify(token, secretKey);
if (type == "freelancer" && isCompleted == false) {
return NextResponse.redirect(
new URL("/completeProfile", request.nextUrl)
);
}
} catch (error) {
return NextResponse.redirect(new URL("/welcome", request.nextUrl));
}
}
if (!isPublicPath && !token) {
return NextResponse.redirect(new URL("/welcome", request.nextUrl));
}
}
if (path.startsWith("/api") && !excludedEndpoints.includes(path)) {
try {
await verify(token, secretKey);
} catch (error) {
return NextResponse.json(
{
message: "You are not authorized . Please login!",
},
{ status: 401 }
);
}
}
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)", "/api/:path*"],
};