-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
40 lines (32 loc) · 1.29 KB
/
Copy pathproxy.ts
File metadata and controls
40 lines (32 loc) · 1.29 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
import { getToken } from 'next-auth/jwt';
import { NextRequest, NextResponse } from 'next/server';
export async function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
const token = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET as string,
salt: process.env.NEXTAUTH_SALT as string,
secureCookie: req.nextUrl.protocol === 'https:',
});
const isAuthRoute = pathname === '/signin';
const isProtectedRoute = pathname.startsWith('/history') || pathname.startsWith('/api/generate') || pathname.startsWith("/api/images") || pathname;
if (isAuthRoute) {
if (token) {
return NextResponse.redirect(new URL('/history', req.url));
}
return NextResponse.next();
}
if (isProtectedRoute) {
if (!token) {
const signinUrl = new URL('/signin', req.url);
signinUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(signinUrl);
}
const now = Date.now() / 1000;
if (token.exp && now > token.exp) {
return NextResponse.redirect(new URL('/signin', req.url));
}
}
return NextResponse.next();
}
export const config = { matcher: ['/history', '/api/generate', '/api/images', '/signin', "/"] };