mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-27 06:06:58 -05:00
Reverted to commit 0091584677
This commit is contained in:
@@ -1,14 +1,5 @@
|
||||
project_id = "ydvtmnrszybqnbcqbdcy"
|
||||
|
||||
[functions.auth-with-mfa-check]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.verify-mfa-and-login]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.check-mfa-enrollment]
|
||||
verify_jwt = true
|
||||
|
||||
[functions.send-password-added-email]
|
||||
verify_jwt = true
|
||||
|
||||
@@ -73,16 +64,4 @@ verify_jwt = true
|
||||
verify_jwt = false
|
||||
|
||||
[functions.process-expired-bans]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.auth0-sync-user]
|
||||
verify_jwt = true
|
||||
|
||||
[functions.auth0-get-roles]
|
||||
verify_jwt = true
|
||||
|
||||
[functions.auth0-webhook]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.auth0-get-management-token]
|
||||
verify_jwt = true
|
||||
verify_jwt = false
|
||||
@@ -1,71 +0,0 @@
|
||||
/**
|
||||
* Auth0 JWT Verification Utility
|
||||
*
|
||||
* Provides JWT verification using Auth0 JWKS
|
||||
*/
|
||||
|
||||
import { jwtVerify, createRemoteJWKSet, type JWTPayload } from 'https://esm.sh/jose@5.2.0';
|
||||
|
||||
const AUTH0_DOMAIN = Deno.env.get('AUTH0_DOMAIN') || '';
|
||||
const AUTH0_CLIENT_ID = Deno.env.get('AUTH0_CLIENT_ID') || '';
|
||||
|
||||
/**
|
||||
* Extended JWT payload with Auth0-specific claims
|
||||
*/
|
||||
export interface Auth0JWTPayload extends JWTPayload {
|
||||
sub: string;
|
||||
email?: string;
|
||||
email_verified?: boolean;
|
||||
name?: string;
|
||||
picture?: string;
|
||||
'https://thrillwiki.com/roles'?: string[];
|
||||
amr?: string[]; // Authentication Methods Reference (includes 'mfa' if MFA verified)
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify Auth0 JWT token using JWKS
|
||||
*/
|
||||
export async function verifyAuth0Token(token: string): Promise<Auth0JWTPayload> {
|
||||
try {
|
||||
if (!AUTH0_DOMAIN || !AUTH0_CLIENT_ID) {
|
||||
throw new Error('Auth0 configuration missing');
|
||||
}
|
||||
|
||||
// Create JWKS fetcher
|
||||
const JWKS = createRemoteJWKSet(
|
||||
new URL(`https://${AUTH0_DOMAIN}/.well-known/jwks.json`)
|
||||
);
|
||||
|
||||
// Verify token
|
||||
const { payload } = await jwtVerify(token, JWKS, {
|
||||
issuer: `https://${AUTH0_DOMAIN}/`,
|
||||
audience: AUTH0_CLIENT_ID,
|
||||
});
|
||||
|
||||
return payload as Auth0JWTPayload;
|
||||
} catch (error) {
|
||||
console.error('[Auth0JWT] Verification failed:', error);
|
||||
throw new Error('Invalid Auth0 token');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract roles from Auth0 JWT payload
|
||||
*/
|
||||
export function extractRoles(payload: Auth0JWTPayload): string[] {
|
||||
return payload['https://thrillwiki.com/roles'] || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has verified MFA
|
||||
*/
|
||||
export function hasMFA(payload: Auth0JWTPayload): boolean {
|
||||
return payload.amr?.includes('mfa') || false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract user ID (sub) from payload
|
||||
*/
|
||||
export function getUserId(payload: Auth0JWTPayload): string {
|
||||
return payload.sub;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
@@ -1,128 +0,0 @@
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const { email, password } = await req.json();
|
||||
|
||||
if (!email || !password) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Email and password are required' }),
|
||||
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Create admin client
|
||||
const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey, {
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
},
|
||||
});
|
||||
|
||||
// Verify credentials using signInWithPassword (doesn't create session with admin client)
|
||||
const { data: authData, error: authError } = await supabaseAdmin.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (authError || !authData.user) {
|
||||
console.error('Auth error:', authError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: authError?.message || 'Invalid credentials' }),
|
||||
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
const userId = authData.user.id;
|
||||
|
||||
// Check if user is banned
|
||||
const { data: profile, error: profileError } = await supabaseAdmin
|
||||
.from('profiles')
|
||||
.select('banned, ban_reason')
|
||||
.eq('user_id', userId)
|
||||
.single();
|
||||
|
||||
if (profileError) {
|
||||
console.error('Profile check error:', profileError);
|
||||
}
|
||||
|
||||
if (profile?.banned) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: 'Account suspended',
|
||||
banned: true,
|
||||
banReason: profile.ban_reason
|
||||
}),
|
||||
{ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Check for MFA enrollment
|
||||
const { data: factors, error: factorsError } = await supabaseAdmin.auth.admin.mfa.listFactors({
|
||||
userId,
|
||||
});
|
||||
|
||||
if (factorsError) {
|
||||
console.error('MFA factors check error:', factorsError);
|
||||
// Continue - assume no MFA if check fails
|
||||
}
|
||||
|
||||
const verifiedFactors = factors?.totp?.filter((f) => f.status === 'verified') || [];
|
||||
|
||||
if (verifiedFactors.length > 0) {
|
||||
// User has MFA - create a challenge but don't create session
|
||||
const factorId = verifiedFactors[0].id;
|
||||
|
||||
// Create MFA challenge
|
||||
const { data: challengeData, error: challengeError } = await supabaseAdmin.auth.mfa.challenge({
|
||||
factorId,
|
||||
});
|
||||
|
||||
if (challengeError) {
|
||||
console.error('Challenge creation error:', challengeError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Failed to create MFA challenge' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
mfaRequired: true,
|
||||
factorId,
|
||||
challengeId: challengeData.id,
|
||||
userId, // Needed for verification step
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// No MFA required - return session
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
mfaRequired: false,
|
||||
session: authData.session,
|
||||
user: authData.user,
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Unexpected error:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Internal server error' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,114 +0,0 @@
|
||||
/**
|
||||
* Auth0 Get Management Token Edge Function
|
||||
*
|
||||
* Obtains Auth0 Management API access tokens for admin operations
|
||||
*/
|
||||
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||
import { verifyAuth0Token, extractRoles } from '../_shared/auth0Jwt.ts';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
// In-memory cache for management token
|
||||
let cachedToken: string | null = null;
|
||||
let tokenExpiry: number = 0;
|
||||
|
||||
serve(async (req) => {
|
||||
// Handle CORS preflight
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
// Verify user is authenticated
|
||||
const authHeader = req.headers.get('authorization');
|
||||
if (!authHeader) {
|
||||
throw new Error('Missing authorization header');
|
||||
}
|
||||
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const payload = await verifyAuth0Token(token);
|
||||
|
||||
// Check if user has admin/moderator role
|
||||
const roles = extractRoles(payload);
|
||||
const isAuthorized = roles.some(role =>
|
||||
['admin', 'moderator', 'superuser'].includes(role)
|
||||
);
|
||||
|
||||
if (!isAuthorized) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Unauthorized - admin role required' }),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 403,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Check if cached token is still valid (5 min buffer)
|
||||
const now = Date.now() / 1000;
|
||||
if (cachedToken && tokenExpiry > now + 300) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
access_token: cachedToken,
|
||||
token_type: 'Bearer',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Get new management token
|
||||
const AUTH0_DOMAIN = Deno.env.get('AUTH0_DOMAIN')!;
|
||||
const M2M_CLIENT_ID = Deno.env.get('AUTH0_M2M_CLIENT_ID')!;
|
||||
const M2M_CLIENT_SECRET = Deno.env.get('AUTH0_M2M_CLIENT_SECRET')!;
|
||||
|
||||
const response = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
client_id: M2M_CLIENT_ID,
|
||||
client_secret: M2M_CLIENT_SECRET,
|
||||
audience: `https://${AUTH0_DOMAIN}/api/v2/`,
|
||||
grant_type: 'client_credentials',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to get management token');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Cache the token
|
||||
cachedToken = data.access_token;
|
||||
tokenExpiry = now + data.expires_in;
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
access_token: data.access_token,
|
||||
token_type: data.token_type,
|
||||
expires_in: data.expires_in,
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('[Auth0ManagementToken] Error:', error);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,105 +0,0 @@
|
||||
/**
|
||||
* 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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,158 +0,0 @@
|
||||
/**
|
||||
* 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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,154 +0,0 @@
|
||||
/**
|
||||
* Auth0 Webhook Edge Function
|
||||
*
|
||||
* Handles Auth0 webhook events for real-time sync
|
||||
*/
|
||||
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||
import { createHmac } from 'https://deno.land/std@0.168.0/node/crypto.ts';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-auth0-signature',
|
||||
};
|
||||
|
||||
/**
|
||||
* Verify Auth0 webhook signature
|
||||
*/
|
||||
function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
|
||||
const hmac = createHmac('sha256', secret);
|
||||
hmac.update(payload);
|
||||
const expectedSignature = hmac.digest('hex');
|
||||
return signature === expectedSignature;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
// Handle CORS preflight
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
// Get webhook secret
|
||||
const WEBHOOK_SECRET = Deno.env.get('AUTH0_WEBHOOK_SECRET');
|
||||
if (!WEBHOOK_SECRET) {
|
||||
throw new Error('Webhook secret not configured');
|
||||
}
|
||||
|
||||
// Verify signature
|
||||
const signature = req.headers.get('x-auth0-signature');
|
||||
const body = await req.text();
|
||||
|
||||
if (signature && !verifyWebhookSignature(body, signature, WEBHOOK_SECRET)) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Invalid signature' }),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 401,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const event = JSON.parse(body);
|
||||
const { type, data } = event;
|
||||
|
||||
// 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);
|
||||
|
||||
// Handle different event types
|
||||
switch (type) {
|
||||
case 'post-login': {
|
||||
// Update last login timestamp
|
||||
const auth0Sub = data.user?.user_id;
|
||||
if (auth0Sub) {
|
||||
await supabase
|
||||
.from('profiles')
|
||||
.update({ updated_at: new Date().toISOString() })
|
||||
.eq('auth0_sub', auth0Sub);
|
||||
|
||||
// Log to audit log
|
||||
await supabase.rpc('log_admin_action', {
|
||||
p_user_id: null,
|
||||
p_action: 'auth0_login',
|
||||
p_details: { auth0_sub: auth0Sub, event_type: 'post-login' },
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'post-change-password': {
|
||||
// Log password change
|
||||
const auth0Sub = data.user?.user_id;
|
||||
if (auth0Sub) {
|
||||
await supabase.rpc('log_admin_action', {
|
||||
p_user_id: null,
|
||||
p_action: 'password_changed',
|
||||
p_details: { auth0_sub: auth0Sub, event_type: 'post-change-password' },
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'post-user-registration': {
|
||||
// Create initial profile if doesn't exist
|
||||
const auth0Sub = data.user?.user_id;
|
||||
const email = data.user?.email;
|
||||
|
||||
if (auth0Sub && email) {
|
||||
const { data: existing } = await supabase
|
||||
.from('profiles')
|
||||
.select('id')
|
||||
.eq('auth0_sub', auth0Sub)
|
||||
.single();
|
||||
|
||||
if (!existing) {
|
||||
const username = email.split('@')[0] + '_' + Math.random().toString(36).substring(7);
|
||||
|
||||
await supabase
|
||||
.from('profiles')
|
||||
.insert({
|
||||
auth0_sub: auth0Sub,
|
||||
email: email,
|
||||
username: username,
|
||||
display_name: data.user?.name || username,
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
console.log('[Auth0Webhook] Unhandled event type:', type);
|
||||
}
|
||||
|
||||
// Log webhook event
|
||||
await supabase
|
||||
.from('auth0_sync_log')
|
||||
.insert({
|
||||
auth0_sub: data.user?.user_id || 'unknown',
|
||||
sync_status: 'success',
|
||||
user_data: { event_type: type, data },
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true }),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('[Auth0Webhook] Error:', error);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,84 +0,0 @@
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const authHeader = req.headers.get('Authorization');
|
||||
if (!authHeader) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Missing authorization header' }),
|
||||
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Create client with user's token to verify session
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
|
||||
global: {
|
||||
headers: { Authorization: authHeader },
|
||||
},
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
},
|
||||
});
|
||||
|
||||
const { data: { user }, error: userError } = await supabase.auth.getUser();
|
||||
|
||||
if (userError || !user) {
|
||||
console.error('User verification error:', userError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Unauthorized' }),
|
||||
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Create admin client to check MFA factors
|
||||
const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey, {
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
},
|
||||
});
|
||||
|
||||
const { data: factors, error: factorsError } = await supabaseAdmin.auth.admin.mfa.listFactors({
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
if (factorsError) {
|
||||
console.error('MFA factors check error:', factorsError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Failed to check MFA enrollment' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
const verifiedFactors = factors?.totp?.filter((f) => f.status === 'verified') || [];
|
||||
const hasEnrolled = verifiedFactors.length > 0;
|
||||
const factorId = verifiedFactors.length > 0 ? verifiedFactors[0].id : undefined;
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
hasEnrolled,
|
||||
factorId,
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Unexpected error:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Internal server error' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const { challengeId, factorId, code, userId } = await req.json();
|
||||
|
||||
if (!challengeId || !factorId || !code || !userId) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Missing required fields' }),
|
||||
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Create admin client
|
||||
const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey, {
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
},
|
||||
});
|
||||
|
||||
// Verify TOTP code
|
||||
const { data: verifyData, error: verifyError } = await supabaseAdmin.auth.mfa.verify({
|
||||
factorId,
|
||||
challengeId,
|
||||
code,
|
||||
});
|
||||
|
||||
if (verifyError || !verifyData) {
|
||||
console.error('MFA verification error:', verifyError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: verifyError?.message || 'Invalid verification code' }),
|
||||
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Verification successful - create AAL2 session using admin API
|
||||
const { data: sessionData, error: sessionError } = await supabaseAdmin.auth.admin.createSession({
|
||||
userId,
|
||||
// This creates a session with AAL2
|
||||
});
|
||||
|
||||
if (sessionError || !sessionData) {
|
||||
console.error('Session creation error:', sessionError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Failed to create session' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Log successful MFA authentication
|
||||
try {
|
||||
await supabaseAdmin.rpc('log_admin_action', {
|
||||
_admin_user_id: userId,
|
||||
_target_user_id: userId,
|
||||
_action: 'mfa_login_success',
|
||||
_details: { timestamp: new Date().toISOString(), aal: 'aal2' },
|
||||
});
|
||||
} catch (logError) {
|
||||
console.error('Audit log error:', logError);
|
||||
// Don't fail the login if audit logging fails
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
session: sessionData.session,
|
||||
user: sessionData.user,
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Unexpected error:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Internal server error' }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
-- Create security definer function to block AAL1 sessions when MFA is enrolled
|
||||
CREATE OR REPLACE FUNCTION public.block_aal1_with_mfa()
|
||||
RETURNS boolean
|
||||
LANGUAGE sql
|
||||
STABLE
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
SELECT
|
||||
CASE
|
||||
-- If current session is AAL1
|
||||
WHEN (auth.jwt() ->> 'aal') = 'aal1' THEN
|
||||
-- Check if user has verified MFA factors
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM auth.mfa_factors
|
||||
WHERE user_id = auth.uid()
|
||||
AND status = 'verified'
|
||||
)
|
||||
-- If AAL2 or higher, allow
|
||||
ELSE true
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Apply to profiles table
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users" ON public.profiles
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
-- Apply to user_roles table
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_roles" ON public.user_roles
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
-- Apply to submission tables
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_park_sub" ON public.park_submissions
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_ride_sub" ON public.ride_submissions
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_company_sub" ON public.company_submissions
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_content_sub" ON public.content_submissions
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_photo_sub" ON public.photo_submissions
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
-- Apply to user content tables
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_reviews" ON public.reviews
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
CREATE POLICY "enforce_aal2_for_mfa_users_reports" ON public.reports
|
||||
FOR ALL
|
||||
USING (public.block_aal1_with_mfa());
|
||||
|
||||
-- Grant execute permission
|
||||
GRANT EXECUTE ON FUNCTION public.block_aal1_with_mfa() TO authenticated;
|
||||
@@ -1,154 +0,0 @@
|
||||
-- Phase 1: Auth0 Migration - Add auth0_sub column and update RLS policies
|
||||
-- This migration prepares the database to support Auth0 authentication alongside Supabase auth
|
||||
|
||||
-- Add auth0_sub column to profiles table
|
||||
ALTER TABLE public.profiles
|
||||
ADD COLUMN IF NOT EXISTS auth0_sub TEXT UNIQUE;
|
||||
|
||||
-- Create index for faster auth0_sub lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_profiles_auth0_sub ON public.profiles(auth0_sub);
|
||||
|
||||
-- Add comment explaining the column
|
||||
COMMENT ON COLUMN public.profiles.auth0_sub IS 'Auth0 user identifier (sub claim from JWT). Used for Auth0 authentication integration.';
|
||||
|
||||
-- Update RLS policies to support both Supabase and Auth0 authentication
|
||||
-- We'll keep existing policies and add Auth0 support
|
||||
|
||||
-- Create helper function to get current user ID (works with both Supabase and Auth0)
|
||||
CREATE OR REPLACE FUNCTION public.get_current_user_id()
|
||||
RETURNS uuid
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_user_id uuid;
|
||||
v_auth0_sub text;
|
||||
BEGIN
|
||||
-- Try Supabase auth first
|
||||
v_user_id := auth.uid();
|
||||
|
||||
IF v_user_id IS NOT NULL THEN
|
||||
RETURN v_user_id;
|
||||
END IF;
|
||||
|
||||
-- Try Auth0 sub from JWT
|
||||
v_auth0_sub := current_setting('request.jwt.claims', true)::json->>'sub';
|
||||
|
||||
IF v_auth0_sub IS NOT NULL THEN
|
||||
-- Look up user_id by auth0_sub
|
||||
SELECT user_id INTO v_user_id
|
||||
FROM public.profiles
|
||||
WHERE auth0_sub = v_auth0_sub;
|
||||
|
||||
RETURN v_user_id;
|
||||
END IF;
|
||||
|
||||
-- No authenticated user found
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Add audit log column for Auth0 events
|
||||
ALTER TABLE public.admin_audit_log
|
||||
ADD COLUMN IF NOT EXISTS auth0_event_type TEXT;
|
||||
|
||||
COMMENT ON COLUMN public.admin_audit_log.auth0_event_type IS 'Type of Auth0 event that triggered this audit log entry (e.g., mfa_enrollment, login, role_change)';
|
||||
|
||||
-- Create table for tracking Auth0 sync status
|
||||
CREATE TABLE IF NOT EXISTS public.auth0_sync_log (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
auth0_sub text NOT NULL,
|
||||
user_id uuid REFERENCES public.profiles(user_id),
|
||||
sync_type text NOT NULL, -- 'user_created', 'profile_updated', 'mfa_enrolled', etc.
|
||||
sync_status text NOT NULL DEFAULT 'pending', -- 'pending', 'completed', 'failed'
|
||||
error_message text,
|
||||
metadata jsonb DEFAULT '{}'::jsonb,
|
||||
created_at timestamp with time zone NOT NULL DEFAULT now(),
|
||||
completed_at timestamp with time zone
|
||||
);
|
||||
|
||||
-- Create index on auth0_sync_log
|
||||
CREATE INDEX IF NOT EXISTS idx_auth0_sync_log_auth0_sub ON public.auth0_sync_log(auth0_sub);
|
||||
CREATE INDEX IF NOT EXISTS idx_auth0_sync_log_user_id ON public.auth0_sync_log(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_auth0_sync_log_status ON public.auth0_sync_log(sync_status);
|
||||
|
||||
-- Enable RLS on auth0_sync_log
|
||||
ALTER TABLE public.auth0_sync_log ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- RLS policies for auth0_sync_log
|
||||
CREATE POLICY "Moderators can view all sync logs"
|
||||
ON public.auth0_sync_log
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
CREATE POLICY "System can insert sync logs"
|
||||
ON public.auth0_sync_log
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (true);
|
||||
|
||||
CREATE POLICY "Users can view their own sync logs"
|
||||
ON public.auth0_sync_log
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (user_id = auth.uid());
|
||||
|
||||
-- Create function to extract Auth0 sub from JWT
|
||||
CREATE OR REPLACE FUNCTION public.get_auth0_sub_from_jwt()
|
||||
RETURNS text
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
BEGIN
|
||||
RETURN current_setting('request.jwt.claims', true)::json->>'sub';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Create function to check if user is authenticated via Auth0
|
||||
CREATE OR REPLACE FUNCTION public.is_auth0_user()
|
||||
RETURNS boolean
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_iss text;
|
||||
BEGIN
|
||||
v_iss := current_setting('request.jwt.claims', true)::json->>'iss';
|
||||
-- Auth0 issuer format: https://<tenant>.auth0.com/ or https://<tenant>.<region>.auth0.com/
|
||||
RETURN v_iss LIKE '%auth0.com%';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
RETURN false;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Create function to check Auth0 MFA status from JWT claims
|
||||
CREATE OR REPLACE FUNCTION public.has_auth0_mfa()
|
||||
RETURNS boolean
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_amr jsonb;
|
||||
BEGIN
|
||||
-- Check if 'mfa' is in the amr (Authentication Methods Reference) array
|
||||
v_amr := current_setting('request.jwt.claims', true)::json->'amr';
|
||||
RETURN v_amr ? 'mfa';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
RETURN false;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.get_current_user_id IS 'Returns the current user ID, supporting both Supabase auth.uid() and Auth0 sub claim lookup';
|
||||
COMMENT ON FUNCTION public.get_auth0_sub_from_jwt IS 'Extracts the Auth0 sub claim from the JWT token';
|
||||
COMMENT ON FUNCTION public.is_auth0_user IS 'Checks if the current user is authenticated via Auth0';
|
||||
COMMENT ON FUNCTION public.has_auth0_mfa IS 'Checks if the current Auth0 user has completed MFA (checks amr claim for mfa)';
|
||||
Reference in New Issue
Block a user