mirror of
https://github.com/marcogll/AnchorOS.git
synced 2026-03-15 11:24:26 +00:00
🚀 FASE 4 COMPLETADO: Comentarios auditables + Calendario funcional + Gestión staff/recursos
✅ COMENTARIOS AUDITABLES IMPLEMENTADOS: - 80+ archivos con JSDoc completo para auditoría manual - APIs críticas con validaciones business/security/performance - Componentes con reglas de negocio documentadas - Funciones core con edge cases y validaciones ✅ CALENDARIO MULTI-COLUMNA FUNCIONAL (95%): - Drag & drop con reprogramación automática - Filtros por sucursal/staff, tiempo real - Indicadores de conflictos y disponibilidad - APIs completas con validaciones de colisión ✅ GESTIÓN OPERATIVA COMPLETA: - CRUD staff: APIs + componente con validaciones - CRUD recursos: APIs + componente con disponibilidad - Autenticación completa con middleware seguro - Auditoría completa en todas las operaciones ✅ DOCUMENTACIÓN ACTUALIZADA: - TASKS.md: FASE 4 95% completado - README.md: Estado actual y funcionalidades - API.md: 40+ endpoints documentados ✅ SEGURIDAD Y VALIDACIONES: - RLS policies documentadas en comentarios - Business rules validadas manualmente - Performance optimizations anotadas - Error handling completo Próximos: Nómina/POS/CRM avanzado (FASE 4 final)
This commit is contained in:
75
scripts/authguard-test-plan.js
Normal file
75
scripts/authguard-test-plan.js
Normal file
@@ -0,0 +1,75 @@
|
||||
console.log('========================================')
|
||||
console.log('🧪 AUTHGUARD - PLAN DE PRUEBA FINAL')
|
||||
console.log('========================================')
|
||||
console.log('')
|
||||
|
||||
console.log('📋 PROBLEMA SOLUCIONADO:')
|
||||
console.log(' ✅ Removido listener onAuthStateChange de AuthProvider')
|
||||
console.log(' ✅ Solo se usa getSession() en mount inicial')
|
||||
console.log(' ✅ Login page redirige manualmente después de login exitoso')
|
||||
console.log(' ✅ AuthGuard en layout maneja verificación centralizada')
|
||||
console.log('')
|
||||
|
||||
console.log('🏗️ ARQUITECTURA FINAL:')
|
||||
console.log(' 1. AuthProvider (lib/auth/context.tsx):')
|
||||
console.log(' - Solo getSession() en mount')
|
||||
console.log(' - NO onAuthStateChange listener')
|
||||
console.log(' ')
|
||||
console.log(' 2. AuthGuard (components/auth-guard.tsx):')
|
||||
console.log(' - Verifica user y pathname')
|
||||
console.log(' - Redirige a /aperture/login si no autenticado')
|
||||
console.log(' ')
|
||||
console.log(' 3. Login Page (app/aperture/login/page.tsx):')
|
||||
console.log(' - Solo formulario de login')
|
||||
console.log(' - signInWithPassword se llama')
|
||||
console.log(' - Después de login exitoso, manual router.push(/aperture)')
|
||||
console.log(' ')
|
||||
console.log(' 4. Dashboard (app/aperture/page.tsx):')
|
||||
console.log(' - Solo muestra datos del usuario')
|
||||
console.log(' - NO verificaciones de autenticación (AuthGuard las maneja)')
|
||||
console.log('')
|
||||
|
||||
console.log('🔄 FLUJO ESPERADO:')
|
||||
console.log(' 1. Usuario hace login')
|
||||
console.log(' 2. signInWithPassword llama a Supabase')
|
||||
console.log(' 3. Login success manualmente:')
|
||||
console.log(' router.push(/aperture)')
|
||||
console.log(' 4. AuthGuard detecta que user existe')
|
||||
console.log(' 5. AuthGuard NO redirige')
|
||||
console.log(' 6. Dashboard renderiza con usuario')
|
||||
console.log(' 7. NO múltiples eventos SIGNED_IN')
|
||||
console.log('')
|
||||
|
||||
console.log('🚫 CASOS QUE NO DEBERÍAN OCURRIR:')
|
||||
console.log(' ❌ Múltiples eventos "Auth state change: SIGNED_IN"')
|
||||
console.log(' ❌ Redirección loop entre /aperture y /aperture/login')
|
||||
console.log(' ❌ Dashboard en blanco o "Cargando..." infinito')
|
||||
console.log('')
|
||||
|
||||
console.log('🧪 PRUEBA DE INSTRUCCIONES:')
|
||||
console.log(' 1. Abrir browser en incógnito')
|
||||
console.log(' 2. Ir a: http://localhost:2311/aperture/login')
|
||||
console.log(' 3. Ingresar:')
|
||||
console.log(' Email: marco.gallegos@anchor23.mx')
|
||||
console.log(' Password: Marco123456!')
|
||||
console.log(' 4. Clic "Sign in"')
|
||||
console.log(' 5. VERIFICAR:')
|
||||
console.log(' ✓ Redirige a /aperture')
|
||||
console.log(' ✓ Dashboard carga')
|
||||
console.log(' ✓ Muestra 4 KPI Cards')
|
||||
console.log(' ✓ Muestra Tabla Top Performers')
|
||||
console.log(' ✓ Muestra Feed de Actividad')
|
||||
console.log(' ✓ NO regresa a login')
|
||||
console.log(' ✓ Console NO muestra múltiples "Auth state change: SIGNED_IN"')
|
||||
console.log('')
|
||||
|
||||
console.log('📊 KEY DIIFERENCIA CON ANTES:')
|
||||
console.log(' Antes: Múltiples onAuthStateChange listeners')
|
||||
console.log(' Después: Solo getSession() en mount inicial')
|
||||
console.log(' Antes: Login page redirigía + AuthGuard redirigía')
|
||||
console.log(' Después: Login page redirige manualmente una sola vez')
|
||||
console.log('')
|
||||
|
||||
console.log('========================================')
|
||||
console.log('READY TO TEST!')
|
||||
console.log('========================================')
|
||||
27
scripts/check-completed.js
Normal file
27
scripts/check-completed.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Check for completed bookings
|
||||
*/
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const supabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
);
|
||||
|
||||
async function checkCompletedBookings() {
|
||||
const { data, error } = await supabase
|
||||
.from('bookings')
|
||||
.select('id, status, end_time_utc')
|
||||
.eq('status', 'completed')
|
||||
.order('end_time_utc', { ascending: false })
|
||||
.limit(5);
|
||||
|
||||
if (error) {
|
||||
console.error('Error:', error);
|
||||
} else {
|
||||
console.log('Completed bookings:', data);
|
||||
}
|
||||
}
|
||||
|
||||
checkCompletedBookings();
|
||||
68
scripts/check-staff-records.js
Normal file
68
scripts/check-staff-records.js
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Check Staff Records Script
|
||||
*
|
||||
* This script checks which staff records exist for the admin user
|
||||
*/
|
||||
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const SUPABASE_URL = process.env.SUPABASE_URL;
|
||||
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
|
||||
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
|
||||
|
||||
async function checkStaffRecords() {
|
||||
console.log('🔍 Checking staff records...\n');
|
||||
|
||||
try {
|
||||
// 1. Get admin user from auth.users
|
||||
const { data: { users }, error: usersError } = await supabase.auth.admin.listUsers();
|
||||
|
||||
if (usersError) {
|
||||
console.error('❌ Error fetching auth.users:', usersError);
|
||||
return;
|
||||
}
|
||||
|
||||
const adminUser = users.find(u => u.email === 'marco.gallegos@anchor23.mx');
|
||||
|
||||
if (!adminUser) {
|
||||
console.error('❌ No admin user found in auth.users');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Found admin user in auth.users:');
|
||||
console.log(` Email: ${adminUser.email}`);
|
||||
console.log(` ID: ${adminUser.id}\n`);
|
||||
|
||||
// 2. Check which staff records exist with this user_id
|
||||
const { data: staffRecords, error: staffError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.eq('user_id', adminUser.id);
|
||||
|
||||
if (staffError) {
|
||||
console.error('❌ Error fetching staff records:', staffError);
|
||||
return;
|
||||
}
|
||||
|
||||
if (staffRecords.length > 0) {
|
||||
console.log(`✅ Found ${staffRecords.length} staff records with user_id = ${adminUser.id}:`);
|
||||
staffRecords.forEach((staff, index) => {
|
||||
console.log(` ${index + 1}. ${staff.display_name} (${staff.role})`);
|
||||
console.log(` Location ID: ${staff.location_id}`);
|
||||
console.log(` Active: ${staff.is_active}`);
|
||||
});
|
||||
console.log('\n✅ Admin user already has valid staff records!');
|
||||
console.log(' No fix needed.\n');
|
||||
} else {
|
||||
console.log('❌ No staff records found with user_id = ${adminUser.id}');
|
||||
console.log(' This is the problem - admin user has no staff record!\n');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Unexpected error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkStaffRecords();
|
||||
110
scripts/create-admin-user.js
Normal file
110
scripts/create-admin-user.js
Normal file
@@ -0,0 +1,110 @@
|
||||
const { createClient } = require('@supabase/supabase-js')
|
||||
require('dotenv').config({ path: '.env.local' })
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://pvvwbnybkadhreuqijsl.supabase.co'
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
/**
|
||||
* @description CRITICAL: Create admin user with full system access permissions
|
||||
* @param {string} locationId - UUID of location where admin will be assigned
|
||||
* @param {string} email - Admin email (default: marco.gallegos@anchor23.mx)
|
||||
* @param {string} password - Admin password (default: Anchor23!2026)
|
||||
* @param {string} phone - Admin phone number
|
||||
* @audit BUSINESS RULE: Only one admin user should exist per system instance
|
||||
* @audit SECURITY: Admin gets full access to all Aperture dashboard features
|
||||
* @audit Validate: Location must exist before admin creation
|
||||
* @audit Validate: Admin user gets role='admin' for maximum permissions
|
||||
* @audit AUDIT: Creation logged in both auth.users and staff tables
|
||||
* @audit RELIABILITY: Script validates all prerequisites before creation
|
||||
*/
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey)
|
||||
|
||||
async function createAdminUser() {
|
||||
try {
|
||||
console.log('=== Creating Admin User: Marco Gallegos ===')
|
||||
|
||||
const locationId = process.argv[2]
|
||||
const email = process.argv[3] || 'marco.gallegos@anchor23.mx'
|
||||
const password = process.argv[4] || 'Anchor23!2026'
|
||||
const displayName = 'Marco Gallegos'
|
||||
const role = 'admin'
|
||||
const phone = process.argv[5] || '+525512345678'
|
||||
|
||||
if (!locationId) {
|
||||
console.error('ERROR: location_id is required')
|
||||
console.log('Usage: node scripts/create-admin-user.js <location_id> [email] [password] [phone]')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log('Step 1: Checking if location exists...')
|
||||
const { data: location, error: locationError } = await supabase
|
||||
.from('locations')
|
||||
.select('id, name, timezone')
|
||||
.eq('id', locationId)
|
||||
.single()
|
||||
|
||||
if (locationError || !location) {
|
||||
console.error('ERROR: Location not found:', locationId)
|
||||
console.error('Location error:', locationError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Location found: ${location.name} (${location.timezone})`)
|
||||
|
||||
console.log('Step 2: Creating Supabase Auth user...')
|
||||
const { data: authUser, error: authError } = await supabase.auth.admin.createUser({
|
||||
email,
|
||||
password,
|
||||
email_confirm: true,
|
||||
user_metadata: {
|
||||
first_name: 'Marco',
|
||||
last_name: 'Gallegos'
|
||||
}
|
||||
})
|
||||
|
||||
if (authError || !authUser) {
|
||||
console.error('ERROR: Failed to create auth user:', authError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Auth user created: ${authUser.user.id}`)
|
||||
|
||||
console.log('Step 3: Creating staff record...')
|
||||
const { data: staff, error: staffError } = await supabase
|
||||
.from('staff')
|
||||
.insert({
|
||||
user_id: authUser.user.id,
|
||||
location_id: locationId,
|
||||
role: role,
|
||||
display_name: displayName,
|
||||
phone: phone,
|
||||
is_active: true
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (staffError || !staff) {
|
||||
console.error('ERROR: Failed to create staff record:', staffError)
|
||||
console.log('Cleaning up auth user...')
|
||||
await supabase.auth.admin.deleteUser(authUser.user.id)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Staff record created: ${staff.id}`)
|
||||
console.log('\n=== Admin User Created Successfully ===')
|
||||
console.log(`Email: ${email}`)
|
||||
console.log(`Password: ${password}`)
|
||||
console.log(`Name: ${displayName}`)
|
||||
console.log(`Role: ${role}`)
|
||||
console.log(`Location: ${location.name}`)
|
||||
console.log(`Staff ID: ${staff.id}`)
|
||||
console.log(`Auth User ID: ${authUser.user.id}`)
|
||||
console.log('\nLogin at: http://localhost:2311/aperture/login')
|
||||
console.log('=======================================\n')
|
||||
} catch (error) {
|
||||
console.error('ERROR:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
createAdminUser()
|
||||
87
scripts/debug-dashboard.js
Normal file
87
scripts/debug-dashboard.js
Normal file
@@ -0,0 +1,87 @@
|
||||
console.log('========================================')
|
||||
console.log('🧪 DASHBOARD DEBUG TEST PLAN')
|
||||
console.log('========================================')
|
||||
console.log('')
|
||||
|
||||
console.log('📋 Testing Steps:')
|
||||
console.log('')
|
||||
console.log('1️⃣ STEP 1: Login Test')
|
||||
console.log(' - Open browser: http://localhost:2311/aperture/login')
|
||||
console.log(' - Enter credentials:')
|
||||
console.log(' Email: marco.gallegos@anchor23.mx')
|
||||
console.log(' Password: Marco123456!')
|
||||
console.log(' - Click "Sign in"')
|
||||
console.log(' - Check console for:')
|
||||
console.log(' ✅ "Login page - Auth state change: INITIAL_SESSION"')
|
||||
console.log(' ✅ "Login page - Auth state change: SIGNED_IN"')
|
||||
console.log(' ✅ "Login page - Redirecting to: /aperture"')
|
||||
console.log(' ✅ "🔍 Dashboard mount - Auth state: { authLoading: false, userEmail: ..., userId: ... }"')
|
||||
console.log(' ✅ "✓ Dashboard rendering with user: marco.gallegos@anchor23.mx"')
|
||||
console.log(' ✅ "🔄 Dashboard useEffect - activeTab: dashboard"')
|
||||
console.log(' ✅ "📊 Fetching dashboard data..."')
|
||||
console.log('')
|
||||
|
||||
console.log('2️⃣ STEP 2: Verify Dashboard Loads')
|
||||
console.log(' - URL should be: http://localhost:2311/aperture')
|
||||
console.log(' - Should see:')
|
||||
console.log(' ✅ KPI Cards (4 cards: Citas Hoy, Ingresos Hoy, Pendientes, Total Mes)')
|
||||
console.log(' ✅ Table "Top Performers" (or empty if no data)')
|
||||
console.log(' ✅ "Feed de Actividad Reciente" (or empty if no data)')
|
||||
console.log(' - Should NOT see:')
|
||||
console.log(' ❌ "Cargando..." screen')
|
||||
console.log(' ❌ "Already logged in" or redirect loop')
|
||||
console.log(' ❌ Blank white screen')
|
||||
console.log('')
|
||||
|
||||
console.log('3️⃣ STEP 3: Check Browser Console for Errors')
|
||||
console.log(' - Look for red errors in console')
|
||||
console.log(' - Look for failed network requests (Network tab)')
|
||||
console.log(' - Expected logs:')
|
||||
console.log(' 📅 Bookings fetched: X')
|
||||
console.log(' (or any fetch errors)')
|
||||
console.log('')
|
||||
|
||||
console.log('🔍 Key Debug Logs to Look For:')
|
||||
console.log('')
|
||||
console.log('SUCCESS CASE (Working correctly):')
|
||||
console.log(' 📋 Login page - Auth state change: INITIAL_SESSION')
|
||||
console.log(' 📋 Login page - Auth state change: SIGNED_IN')
|
||||
console.log(' 📋 Login page - Redirecting to: /aperture')
|
||||
console.log(' 🔍 Dashboard mount - Auth state: { authLoading: false, userEmail: "marco.gallegos@anchor23.mx" }')
|
||||
console.log(' ✓ Dashboard rendering with user: marco.gallegos@anchor23.mx')
|
||||
console.log(' 🔄 Dashboard useEffect - activeTab: dashboard')
|
||||
console.log(' 📊 Fetching dashboard data...')
|
||||
console.log(' 📅 Bookings fetched: X')
|
||||
console.log('')
|
||||
console.log('ERROR CASE (Something wrong):')
|
||||
console.log(' ⏳ Dashboard showing loading state - authLoading: true')
|
||||
console.log(' ⚠️ Dashboard mounting WITHOUT user - user: null/undefined')
|
||||
console.log(' 🔄 Dashboard useEffect - activeTab: dashboard (but then stuck)')
|
||||
console.log(' ❌ No "Dashboard rendering" or "Dashboard useEffect" logs')
|
||||
console.log(' ❌ Browser console errors (red text)')
|
||||
console.log('')
|
||||
|
||||
console.log('📌 Known Issues and Expected Behavior:')
|
||||
console.log('')
|
||||
console.log('✅ Normal:')
|
||||
console.log(' - Bookings list may be empty (no bookings today)')
|
||||
console.log(' - Top Performers may be empty (no staff performance data)')
|
||||
console.log(' - Activity Feed may be empty (no recent activity)')
|
||||
console.log(' - This is OK - components will show empty states')
|
||||
console.log('')
|
||||
console.log('❌ Not Normal:')
|
||||
console.log(' - "Cargando..." stays on screen (infinite loading)')
|
||||
console.log(' - Blank white screen (no content rendered)')
|
||||
console.log(' - Redirect loop back to /aperture/login')
|
||||
console.log(' - Red error in browser console')
|
||||
console.log('')
|
||||
|
||||
console.log('📸 Take Screenshots of:')
|
||||
console.log(' 1. Login page')
|
||||
console.log(' 2. Dashboard (if it loads)')
|
||||
console.log(' 3. Browser console (Network tab showing requests)')
|
||||
console.log('')
|
||||
|
||||
console.log('========================================')
|
||||
console.log('READY TO TEST!')
|
||||
console.log('========================================')
|
||||
112
scripts/final-test-plan.js
Normal file
112
scripts/final-test-plan.js
Normal file
@@ -0,0 +1,112 @@
|
||||
console.log('========================================')
|
||||
console.log('🧪 AUTHGUARD - PLAN DE PRUEBA FINAL')
|
||||
console.log('========================================')
|
||||
console.log('')
|
||||
|
||||
console.log('📋 PROBLEMA SOLUCIONADO:')
|
||||
console.log(' - Removidos useEffect duplicados en login page')
|
||||
console.log(' - Removidos useEffect duplicados en dashboard page')
|
||||
console.log(' - Agregado AuthGuard en layout global')
|
||||
console.log(' - AuthGuard maneja autenticación centralizadamente')
|
||||
console.log('')
|
||||
|
||||
console.log('🏗️ ARQUITECTURA ACTUAL:')
|
||||
console.log(' 1. AuthProvider en app/layout.tsx (global)')
|
||||
console.log(' 2. AuthGuard envuelve children en app/layout.tsx')
|
||||
console.log(' 3. Login page: Solo formulario, sin lógica de redirección')
|
||||
console.log(' 4. Dashboard: Solo muestra datos, sin lógica de auth')
|
||||
console.log('')
|
||||
|
||||
console.log('🔄 FLUJO ESPERADO:')
|
||||
console.log(' 1. Usuario visita /aperture/login')
|
||||
console.log(' 2. Ingresa credenciales y hace login')
|
||||
console.log(' 3. Supabase auth → evento SIGNED_IN')
|
||||
console.log(' 4. AuthProvider actualiza user state')
|
||||
console.log(' 5. AuthGuard detecta que user existe')
|
||||
console.log(' 6. AuthGuard NO redirige (porque user existe)')
|
||||
console.log(' 7. Router.push(/aperture) en login page (si hay hasRedirected)')
|
||||
console.log(' 8. Dashboard carga con usuario autenticado')
|
||||
console.log('')
|
||||
|
||||
console.log('🔍 DIAGNÓSTICO DE ERRORES:')
|
||||
console.log('')
|
||||
console.log('CASO 1: AuthGuard no detecta user:')
|
||||
console.log(' Síntomas: Usuario queda en login page después de hacer login')
|
||||
console.log(' Causa: AuthProvider no está actualizando user state')
|
||||
console.log(' Solución: Verificar logs de AuthProvider en context.tsx')
|
||||
console.log('')
|
||||
|
||||
console.log('CASO 2: AuthGuard redirige incorrectamente:')
|
||||
console.log(' Síntomas: Usuario es redirigido a /aperture/login')
|
||||
console.log(' Causa: AuthGuard logic error en isProtectedRoute')
|
||||
console.log(' Solución: Revisar condición: isProtectedRoute = pathname?.startsWith('/aperture') && pathname !== '/aperture/login'')
|
||||
console.log('')
|
||||
|
||||
console.log('CASO 3: Loop de redirección:')
|
||||
console.log(' Síntomas: Usuario es redirigido entre login y dashboard')
|
||||
console.log(' Causa: Múltiples listeners en login page y AuthGuard')
|
||||
console.log(' Solución: Verificar que login page NO tiene listener de onAuthStateChange')
|
||||
console.log('')
|
||||
|
||||
console.log('CASO 4: Dashboard no carga:')
|
||||
console.log(' Síntomas: Pantalla blanca o "Cargando..." infinito')
|
||||
console.log(' Causa: AuthGuard muestra loading pero nunca termina')
|
||||
console.log(' Solución: Verificar que AuthProvider setea loading=false')
|
||||
console.log('')
|
||||
|
||||
console.log('📊 VERIFICACIÓN DE FIX:')
|
||||
console.log('')
|
||||
console.log('Archivos modificados:')
|
||||
console.log(' ✓ app/layout.tsx - Agregado AuthGuard')
|
||||
console.log(' ✓ components/auth-guard.tsx - Nuevo componente AuthGuard')
|
||||
console.log(' ✓ app/aperture/page.tsx - Removidos useEffect duplicados')
|
||||
console.log(' ✓ app/aperture/login/page.tsx - Simplificado sin listeners')
|
||||
console.log('')
|
||||
|
||||
console.log('📝 INSTRUCCIONES DE PRUEBA:')
|
||||
console.log('')
|
||||
console.log('1. Abrir browser en incógnito (para limpiar cookies/sesiones)')
|
||||
console.log(' URL: http://localhost:2311/aperture/login')
|
||||
console.log('')
|
||||
|
||||
console.log('2. Abrir F12 → Console tab')
|
||||
console.log('')
|
||||
|
||||
console.log('3. Ingresar credenciales:')
|
||||
console.log(' Email: marco.gallegos@anchor23.mx')
|
||||
console.log(' Password: Marco123456!')
|
||||
console.log('')
|
||||
|
||||
console.log('4. Clic en "Sign in"')
|
||||
console.log('')
|
||||
|
||||
console.log('5. VERIFICAR CONSOLA:')
|
||||
console.log(' - Debería mostrar: "AuthGuard: Redirecting to /aperture/login - Path: /aperture/login"')
|
||||
console.log(' - Debería mostrar: "Auth state change: SIGNED_IN marco.gallegos@anchor23.mx"')
|
||||
console.log(' - Debería mostrar: "Login page - Redirecting to: /aperture"')
|
||||
console.log('')
|
||||
|
||||
console.log('6. VERIFICAR REDIRECCIÓN:')
|
||||
console.log(' - Debería cambiar a: http://localhost:2311/aperture')
|
||||
console.log(' - Debería mostrar dashboard con:')
|
||||
console.log(' ✓ 4 KPI Cards (Citas Hoy, Ingresos Hoy, Pendientes, Total Mes)')
|
||||
console.log(' ✓ Tabla Top Performers (o "No data" message)')
|
||||
console.log(' ✓ Feed de Actividad (o "No activity" message)')
|
||||
console.log('')
|
||||
|
||||
console.log('7. VERIFICAR QUE NO HAY LOOP:')
|
||||
console.log(' - URL debe ser: http://localhost:2311/aperture')
|
||||
console.log(' - NO debe regresar a: /aperture/login')
|
||||
console.log(' - Console NO debe mostrar más eventos SIGNED_IN repetidos')
|
||||
console.log('')
|
||||
|
||||
console.log('⚠️ ERRORES ESPERADOS:')
|
||||
console.log(' - "Cargando..." se queda en pantalla')
|
||||
console.log(' - Redirección de vuelta a login page')
|
||||
console.log(' - Multiple "Auth state change: SIGNED_IN" messages')
|
||||
console.log(' - Console errors en rojo')
|
||||
console.log('')
|
||||
|
||||
console.log('========================================')
|
||||
console.log('READY TO TEST!')
|
||||
console.log('========================================')
|
||||
141
scripts/fix-staff-user-id.js
Normal file
141
scripts/fix-staff-user-id.js
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Fix Staff User ID Mapping Script
|
||||
*
|
||||
* This script fixes the SECONDARY blocker in authentication:
|
||||
* - Staff record has user_id = random UUID (from seed_data.sql)
|
||||
* - Instead of the real auth.users user_id
|
||||
*
|
||||
* This script:
|
||||
* 1. Gets the admin user from auth.users
|
||||
* 2. Updates the staff record with the real user_id
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/fix-staff-user-id.js [--email <email>]
|
||||
*/
|
||||
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const SUPABASE_URL = process.env.SUPABASE_URL;
|
||||
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
|
||||
|
||||
if (!SUPABASE_URL || !SUPABASE_SERVICE_ROLE_KEY) {
|
||||
console.error('❌ ERROR: Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
|
||||
|
||||
async function fixStaffUserId() {
|
||||
console.log('🔧 Fixing staff user_id mapping...\n');
|
||||
|
||||
try {
|
||||
// 1. Get admin user from auth.users (using service role)
|
||||
const { data: { users }, error: usersError } = await supabase.auth.admin.listUsers();
|
||||
|
||||
if (usersError) {
|
||||
console.error('❌ Error fetching auth.users:', usersError);
|
||||
return;
|
||||
}
|
||||
|
||||
// Find admin user (email starts with 'admin' or 'marco')
|
||||
const adminUser = users.find(u =>
|
||||
u.email?.startsWith('admin') || u.email?.startsWith('marco') || u.email?.includes('@')
|
||||
);
|
||||
|
||||
if (!adminUser) {
|
||||
console.error('❌ No admin user found in auth.users');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Found admin user in auth.users:');
|
||||
console.log(` Email: ${adminUser.email}`);
|
||||
console.log(` ID: ${adminUser.id}\n`);
|
||||
|
||||
// 2. Find staff records with invalid user_id (random UUIDs)
|
||||
const { data: staffRecords, error: staffError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.is('is_active', true);
|
||||
|
||||
if (staffError) {
|
||||
console.error('❌ Error fetching staff records:', staffError);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`📊 Found ${staffRecords.length} active staff records\n`);
|
||||
|
||||
// 3. Check if any staff record has a user_id that matches auth.users
|
||||
let matchedStaff = null;
|
||||
for (const staff of staffRecords) {
|
||||
const { data: { users: matchingUsers }, error: matchError } = await supabase.auth.admin.getUserById(staff.user_id);
|
||||
|
||||
if (!matchError && matchingUsers) {
|
||||
console.log('✅ Staff record already has valid user_id:', staff.display_name);
|
||||
console.log(` Staff user_id: ${staff.user_id}`);
|
||||
console.log(` Staff role: ${staff.role}\n`);
|
||||
matchedStaff = staff;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (matchedStaff) {
|
||||
console.log('✅ Staff record already has valid user_id mapping!');
|
||||
console.log(' No fix needed.\n');
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. Update the first admin staff record with the real user_id
|
||||
const adminStaff = staffRecords.find(s => s.role === 'admin');
|
||||
|
||||
if (!adminStaff) {
|
||||
console.error('❌ No admin staff record found');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('🔧 Updating staff record:');
|
||||
console.log(` Display Name: ${adminStaff.display_name}`);
|
||||
console.log(` Old user_id: ${adminStaff.user_id}`);
|
||||
console.log(` New user_id: ${adminUser.id}`);
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('staff')
|
||||
.update({ user_id: adminUser.id })
|
||||
.eq('id', adminStaff.id);
|
||||
|
||||
if (updateError) {
|
||||
console.error('❌ Error updating staff record:', updateError);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('\n✅ Staff user_id fixed successfully!\n');
|
||||
|
||||
// 5. Verify the fix
|
||||
console.log('🔍 Verifying fix...');
|
||||
const { data: updatedStaff, error: verifyError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.eq('id', adminStaff.id)
|
||||
.single();
|
||||
|
||||
if (verifyError) {
|
||||
console.error('❌ Error verifying fix:', verifyError);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Verification successful:');
|
||||
console.log(` Staff: ${updatedStaff.display_name}`);
|
||||
console.log(` Role: ${updatedStaff.role}`);
|
||||
console.log(` Location: ${updatedStaff.location_id}`);
|
||||
console.log(` User ID: ${updatedStaff.user_id}`);
|
||||
console.log(` Auth User ID: ${adminUser.id}`);
|
||||
console.log(` Match: ${updatedStaff.user_id === adminUser.id ? '✅ YES' : '❌ NO'}\n`);
|
||||
|
||||
console.log('🎉 Fix complete! You can now log in to /aperture\n');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Unexpected error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
fixStaffUserId();
|
||||
50
scripts/list-locations.js
Normal file
50
scripts/list-locations.js
Normal file
@@ -0,0 +1,50 @@
|
||||
const { createClient } = require('@supabase/supabase-js')
|
||||
|
||||
require('dotenv').config({ path: '.env.local' })
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://pvvwbnybkadhreuqijsl.supabase.co'
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey)
|
||||
|
||||
async function listLocations() {
|
||||
try {
|
||||
console.log('=== Listing Available Locations ===\n')
|
||||
|
||||
const { data: locations, error } = await supabase
|
||||
.from('locations')
|
||||
.select('id, name, timezone, address, is_active')
|
||||
.order('name', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
console.error('ERROR fetching locations:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!locations || locations.length === 0) {
|
||||
console.log('No locations found. You need to create locations first.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log('Available locations:\n')
|
||||
locations.forEach((loc, index) => {
|
||||
console.log(`${index + 1}. ${loc.name}`)
|
||||
console.log(` ID: ${loc.id}`)
|
||||
console.log(` Timezone: ${loc.timezone}`)
|
||||
if (loc.address) console.log(` Address: ${loc.address}`)
|
||||
console.log(` Active: ${loc.is_active ? 'Yes' : 'No'}`)
|
||||
console.log('')
|
||||
})
|
||||
|
||||
console.log('To create an admin user, run:')
|
||||
console.log(` node scripts/create-admin-user.js <location_id>`)
|
||||
console.log('\nExample:')
|
||||
console.log(` node scripts/create-admin-user.js ${locations[0].id}`)
|
||||
console.log('\n========================================\n')
|
||||
} catch (error) {
|
||||
console.error('ERROR:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
listLocations()
|
||||
57
scripts/reset-admin-password.js
Normal file
57
scripts/reset-admin-password.js
Normal file
@@ -0,0 +1,57 @@
|
||||
const { createClient } = require('@supabase/supabase-js')
|
||||
require('dotenv').config({ path: '.env.local' })
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://pvvwbnybkadhreuqijsl.supabase.co'
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey)
|
||||
|
||||
async function resetAdminPassword() {
|
||||
try {
|
||||
console.log('=== Resetting Admin Password ===\n')
|
||||
|
||||
const email = 'marco.gallegos@anchor23.mx'
|
||||
const newPassword = 'Marco123456!'
|
||||
|
||||
console.log('Step 1: Finding auth user...')
|
||||
const { data: { users }, error: listError } = await supabase.auth.admin.listUsers()
|
||||
|
||||
if (listError) {
|
||||
console.error('ERROR listing users:', listError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const authUser = users.find(u => u.email === email)
|
||||
|
||||
if (!authUser) {
|
||||
console.error('ERROR: Auth user not found')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Auth user found: ${authUser.id}`)
|
||||
|
||||
console.log('Step 2: Resetting password...')
|
||||
const { error: updateError } = await supabase.auth.admin.updateUserById(
|
||||
authUser.id,
|
||||
{ password: newPassword }
|
||||
)
|
||||
|
||||
if (updateError) {
|
||||
console.error('ERROR updating password:', updateError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Password updated successfully`)
|
||||
|
||||
console.log('\n=== Password Reset Successfully ===')
|
||||
console.log(`Email: ${email}`)
|
||||
console.log(`New Password: ${newPassword}`)
|
||||
console.log('\nLogin at: http://localhost:2311/aperture/login')
|
||||
console.log('====================================\n')
|
||||
} catch (error) {
|
||||
console.error('ERROR:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
resetAdminPassword()
|
||||
44
scripts/test-login-flow-v2.js
Normal file
44
scripts/test-login-flow-v2.js
Normal file
@@ -0,0 +1,44 @@
|
||||
console.log('=== Login Flow Test Plan ===\n')
|
||||
|
||||
console.log('📋 Testing Steps:')
|
||||
console.log('')
|
||||
console.log('1️⃣ Access /aperture (should redirect to /aperture/login)')
|
||||
console.log(' URL: http://localhost:2311/aperture')
|
||||
console.log('')
|
||||
console.log('2️⃣ Access /aperture/login directly')
|
||||
console.log(' URL: http://localhost:2311/aperture/login')
|
||||
console.log('')
|
||||
console.log('3️⃣ Login with credentials:')
|
||||
console.log(' Email: marco.gallegos@anchor23.mx')
|
||||
console.log(' Password: Marco123456!')
|
||||
console.log('')
|
||||
console.log('4️⃣ Expected behavior:')
|
||||
console.log(' ✓ Single redirect to /aperture (NOT multiple)')
|
||||
console.log(' ✓ Dashboard loads successfully')
|
||||
console.log(' ✓ No redirect loop back to login')
|
||||
console.log(' ✓ Browser stays on /aperture')
|
||||
console.log('')
|
||||
|
||||
console.log('🔍 Expected console logs:')
|
||||
console.log(' Step 1: Login page - Auth state change: INITIAL_SESSION marco.gallegos@anchor23.mx')
|
||||
console.log(' Step 2: Auth state change: SIGNED_IN marco.gallegos@anchor23.mx')
|
||||
console.log(' Step 3: Login page - Redirecting to: /aperture')
|
||||
console.log(' Step 4: (NO MORE LOGS - should NOT show "Already logged in" or redirect again)')
|
||||
console.log('')
|
||||
|
||||
console.log('🚫 NOT Expected:')
|
||||
console.log(' ❌ Multiple "Already logged in" messages')
|
||||
console.log(' ❌ Multiple "Redirecting to: /aperture" messages')
|
||||
console.log(' ❌ Redirect loop back to login')
|
||||
console.log('')
|
||||
|
||||
console.log('📊 Key Changes Made:')
|
||||
console.log(' ✓ Added hasRedirected state flag')
|
||||
console.log(' ✓ Removed duplicate checkSession useEffect')
|
||||
console.log(' ✓ Modified onAuthStateChange to check !hasRedirected')
|
||||
console.log(' ✓ Reset hasRedirected=false on new login')
|
||||
console.log('')
|
||||
|
||||
console.log('========================================\n')
|
||||
console.log('Ready to test! Open browser and follow steps above.')
|
||||
console.log('========================================')
|
||||
85
scripts/test-login-flow.js
Normal file
85
scripts/test-login-flow.js
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Test Login Flow Script
|
||||
*
|
||||
* This script tests the login flow to verify the RLS policy fix works
|
||||
*/
|
||||
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||
const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
||||
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
|
||||
|
||||
async function testLoginFlow() {
|
||||
console.log('🧪 Testing Login Flow...\n');
|
||||
|
||||
try {
|
||||
// 1. Test sign in with admin credentials
|
||||
console.log('1️⃣ Testing sign in...');
|
||||
const { data: { user }, error: signInError } = await supabase.auth.signInWithPassword({
|
||||
email: 'marco.gallegos@anchor23.mx',
|
||||
password: 'Marco123456!'
|
||||
});
|
||||
|
||||
if (signInError) {
|
||||
console.error('❌ Sign in failed:', signInError);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Sign in successful!');
|
||||
console.log(` Email: ${user.email}`);
|
||||
console.log(` User ID: ${user.id}\n`);
|
||||
|
||||
// 2. Test querying staff table (this is what middleware does)
|
||||
console.log('2️⃣ Testing staff query (middleware simulation)...');
|
||||
const { data: staff, error: staffError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.single();
|
||||
|
||||
if (staffError) {
|
||||
console.error('❌ Staff query failed:', staffError);
|
||||
console.log(' This is the RLS policy issue!');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Staff query successful!');
|
||||
console.log(` Name: ${staff.display_name}`);
|
||||
console.log(` Role: ${staff.role}`);
|
||||
console.log(` Location: ${staff.location_id}\n`);
|
||||
|
||||
// 3. Test getting dashboard data
|
||||
console.log('3️⃣ Testing dashboard API...');
|
||||
const { data: sessionData } = await supabase.auth.getSession();
|
||||
|
||||
// Test redirect by checking if we can access the dashboard page
|
||||
console.log('3️⃣ Testing redirect to dashboard page...');
|
||||
const dashboardResponse = await fetch('http://localhost:2311/aperture', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${sessionData.session.access_token}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!dashboardResponse.ok) {
|
||||
console.error('❌ Dashboard API failed:', dashboardResponse.status);
|
||||
console.log(' Response:', await dashboardResponse.text());
|
||||
return;
|
||||
}
|
||||
|
||||
const dashboardData = await dashboardResponse.json();
|
||||
console.log('✅ Dashboard API successful!');
|
||||
console.log(` KPI Cards: ${dashboardData.kpi_cards ? '✅' : '❌'}`);
|
||||
console.log(` Top Performers: ${dashboardData.top_performers ? '✅' : '❌'}`);
|
||||
console.log(` Activity Feed: ${dashboardData.activity_feed ? '✅' : '❌'}\n`);
|
||||
|
||||
console.log('🎉 All tests passed! Login flow is working!\n');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Unexpected error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
testLoginFlow();
|
||||
98
scripts/test-login-loop.js
Normal file
98
scripts/test-login-loop.js
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Test Login Loop Script
|
||||
* This script simulates the login flow to detect redirect loops
|
||||
*/
|
||||
|
||||
const puppeteer = require('puppeteer');
|
||||
|
||||
async function testLoginLoop() {
|
||||
console.log('🧪 Testing Login Loop...\n');
|
||||
|
||||
let browser;
|
||||
try {
|
||||
browser = await puppeteer.launch({ headless: false });
|
||||
const page = await browser.newPage();
|
||||
|
||||
// Track redirects
|
||||
const redirects = [];
|
||||
page.on('response', response => {
|
||||
if (response.status() >= 300 && response.status() < 400) {
|
||||
console.log(`Redirect: ${response.url()} -> ${response.headers().location}`);
|
||||
redirects.push({
|
||||
from: response.url(),
|
||||
to: response.headers().location,
|
||||
status: response.status()
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Track navigation
|
||||
page.on('framenavigated', frame => {
|
||||
if (frame === page.mainFrame()) {
|
||||
console.log(`Navigated to: ${frame.url()}`);
|
||||
}
|
||||
});
|
||||
|
||||
console.log('1️⃣ Loading login page...');
|
||||
await page.goto('http://localhost:2311/aperture/login', { waitUntil: 'networkidle2' });
|
||||
|
||||
// Check if we get stuck in loading
|
||||
const loadingElement = await page.$('text=Cargando...');
|
||||
if (loadingElement) {
|
||||
console.log('⚠️ Page stuck in loading state');
|
||||
|
||||
// Wait a bit more to see if it resolves
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
const stillLoading = await page.$('text=Cargando...');
|
||||
if (stillLoading) {
|
||||
console.log('❌ Page still stuck in loading after 5 seconds');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('2️⃣ Attempting login...');
|
||||
|
||||
// Fill login form
|
||||
await page.type('input[name="email"]', 'marco.gallegos@anchor23.mx');
|
||||
await page.type('input[name="password"]', 'Marco123456!');
|
||||
|
||||
// Click login button
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for navigation or error
|
||||
try {
|
||||
await page.waitForNavigation({ timeout: 10000, waitUntil: 'networkidle2' });
|
||||
console.log('✅ Navigation completed');
|
||||
console.log(`Final URL: ${page.url()}`);
|
||||
} catch (error) {
|
||||
console.log('❌ Navigation timeout or error');
|
||||
console.log(`Current URL: ${page.url()}`);
|
||||
|
||||
// Check for error messages
|
||||
const errorElement = await page.$('[class*="text-red-600"]');
|
||||
if (errorElement) {
|
||||
const errorText = await page.evaluate(el => el.textContent, errorElement);
|
||||
console.log(`Error message: ${errorText}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n📊 Redirect Summary:');
|
||||
redirects.forEach((redirect, index) => {
|
||||
console.log(`${index + 1}. ${redirect.from} -> ${redirect.to} (${redirect.status})`);
|
||||
});
|
||||
|
||||
if (redirects.length > 3) {
|
||||
console.log('⚠️ Multiple redirects detected - possible loop!');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Test failed:', error);
|
||||
} finally {
|
||||
if (browser) {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
testLoginLoop();
|
||||
80
scripts/test-middleware.js
Normal file
80
scripts/test-middleware.js
Normal file
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Test Middleware Authentication
|
||||
* Tests if the middleware properly recognizes authenticated requests
|
||||
*/
|
||||
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||
const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
||||
|
||||
async function testMiddleware() {
|
||||
console.log('🧪 Testing Middleware Authentication...\n');
|
||||
|
||||
// Create authenticated client
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
|
||||
auth: {
|
||||
autoRefreshToken: true,
|
||||
persistSession: true,
|
||||
detectSessionInUrl: true
|
||||
}
|
||||
});
|
||||
|
||||
console.log('1️⃣ Signing in...');
|
||||
const { data: authData, error: signInError } = await supabase.auth.signInWithPassword({
|
||||
email: 'marco.gallegos@anchor23.mx',
|
||||
password: 'Marco123456!'
|
||||
});
|
||||
|
||||
if (signInError) {
|
||||
console.error('❌ Sign in failed:', signInError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Sign in successful!');
|
||||
|
||||
// Test middleware by simulating the same logic
|
||||
console.log('\n2️⃣ Testing middleware logic...');
|
||||
|
||||
const middlewareSupabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
|
||||
|
||||
// This simulates what the middleware does
|
||||
const { data: { session }, error: sessionError } = await middlewareSupabase.auth.getSession();
|
||||
|
||||
if (sessionError) {
|
||||
console.error('❌ Middleware session error:', sessionError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
console.error('❌ Middleware: No session found');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Middleware: Session found');
|
||||
console.log(` User: ${session.user.email}`);
|
||||
|
||||
const { data: staff, error: staffError } = await middlewareSupabase
|
||||
.from('staff')
|
||||
.select('role')
|
||||
.eq('user_id', session.user.id)
|
||||
.single();
|
||||
|
||||
if (staffError) {
|
||||
console.error('❌ Middleware staff query error:', staffError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!staff || !['admin', 'manager', 'staff'].includes(staff.role)) {
|
||||
console.error('❌ Middleware: Invalid role or no staff record');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Middleware: Role check passed');
|
||||
console.log(` Role: ${staff.role}`);
|
||||
|
||||
console.log('\n🎉 Middleware test passed! Authentication should work.');
|
||||
}
|
||||
|
||||
testMiddleware();
|
||||
96
scripts/test-simple-auth.js
Normal file
96
scripts/test-simple-auth.js
Normal file
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Simple Login Test Script
|
||||
* Tests the authentication flow without browser automation
|
||||
*/
|
||||
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||
const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
||||
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
|
||||
|
||||
async function testAuthFlow() {
|
||||
console.log('🧪 Testing Authentication Flow...\n');
|
||||
|
||||
try {
|
||||
console.log('1️⃣ Testing sign in...');
|
||||
const { data: authData, error: signInError } = await supabase.auth.signInWithPassword({
|
||||
email: 'marco.gallegos@anchor23.mx',
|
||||
password: 'Marco123456!'
|
||||
});
|
||||
|
||||
if (signInError) {
|
||||
console.error('❌ Sign in failed:', signInError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Sign in successful!');
|
||||
console.log(` User: ${authData.user.email}`);
|
||||
console.log(` Session: ${authData.session ? '✅' : '❌'}`);
|
||||
|
||||
if (authData.session) {
|
||||
console.log(` Access Token: ${authData.session.access_token.substring(0, 20)}...`);
|
||||
console.log(` Refresh Token: ${authData.session.refresh_token.substring(0, 20)}...`);
|
||||
}
|
||||
|
||||
console.log('\n2️⃣ Testing staff query (middleware simulation)...');
|
||||
const { data: staff, error: staffError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.eq('user_id', authData.user.id)
|
||||
.single();
|
||||
|
||||
if (staffError) {
|
||||
console.error('❌ Staff query failed:', staffError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✅ Staff query successful!');
|
||||
console.log(` Name: ${staff.display_name}`);
|
||||
console.log(` Role: ${staff.role}`);
|
||||
|
||||
console.log('\n3️⃣ Testing session persistence with same client...');
|
||||
// Test with the same client
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
const { data: sessionData, error: sessionError } = await supabase.auth.getSession();
|
||||
|
||||
if (sessionError) {
|
||||
console.error('❌ Session error:', sessionError.message);
|
||||
} else if (sessionData.session) {
|
||||
console.log('✅ Session persisted!');
|
||||
console.log(` User: ${sessionData.session.user.email}`);
|
||||
} else {
|
||||
console.error('❌ Session lost!');
|
||||
}
|
||||
|
||||
console.log('\n4️⃣ Testing dashboard access with authenticated client...');
|
||||
const { data: dashboardData, error: dashboardError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.eq('user_id', authData.user.id);
|
||||
|
||||
if (dashboardError) {
|
||||
console.error('❌ Dashboard access failed:', dashboardError.message);
|
||||
} else {
|
||||
console.log('✅ Dashboard access successful!');
|
||||
console.log(` Staff records: ${dashboardData.length}`);
|
||||
}
|
||||
|
||||
console.log(` Status: ${dashboardResponse.status}`);
|
||||
console.log(` Location: ${dashboardResponse.headers.get('location') || 'none'}`);
|
||||
|
||||
if (dashboardResponse.status === 200) {
|
||||
console.log('✅ Dashboard accessible!');
|
||||
} else if (dashboardResponse.status >= 300 && dashboardResponse.status < 400) {
|
||||
console.log(`➡️ Redirect to: ${dashboardResponse.headers.get('location')}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Unexpected error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
testAuthFlow();
|
||||
27
scripts/test-simple-query.js
Normal file
27
scripts/test-simple-query.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Test simple dashboard query
|
||||
*/
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
require('dotenv').config();
|
||||
|
||||
const supabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
);
|
||||
|
||||
async function testSimpleQuery() {
|
||||
console.log('Testing simple bookings query...');
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('bookings')
|
||||
.select('id, status, total_amount')
|
||||
.limit(5);
|
||||
|
||||
if (error) {
|
||||
console.error('Error:', error);
|
||||
} else {
|
||||
console.log('Success:', data);
|
||||
}
|
||||
}
|
||||
|
||||
testSimpleQuery();
|
||||
67
scripts/verify-admin-user.js
Normal file
67
scripts/verify-admin-user.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const { createClient } = require('@supabase/supabase-js')
|
||||
require('dotenv').config({ path: '.env.local' })
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://pvvwbnybkadhreuqijsl.supabase.co'
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey)
|
||||
|
||||
async function verifyAdminUser() {
|
||||
try {
|
||||
console.log('=== Verifying Admin User: Marco Gallegos ===\n')
|
||||
|
||||
const email = 'marco.gallegos@anchor23.mx'
|
||||
|
||||
console.log('Step 1: Checking auth user...')
|
||||
const { data: { users }, error: authError } = await supabase.auth.admin.listUsers()
|
||||
|
||||
if (authError) {
|
||||
console.error('ERROR listing users:', authError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const authUser = users.find(u => u.email === email)
|
||||
|
||||
if (!authUser) {
|
||||
console.error('ERROR: Auth user not found')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Auth user found: ${authUser.id}`)
|
||||
|
||||
console.log('Step 2: Checking staff record...')
|
||||
const { data: staff, error: staffError } = await supabase
|
||||
.from('staff')
|
||||
.select('*')
|
||||
.eq('user_id', authUser.id)
|
||||
.single()
|
||||
|
||||
if (staffError || !staff) {
|
||||
console.error('ERROR: Staff record not found:', staffError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`✓ Staff record found: ${staff.id}`)
|
||||
console.log(`✓ Role: ${staff.role}`)
|
||||
console.log(`✓ Display Name: ${staff.display_name}`)
|
||||
console.log(`✓ Location ID: ${staff.location_id}`)
|
||||
console.log(`✓ Is Active: ${staff.is_active}`)
|
||||
console.log(`✓ Phone: ${staff.phone || 'N/A'}`)
|
||||
|
||||
if (!['admin', 'manager', 'staff'].includes(staff.role)) {
|
||||
console.error('\n✗ ERROR: User role is NOT authorized for Aperture!')
|
||||
console.error(` Current role: ${staff.role}`)
|
||||
console.error(` Expected: admin, manager, or staff`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log('\n=== Admin User Verified Successfully ===')
|
||||
console.log('User can access Aperture dashboard')
|
||||
console.log('=========================================\n')
|
||||
} catch (error) {
|
||||
console.error('ERROR:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
verifyAdminUser()
|
||||
Reference in New Issue
Block a user