-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
212 lines (175 loc) · 8.5 KB
/
Copy pathproxy.ts
File metadata and controls
212 lines (175 loc) · 8.5 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
const ADMIN_EMAIL = process.env.ADMIN_EMAIL
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
// ── Root redirect ─────────────────────────────────────────────────────────
if (pathname === '/') {
return NextResponse.redirect(new URL('/splash', request.url))
}
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-pathname', pathname)
// Create Supabase response with cookie handling
const supabaseResponse = NextResponse.next({
request: {
headers: requestHeaders,
}
})
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, { ...options, path: '/' })
)
},
},
}
)
// Use getSession() to read the JWT from the cookie — no network call, no false logouts.
// getUser() (network-validated) is reserved for API route handlers where security is critical.
const { data: { session } } = await supabase.auth.getSession()
const user = session?.user ?? null
// Add security headers
supabaseResponse.headers.set('X-Frame-Options', 'DENY')
supabaseResponse.headers.set('X-Content-Type-Options', 'nosniff')
supabaseResponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin')
supabaseResponse.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=(self)')
supabaseResponse.headers.set(
'Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://checkout.razorpay.com https://cdn.razorpay.com; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:; " +
"connect-src 'self' https://api.razorpay.com https://garxraczisrnmvvnotyu.supabase.co wss://garxraczisrnmvvnotyu.supabase.co; " +
"frame-src https://checkout.razorpay.com https://api.razorpay.com https://livebutton.razorpay.com;"
)
// ── API route protection ─────────────────────────────────────────────────
if (pathname.startsWith('/api/')) {
// Allow public API routes without auth
const publicApiRoutes = [
'/api/auth',
'/api/webhooks',
'/api/customer/products',
'/api/product-ratings',
'/api/reviews',
'/api/cron',
'/api/notifications/order-placed',
]
const isPublicApi = publicApiRoutes.some(route =>
pathname === route || pathname.startsWith(route + '/')
)
if (!isPublicApi && !user) {
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
}
// Role-based API protection
if (user) {
const userRole = user.user_metadata?.role || user.app_metadata?.role
if (pathname.startsWith('/api/admin') && userRole !== 'admin') {
return NextResponse.json({ error: 'Admin access required' }, { status: 403 })
}
if (pathname.startsWith('/api/shopkeeper') && userRole !== 'shopkeeper') {
return NextResponse.json({ error: 'Shopkeeper access required' }, { status: 403 })
}
if (pathname.startsWith('/api/delivery') && userRole !== 'delivery_agent') {
return NextResponse.json({ error: 'Delivery agent access required' }, { status: 403 })
}
}
return supabaseResponse
}
// ── Protect /admin routes ──────────────────────────────────────────────────
if (pathname.startsWith('/admin')) {
if (pathname === '/admin/login') return supabaseResponse
if (!user) {
return NextResponse.redirect(new URL('/admin/login', request.url))
}
const isAdminEmail = user.email === ADMIN_EMAIL
const metaRole = user.user_metadata?.role || user.app_metadata?.role
// Fast path — trust email or metadata role without a DB call
if (isAdminEmail || metaRole === 'admin') return supabaseResponse
// Slow path — check profiles table
try {
const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).maybeSingle()
if (profile?.role === 'admin') return supabaseResponse
// Profile exists but not admin — block
if (profile) return NextResponse.redirect(new URL('/admin/login', request.url))
// Profile missing — fail open (layout will re-verify)
return supabaseResponse
} catch {
// DB error — fail open, layout will handle it
return supabaseResponse
}
}
// ── Protect /shopkeeper routes ──────────────────────────────────────────────
if (pathname.startsWith('/shopkeeper')) {
if (!user) {
return NextResponse.redirect(new URL('/login/shopkeeper', request.url))
}
const metaRole = user.user_metadata?.role || user.app_metadata?.role
if (metaRole === 'shopkeeper') return supabaseResponse
try {
const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).maybeSingle()
if (profile?.role === 'shopkeeper') return supabaseResponse
} catch (profileError) {
console.error('Profile check error in shopkeeper middleware:', profileError)
}
return NextResponse.redirect(new URL('/login/shopkeeper', request.url))
}
// ── Protect /delivery routes ────────────────────────────────────────────────
if (pathname.startsWith('/delivery') && !pathname.startsWith('/login/delivery')) {
if (!user) {
return NextResponse.redirect(new URL('/login/delivery', request.url))
}
const metaRole = user.user_metadata?.role || user.app_metadata?.role
if (metaRole === 'delivery_agent') return supabaseResponse
try {
const { data: profile, error: profileError } = await supabase.from('profiles').select('role').eq('id', user.id).maybeSingle()
if (profileError) {
return NextResponse.redirect(new URL('/login/delivery', request.url))
}
if (profile?.role === 'delivery_agent') return supabaseResponse
} catch {
return NextResponse.redirect(new URL('/login/delivery', request.url))
}
return NextResponse.redirect(new URL('/login/delivery', request.url))
}
// ── Allow login/splash pages for everyone ────────────────────────────────
if (pathname.startsWith('/login') || pathname === '/splash') {
// Redirect logged-in users to their dashboard
if (user) {
const userRole = user.user_metadata?.role || user.app_metadata?.role
if (userRole === 'admin') return NextResponse.redirect(new URL('/admin', request.url))
if (userRole === 'shopkeeper') return NextResponse.redirect(new URL('/shopkeeper', request.url))
if (userRole === 'delivery_agent') return NextResponse.redirect(new URL('/delivery', request.url))
return NextResponse.redirect(new URL('/customer', request.url))
}
// Allow unauthenticated users to access login/splash
return supabaseResponse
}
// ── Protect /customer routes ────────────────────────────────────────────────
if (pathname.startsWith('/customer') && !pathname.startsWith('/login/customer')) {
if (!user) {
return NextResponse.redirect(new URL('/login', request.url))
}
const metaRole = user.user_metadata?.role || user.app_metadata?.role
if (metaRole === 'customer') return supabaseResponse
try {
const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).maybeSingle()
if (profile?.role === 'customer') return supabaseResponse
} catch {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.redirect(new URL('/login', request.url))
}
return supabaseResponse
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}