-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
111 lines (94 loc) · 3.82 KB
/
Copy pathproxy.ts
File metadata and controls
111 lines (94 loc) · 3.82 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
101
102
103
104
105
106
107
108
109
110
111
import { createServerClient } from '@supabase/ssr';
import { navigationRoutes } from '@/app/utils/navigation';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY;
// This function can be marked `async` if using `await` inside
export async function proxy(request: NextRequest) {
// Create supabaseResponse that we'll modify with refreshed cookies
let supabaseResponse = NextResponse.next({
request: {
headers: request.headers,
},
});
// Refresh Supabase auth session if needed - required for Server Components
if (supabaseUrl && supabaseKey) {
const supabase = createServerClient(supabaseUrl, supabaseKey, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
supabaseResponse = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) => supabaseResponse.cookies.set(name, value, options));
},
},
});
// This refreshes the session if it exists and is expired
await supabase.auth.getUser();
}
// Get the pathname of the request
const path = request.nextUrl.pathname;
// Skip proxy for API routes, static files, server actions, and direct user ID access
if (
path.startsWith('/_next') ||
path.startsWith('/api') ||
path.includes('.') ||
path === '/favicon.ico' ||
request.headers.get('Next-Action')
)
return NextResponse.next();
// Get the user ID and user type from cookies
const userId = request.cookies.get('user_id')?.value;
const userType = request.cookies.get('user_type')?.value;
// If no user ID or user type, redirect to home page
if (!userId || !userType) {
if (path !== '/') return NextResponse.redirect(new URL('/', request.url));
return supabaseResponse;
}
try {
// Make a fetch request to our own API to check user status
const response = await fetch(new URL('/api/auth/', request.url), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId }),
});
if (!response?.ok || response?.status !== 200) throw new Error('Failed to check user status');
const { userType: foundUserType } = await response.json();
// Handle redirects based on user type and status
if (userType === foundUserType) {
// If we're on an invalid path, redirect to missions
if (!navigationRoutes.includes(path)) return NextResponse.redirect(new URL('/missions', request.url));
return supabaseResponse;
} else {
// Not authenticated, redirect to error or waiting page
if (navigationRoutes.includes(path)) return NextResponse.redirect(new URL('/error', request.url));
// Skip if path matches a user ID pattern (20-22 characters alphanumeric string)
else if ((path === '/' || path === '/error' || !/^\/?[0-9a-z]{2,26}$/.test(path)) && path !== '/waiting')
return NextResponse.redirect(new URL('/waiting', request.url));
return supabaseResponse;
}
} catch (error) {
console.error('Middleware error:', error);
// Redirect to error page for database connection issues
if (path !== '/error') return NextResponse.redirect(new URL('/error', request.url));
return supabaseResponse;
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};