mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 23:11:13 -05:00
Reverted to commit 0091584677
This commit is contained in:
@@ -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' } }
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user