-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
72 lines (68 loc) · 2.42 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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import verifyIdToken from "./shared/functions/verifyIdToken";
import { JWTExpired } from "jose/dist/types/util/errors";
import { JWTPayload } from "jose";
const protectedRoutes = [`/dashboard`, `/people`, `/tasks`, `/tools`, `/crm`];
const authRoutes = [`/login`, `/signup`];
export default async function middleware(req: NextRequest) {
let token = req.cookies.get("token");
let tokenExpired = false;
let decodedToken: void | JWTPayload;
if (token) {
decodedToken = await verifyIdToken(token.value).catch((err: JWTExpired) => {
console.log("IdToken expired", err);
tokenExpired = true;
});
}
const userId = decodedToken?.user_id ?? req.cookies.get("uid");
const userVerified = decodedToken?.user_id ? true : false;
const emailVerified = decodedToken?.email_verified as boolean;
let url = req.nextUrl.clone();
let siteUrl = url.origin;
if (tokenExpired) {
//refresh page if token is expired
return NextResponse.redirect(url);
}
// If user verified but email not verified and tries to access protected pages redirect to onboarding page
if (
userVerified &&
!emailVerified &&
protectedRoutes.some((route) => url.pathname.includes(route))
) {
return NextResponse.redirect(`${siteUrl}/auth/signup/verifyEmail`);
}
// If user not verified and tries to access dashboard redirect to login page
if (
!userVerified &&
!emailVerified &&
protectedRoutes.some((route) => url.pathname.includes(route))
) {
return NextResponse.redirect(`${siteUrl}/auth/login`);
}
// If user verified and tries to access auth pages redirect to dashboard page
if (
userVerified &&
emailVerified &&
authRoutes.some((route) => url.pathname.includes(route))
) {
return NextResponse.redirect(`${siteUrl}/dashboard`);
}
// console.log({
// host: url.host,
// hostname: url.hostname,
// locale: url.locale,
// domainLocale: url.domainLocale,
// defaultLocale: url.defaultLocale,
// url: url.pathname,
// emailVerified: emailVerified,
// userVerified: userVerified,
// tokenExists: !!token,
// tokenExpired: tokenExpired,
// landingPage: url.pathname == "/",
// protectedRoute: protectedRoutes.some((route) =>
// url.pathname.includes(route)
// ),
// authRoute: authRoutes.some((route) => url.pathname.includes(route)),
// });
}