forked from lobehub/lobe-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
69 lines (58 loc) · 1.79 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
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
import { authEnv } from '@/config/auth';
import NextAuthEdge from '@/libs/next-auth/edge';
import { OAUTH_AUTHORIZED } from './const/auth';
export const config = {
matcher: [
// include any files in the api or trpc folders that might have an extension
'/(api|trpc|webapi)(.*)',
// include the /
'/',
'/chat(.*)',
'/settings(.*)',
'/files(.*)',
'/repos(.*)',
// ↓ cloud ↓
],
};
const defaultMiddleware = () => NextResponse.next();
// Initialize an Edge compatible NextAuth middleware
const nextAuthMiddleware = NextAuthEdge.auth((req) => {
// skip the '/' route
if (req.nextUrl.pathname === '/') return NextResponse.next();
// Just check if session exists
const session = req.auth;
// Check if next-auth throws errors
// refs: https://github.com/lobehub/lobe-chat/pull/1323
const isLoggedIn = !!session?.expires;
// Remove & amend OAuth authorized header
const requestHeaders = new Headers(req.headers);
requestHeaders.delete(OAUTH_AUTHORIZED);
if (isLoggedIn) requestHeaders.set(OAUTH_AUTHORIZED, 'true');
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
});
const isProtectedRoute = createRouteMatcher([
'/settings(.*)',
'/files(.*)',
// ↓ cloud ↓
]);
export default authEnv.NEXT_PUBLIC_ENABLE_CLERK_AUTH
? clerkMiddleware(
(auth, req) => {
if (isProtectedRoute(req)) auth().protect();
},
{
// https://github.com/lobehub/lobe-chat/pull/3084
clockSkewInMs: 60 * 60 * 1000,
signInUrl: '/login',
signUpUrl: '/signup',
},
)
: authEnv.NEXT_PUBLIC_ENABLE_NEXT_AUTH
? nextAuthMiddleware
: defaultMiddleware;