-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathproxy.ts
More file actions
100 lines (77 loc) · 2.77 KB
/
proxy.ts
File metadata and controls
100 lines (77 loc) · 2.77 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { NextRequest, NextResponse } from 'next/server';
import createIntlMiddleware from 'next-intl/middleware';
import { routing } from './i18n/routing';
import { AuthTokenPayload } from '@/lib/auth';
const AUTH_COOKIE_NAME = 'auth_session';
const AUTH_SECRET = process.env.AUTH_SECRET;
if (!AUTH_SECRET) {
throw new Error('AUTH_SECRET is not defined');
}
function decodeAuthToken(token: string): AuthTokenPayload | null {
const parts = token.split(".");
if (parts.length < 2) return null;
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(base64.length + (4 - (base64.length % 4)) % 4, "=");
try {
const json = atob(padded);
const payload = JSON.parse(json) as Partial<AuthTokenPayload>;
if (
typeof payload.userId !== "string" ||
(payload.role !== "user" && payload.role !== "admin") ||
typeof payload.email !== "string" ||
typeof payload.exp !== "number"
) {
return null;
}
return payload as AuthTokenPayload;
} catch {
return null;
}
}
function isAuthenticated(req: NextRequest): boolean {
const token = req.cookies.get(AUTH_COOKIE_NAME)?.value;
if (!token) return false;
const payload = decodeAuthToken(token);
if (!payload) return false;
const now = Math.floor(Date.now() / 1000);
return typeof payload.exp === 'number' && payload.exp > now;
}
const intlMiddleware = createIntlMiddleware(routing);
function authMiddleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const authenticated = isAuthenticated(req);
const pathnameWithoutLocale =
pathname.replace(/^\/(uk|en|pl)(?=\/|$)/, '') || '/';
if (pathnameWithoutLocale.startsWith('/dashboard')) {
if (!authenticated) {
const locale = pathname.split('/')[1] || 'en';
return NextResponse.redirect(new URL(`/${locale}/login`, req.url));
}
}
return null;
}
function getScopeFromPathname(pathname: string): 'shop' | 'site' {
const pathnameWithoutLocale =
pathname.replace(/^\/(uk|en|pl)(?=\/|$)/, '') || '/';
return pathnameWithoutLocale.startsWith('/shop') ? 'shop' : 'site';
}
export function proxy(req: NextRequest) {
if (req.nextUrl.pathname === '/') {
return NextResponse.redirect(new URL('/en', req.url));
}
const locale = req.nextUrl.pathname.split('/')[1] || 'en';
const authResponse = authMiddleware(req);
if (authResponse) return authResponse;
const intlResponse = intlMiddleware(req);
const scope = getScopeFromPathname(req.nextUrl.pathname);
intlResponse.headers.set('x-app-scope', scope);
intlResponse.headers.set('x-locale', locale);
intlResponse.cookies.set('NEXT_LOCALE', locale, {
path: '/',
sameSite: 'lax',
});
return intlResponse;
}
export const config = {
matcher: ['/', '/(uk|en|pl)/:path*', '/((?!api|_next|.*\\..*).*)'],
};