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

106 lines
2.8 KiB
TypeScript

/**
* Auth0 Get Roles Edge Function
*
* Fetches user roles for authorization checks
*/
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, extractRoles } 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);
// Try to get roles from JWT first
const jwtRoles = extractRoles(payload);
// Create Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Get profile by auth0_sub
const { data: profile, error: profileError } = await supabase
.from('profiles')
.select('id')
.eq('auth0_sub', auth0Sub)
.single();
if (profileError || !profile) {
// Return JWT roles if profile not found
return new Response(
JSON.stringify({
success: true,
roles: jwtRoles,
source: 'jwt',
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
}
// Fetch roles from database
const { data: dbRoles, error: rolesError } = await supabase
.from('user_roles')
.select('role')
.eq('user_id', profile.id);
if (rolesError) {
throw rolesError;
}
const roles = dbRoles?.map(r => r.role) || [];
// Also fetch permissions
const { data: permissions } = await supabase
.rpc('get_user_management_permissions', { _user_id: profile.id });
return new Response(
JSON.stringify({
success: true,
roles,
permissions,
source: 'database',
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('[Auth0GetRoles] Error:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
});