From c5ad4326675b523221c24e96d93756e2264ac1f9 Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Sun, 12 Oct 2025 00:51:45 +0000 Subject: [PATCH] feat: Update Discord username in edge function --- .../functions/process-oauth-profile/index.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/supabase/functions/process-oauth-profile/index.ts b/supabase/functions/process-oauth-profile/index.ts index 9eae5aa1..7df01c01 100644 --- a/supabase/functions/process-oauth-profile/index.ts +++ b/supabase/functions/process-oauth-profile/index.ts @@ -43,6 +43,35 @@ interface DiscordUserMetadata { iss?: string; } +async function ensureUniqueUsername( + supabase: any, + baseUsername: string, + userId: string, + maxAttempts: number = 10 +): Promise { + let username = baseUsername.toLowerCase(); + let attempt = 0; + + while (attempt < maxAttempts) { + const { data: existing } = await supabase + .from('profiles') + .select('user_id') + .eq('username', username) + .neq('user_id', userId) + .maybeSingle(); + + if (!existing) { + return username; + } + + attempt++; + username = `${baseUsername.toLowerCase()}_${attempt}`; + } + + // Fallback to UUID-based username + return `user_${userId.substring(0, 8)}`; +} + Deno.serve(async (req) => { if (req.method === 'OPTIONS') { return new Response(null, { headers: corsHeaders }); @@ -275,6 +304,13 @@ Deno.serve(async (req) => { updateData.display_name = displayName; } + // Update username if it's currently a generic UUID-based username + if (usernameBase && profile?.username?.startsWith('user_')) { + const newUsername = await ensureUniqueUsername(supabase, usernameBase, user.id); + updateData.username = newUsername; + console.log('[OAuth Profile] Updating generic username from', profile.username, 'to', newUsername); + } + // Only update if we have data to update if (Object.keys(updateData).length > 0) { const { error: updateError } = await supabase