|
1 | 1 | import { dashboardApi } from "apis/auth/dashboardApi";
|
| 2 | +import { cookieKey } from "constants/cookieKey"; |
| 3 | +import { clientUrl } from "constants/url"; |
2 | 4 | import { cookies } from "next/headers";
|
3 |
| -import type { NextRequest } from "next/server"; |
4 | 5 | import { NextResponse } from "next/server";
|
5 |
| - |
| 6 | +import setExpireTime from "utils/setExpireTime"; |
6 | 7 | export const config = {
|
7 | 8 | matcher: ["/studies/:path*", "/participants/:path*"],
|
8 | 9 | };
|
9 | 10 |
|
10 |
| -const middleware = async (req: NextRequest) => { |
| 11 | +const middleware = async () => { |
11 | 12 | const cookieStore = cookies();
|
12 |
| - const accessToken = cookieStore.get("accessToken")?.value; |
| 13 | + const accessToken = cookieStore.get(cookieKey.accessToken)?.value; |
| 14 | + const middlewareExecuted = cookieStore.get( |
| 15 | + cookieKey["admin-middleware-executed"] |
| 16 | + )?.value; |
13 | 17 |
|
14 | 18 | if (!accessToken) {
|
15 |
| - return NextResponse.redirect(new URL("/not-found", req.url)); |
| 19 | + return NextResponse.redirect(new URL("/auth", clientUrl)); |
16 | 20 | }
|
17 | 21 |
|
18 |
| - const { studyRole, manageRole } = await dashboardApi.getDashboardInfo(); |
19 |
| - |
20 |
| - if (studyRole === "STUDENT" && manageRole === "NONE") { |
21 |
| - const url = |
22 |
| - process.env.NEXT_PUBLIC_VERCEL_ENV === "production" |
23 |
| - ? process.env.NEXT_PUBLIC_CLIENT_PROD_URL |
24 |
| - : process.env.NEXT_PUBLIC_CLIENT_DEV_URL; |
25 |
| - |
26 |
| - return NextResponse.redirect(new URL("/auth", url)); |
| 22 | + if (!middlewareExecuted) { |
| 23 | + try { |
| 24 | + const { manageRole, studyRole } = await dashboardApi.getDashboardInfo(); |
| 25 | + if (studyRole === "STUDENT" && manageRole === "NONE") { |
| 26 | + return NextResponse.redirect(new URL("/auth", clientUrl)); |
| 27 | + } |
| 28 | + const response = NextResponse.next(); |
| 29 | + response.cookies.set(cookieKey["admin-middleware-executed"], "true", { |
| 30 | + httpOnly: true, |
| 31 | + secure: true, |
| 32 | + sameSite: "lax", |
| 33 | + }); |
| 34 | + return response; |
| 35 | + } catch (error) { |
| 36 | + return NextResponse.next(); |
| 37 | + } |
27 | 38 | }
|
28 | 39 |
|
29 | 40 | return NextResponse.next();
|
|
0 commit comments