gpt-engineer-app[bot] nextgenframes commited on
Commit
a96a0f9
·
1 Parent(s): 33bdc06

Co-authored-by: nextgenframes <281320089+nextgenframes@users.noreply.github.com>

src/integrations/supabase/auth-middleware.ts ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is automatically generated. Do not edit it directly.
2
+ import { createMiddleware } from '@tanstack/react-start'
3
+ import { getRequest } from '@tanstack/react-start/server'
4
+ import { createClient } from '@supabase/supabase-js'
5
+ import type { Database } from './types'
6
+
7
+
8
+
9
+ export const requireSupabaseAuth = createMiddleware({ type: 'function' }).server(
10
+ async ({ next }) => {
11
+
12
+ const SUPABASE_URL = process.env.SUPABASE_URL;
13
+ const SUPABASE_PUBLISHABLE_KEY = process.env.SUPABASE_PUBLISHABLE_KEY;
14
+
15
+ if (!SUPABASE_URL || !SUPABASE_PUBLISHABLE_KEY) {
16
+ const missing = [
17
+ ...(!SUPABASE_URL ? ['SUPABASE_URL'] : []),
18
+ ...(!SUPABASE_PUBLISHABLE_KEY ? ['SUPABASE_PUBLISHABLE_KEY'] : []),
19
+ ];
20
+ const message = `Missing Supabase environment variable(s): ${missing.join(', ')}. Connect Supabase in Lovable Cloud.`;
21
+ console.error(`[Supabase] ${message}`);
22
+ throw new Response(message, { status: 500 });
23
+ }
24
+
25
+ const request = getRequest();
26
+
27
+ if (!request?.headers) {
28
+ throw new Response('Unauthorized: No request headers available', { status: 401 });
29
+ }
30
+
31
+ const authHeader = request.headers.get('authorization');
32
+
33
+ if (!authHeader) {
34
+ throw new Response('Unauthorized: No authorization header provided', { status: 401 });
35
+ }
36
+
37
+ if (!authHeader.startsWith('Bearer ')) {
38
+ throw new Response('Unauthorized: Only Bearer tokens are supported', { status: 401 });
39
+ }
40
+
41
+ const token = authHeader.replace('Bearer ', '');
42
+ if (!token) {
43
+ throw new Response('Unauthorized: No token provided', { status: 401 });
44
+ }
45
+
46
+ const supabase = createClient<Database>(
47
+ SUPABASE_URL!,
48
+ SUPABASE_PUBLISHABLE_KEY!,
49
+ {
50
+ global: {
51
+ headers: {
52
+ Authorization: `Bearer ${token}`,
53
+ },
54
+ },
55
+ auth: {
56
+ storage: undefined,
57
+ persistSession: false,
58
+ autoRefreshToken: false,
59
+ },
60
+ }
61
+ );
62
+
63
+ const { data, error } = await supabase.auth.getClaims(token);
64
+ if (error || !data?.claims) {
65
+ throw new Response('Unauthorized: Invalid token', { status: 401 });
66
+ }
67
+
68
+ if (!data.claims.sub) {
69
+ throw new Response('Unauthorized: No user ID found in token', { status: 401 });
70
+ }
71
+
72
+ return next({
73
+ context: {
74
+ supabase,
75
+ userId: data.claims.sub,
76
+ claims: data.claims,
77
+ },
78
+ })
79
+ }
80
+ )