|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import { supabase } from '@/lib/supabase'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Example protected API route |
| 6 | + * GET /api/user/profile - Get current user profile |
| 7 | + */ |
| 8 | +export async function GET(request: NextRequest) { |
| 9 | + try { |
| 10 | + // Get the authorization header |
| 11 | + const token = request.headers.get('authorization')?.replace('Bearer ', ''); |
| 12 | + |
| 13 | + if (!token) { |
| 14 | + return NextResponse.json( |
| 15 | + { error: 'No authorization token provided' }, |
| 16 | + { status: 401 } |
| 17 | + ); |
| 18 | + } |
| 19 | + |
| 20 | + // Verify the user with Supabase |
| 21 | + const { data: { user }, error } = await supabase.auth.getUser(token); |
| 22 | + |
| 23 | + if (error || !user) { |
| 24 | + return NextResponse.json( |
| 25 | + { error: 'Invalid or expired token' }, |
| 26 | + { status: 401 } |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + // Return user data |
| 31 | + return NextResponse.json({ |
| 32 | + id: user.id, |
| 33 | + email: user.email, |
| 34 | + created_at: user.created_at, |
| 35 | + }); |
| 36 | + } catch (error) { |
| 37 | + console.error('Profile API error:', error); |
| 38 | + return NextResponse.json( |
| 39 | + { error: 'Internal server error' }, |
| 40 | + { status: 500 } |
| 41 | + ); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * PATCH /api/user/profile - Update user profile |
| 47 | + */ |
| 48 | +export async function PATCH(request: NextRequest) { |
| 49 | + try { |
| 50 | + const token = request.headers.get('authorization')?.replace('Bearer ', ''); |
| 51 | + |
| 52 | + if (!token) { |
| 53 | + return NextResponse.json( |
| 54 | + { error: 'No authorization token provided' }, |
| 55 | + { status: 401 } |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + const { data: { user }, error: authError } = await supabase.auth.getUser(token); |
| 60 | + |
| 61 | + if (authError || !user) { |
| 62 | + return NextResponse.json( |
| 63 | + { error: 'Invalid or expired token' }, |
| 64 | + { status: 401 } |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + // Get the update data from request body |
| 69 | + const updates = await request.json(); |
| 70 | + |
| 71 | + // Update user metadata (example) |
| 72 | + const { data, error } = await supabase.auth.updateUser({ |
| 73 | + data: updates, |
| 74 | + }); |
| 75 | + |
| 76 | + if (error) { |
| 77 | + return NextResponse.json( |
| 78 | + { error: error.message }, |
| 79 | + { status: 400 } |
| 80 | + ); |
| 81 | + } |
| 82 | + |
| 83 | + return NextResponse.json({ |
| 84 | + message: 'Profile updated successfully', |
| 85 | + user: data.user, |
| 86 | + }); |
| 87 | + } catch (error) { |
| 88 | + console.error('Profile update error:', error); |
| 89 | + return NextResponse.json( |
| 90 | + { error: 'Internal server error' }, |
| 91 | + { status: 500 } |
| 92 | + ); |
| 93 | + } |
| 94 | +} |
0 commit comments