Files
thrilltrack-explorer/supabase/functions/auth0-sync-user/index.ts
gpt-engineer-app[bot] b2bf9a6e20 Implement Auth0 migration
2025-11-01 01:08:11 +00:00

159 lines
4.4 KiB
TypeScript

/**
* Auth0 User Sync Edge Function
*
* Syncs Auth0 user data to Supabase profiles table after authentication
*/
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { verifyAuth0Token, getUserId } from '../_shared/auth0Jwt.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
// Handle CORS preflight
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
// Get Auth0 token from Authorization header
const authHeader = req.headers.get('authorization');
if (!authHeader) {
throw new Error('Missing authorization header');
}
const token = authHeader.replace('Bearer ', '');
const payload = await verifyAuth0Token(token);
const auth0Sub = getUserId(payload);
// Parse request body
const { email, name, picture, email_verified } = await req.json();
// Create Supabase admin client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Check if profile exists by auth0_sub
const { data: existingProfile } = await supabase
.from('profiles')
.select('id, username, email, auth0_sub')
.eq('auth0_sub', auth0Sub)
.single();
let profile;
if (existingProfile) {
// Update existing profile
const { data, error } = await supabase
.from('profiles')
.update({
email: email || existingProfile.email,
avatar_url: picture || existingProfile.avatar_url,
updated_at: new Date().toISOString(),
})
.eq('auth0_sub', auth0Sub)
.select()
.single();
if (error) throw error;
profile = data;
} else {
// Check if profile exists by email (migration case)
const { data: emailProfile } = await supabase
.from('profiles')
.select('id, username, email')
.eq('email', email)
.is('auth0_sub', null)
.single();
if (emailProfile) {
// Link existing Supabase account to Auth0
const { data, error } = await supabase
.from('profiles')
.update({
auth0_sub: auth0Sub,
avatar_url: picture || emailProfile.avatar_url,
updated_at: new Date().toISOString(),
})
.eq('id', emailProfile.id)
.select()
.single();
if (error) throw error;
profile = data;
} else {
// Create new profile
const username = email.split('@')[0] + '_' + Math.random().toString(36).substring(7);
const { data, error } = await supabase
.from('profiles')
.insert({
auth0_sub: auth0Sub,
email: email,
username: username,
display_name: name || username,
avatar_url: picture,
email_verified: email_verified || false,
})
.select()
.single();
if (error) throw error;
profile = data;
}
}
// Log sync to auth0_sync_log
await supabase
.from('auth0_sync_log')
.insert({
auth0_sub: auth0Sub,
user_id: profile.id,
sync_status: 'success',
user_data: { email, name, picture },
});
// Fetch user roles
const { data: roles } = await supabase
.from('user_roles')
.select('role')
.eq('user_id', profile.id);
return new Response(
JSON.stringify({
success: true,
profile: {
id: profile.id,
auth0_sub: profile.auth0_sub,
username: profile.username,
email: profile.email,
avatar_url: profile.avatar_url,
roles: roles?.map(r => r.role) || [],
},
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('[Auth0Sync] Error:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
});