feat: Update Discord username in edge function

This commit is contained in:
gpt-engineer-app[bot]
2025-10-12 00:51:45 +00:00
parent c129fb1a9e
commit c5ad432667

View File

@@ -43,6 +43,35 @@ interface DiscordUserMetadata {
iss?: string; iss?: string;
} }
async function ensureUniqueUsername(
supabase: any,
baseUsername: string,
userId: string,
maxAttempts: number = 10
): Promise<string> {
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) => { Deno.serve(async (req) => {
if (req.method === 'OPTIONS') { if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders }); return new Response(null, { headers: corsHeaders });
@@ -275,6 +304,13 @@ Deno.serve(async (req) => {
updateData.display_name = displayName; 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 // Only update if we have data to update
if (Object.keys(updateData).length > 0) { if (Object.keys(updateData).length > 0) {
const { error: updateError } = await supabase const { error: updateError } = await supabase