Files
thrilltrack-explorer/supabase/functions/process-expired-bans/index.ts
gpt-engineer-app[bot] 16a1fa756d Continue Phase 2 Batch 2 and Batch 3
Migrate 6 background jobs to use wrapEdgeFunction: cleanup-old-versions, process-scheduled-deletions, data-retention-cleanup, run-cleanup-jobs, scheduled-maintenance, process-expired-bans. Replace old server routines with edgeFunction wrapper, add centralized logging, tracing, and standardized error handling, and adjust for batch-wise deployment.
2025-11-11 03:36:40 +00:00

105 lines
2.9 KiB
TypeScript

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
export default createEdgeFunction(
{
name: 'process-expired-bans',
requireAuth: false,
},
async (req, context, supabase) => {
edgeLogger.info('Processing expired bans', {
requestId: context.requestId
});
const now = new Date().toISOString();
// Find expired bans
const { data: expiredBans, error: fetchError } = await supabase
.from('profiles')
.select('user_id, username, ban_reason, ban_expires_at')
.eq('banned', true)
.not('ban_expires_at', 'is', null)
.lte('ban_expires_at', now);
if (fetchError) {
edgeLogger.error('Error fetching expired bans', {
error: fetchError,
requestId: context.requestId
});
throw fetchError;
}
edgeLogger.info('Found expired bans to process', {
count: expiredBans?.length || 0,
requestId: context.requestId
});
// Unban users with expired bans
const unbannedUsers: string[] = [];
for (const profile of expiredBans || []) {
edgeLogger.info('Unbanning user', {
username: profile.username,
userId: profile.user_id,
requestId: context.requestId
});
const { error: unbanError } = await supabase
.from('profiles')
.update({
banned: false,
ban_reason: null,
ban_expires_at: null
})
.eq('user_id', profile.user_id);
if (unbanError) {
edgeLogger.error('Failed to unban user', {
username: profile.username,
error: unbanError,
requestId: context.requestId
});
continue;
}
// Log the automatic unban
const { error: logError } = await supabase
.rpc('log_admin_action', {
_admin_user_id: '00000000-0000-0000-0000-000000000000',
_target_user_id: profile.user_id,
_action: 'auto_unban',
_details: {
reason: 'Ban expired',
original_ban_reason: profile.ban_reason,
expired_at: profile.ban_expires_at
}
});
if (logError) {
edgeLogger.error('Failed to log auto-unban', {
username: profile.username,
error: logError,
requestId: context.requestId
});
}
unbannedUsers.push(profile.username);
}
edgeLogger.info('Successfully unbanned users', {
count: unbannedUsers.length,
requestId: context.requestId
});
return new Response(
JSON.stringify({
success: true,
unbanned_count: unbannedUsers.length,
unbanned_users: unbannedUsers,
processed_at: now
}),
{ headers: { 'Content-Type': 'application/json' } }
);
}
);