Fix Google Login CORS and role-based redirection
This commit is contained in:
@ -110,12 +110,19 @@ app = FastAPI(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# CORS middleware
|
# CORS middleware
|
||||||
origins = ["*"] # Permitir todos para producción corregida
|
origins = [
|
||||||
|
"http://localhost:5173",
|
||||||
|
"http://127.0.0.1:5173",
|
||||||
|
"https://sibu-frontend.vercel.app",
|
||||||
|
"https://sibu-transport.web.app",
|
||||||
|
"https://sibu2-0-transport-2026.firebaseapp.com",
|
||||||
|
"https://sibu2-0-transport-2026.web.app",
|
||||||
|
]
|
||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=origins,
|
allow_origins=origins,
|
||||||
|
allow_origin_regex="https://.*sibu.*\.vercel\.app", # Permitir subdominios de vercel con 'sibu'
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
|
|||||||
@ -50,6 +50,14 @@ const handleLogin = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const navigateByUserRole = (role: string) => {
|
||||||
|
const r = role.toUpperCase()
|
||||||
|
if (r === 'ADMIN') router.push('/admin')
|
||||||
|
else if (r === 'DRIVER') router.push('/driver')
|
||||||
|
else if (r === 'PROMOTER') router.push('/promoter')
|
||||||
|
else router.push('/map')
|
||||||
|
}
|
||||||
|
|
||||||
const handleGoogleLogin = async () => {
|
const handleGoogleLogin = async () => {
|
||||||
isLoading.value = true
|
isLoading.value = true
|
||||||
errorMessage.value = ''
|
errorMessage.value = ''
|
||||||
@ -63,11 +71,17 @@ const handleGoogleLogin = async () => {
|
|||||||
const response = await authService.googleLogin(token)
|
const response = await authService.googleLogin(token)
|
||||||
console.log('Backend Google login exitoso:', response)
|
console.log('Backend Google login exitoso:', response)
|
||||||
authStore.login(response.access_token, response.role, response.full_name)
|
authStore.login(response.access_token, response.role, response.full_name)
|
||||||
router.push('/map')
|
|
||||||
|
// Navigate based on actual role from backend
|
||||||
|
navigateByUserRole(response.role)
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('Error Google Login:', error)
|
console.error('Error Google Login:', error)
|
||||||
|
if (error.response?.data?.detail) {
|
||||||
|
errorMessage.value = `Error: ${error.response.data.detail}`
|
||||||
|
} else {
|
||||||
errorMessage.value = `Error con Google: ${error.message || 'Error desconocido'}`
|
errorMessage.value = `Error con Google: ${error.message || 'Error desconocido'}`
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false
|
isLoading.value = false
|
||||||
}
|
}
|
||||||
|
|||||||
@ -54,7 +54,7 @@ const handleRegister = async () => {
|
|||||||
|
|
||||||
// Redirigir casi de inmediato
|
// Redirigir casi de inmediato
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
router.push('/map')
|
navigateByUserRole(response.role)
|
||||||
}, 1000)
|
}, 1000)
|
||||||
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@ -71,6 +71,14 @@ const handleRegister = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const navigateByUserRole = (role: string) => {
|
||||||
|
const r = role.toUpperCase()
|
||||||
|
if (r === 'ADMIN') router.push('/admin')
|
||||||
|
else if (r === 'DRIVER') router.push('/driver')
|
||||||
|
else if (r === 'PROMOTER') router.push('/promoter')
|
||||||
|
else router.push('/map')
|
||||||
|
}
|
||||||
|
|
||||||
const handleGoogleRegister = async () => {
|
const handleGoogleRegister = async () => {
|
||||||
isLoading.value = true
|
isLoading.value = true
|
||||||
errorMessage.value = ''
|
errorMessage.value = ''
|
||||||
@ -82,7 +90,7 @@ const handleGoogleRegister = async () => {
|
|||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
const response = await authService.googleLogin(token)
|
const response = await authService.googleLogin(token)
|
||||||
console.log('Backend Google login exitoso:', response)
|
console.log('Backend Google login/register exitoso:', response)
|
||||||
|
|
||||||
analyticsService.logEvent({
|
analyticsService.logEvent({
|
||||||
event_name: 'sign_up',
|
event_name: 'sign_up',
|
||||||
@ -90,12 +98,18 @@ const handleGoogleRegister = async () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
authStore.login(response.access_token, response.role, response.full_name)
|
authStore.login(response.access_token, response.role, response.full_name)
|
||||||
router.push('/map')
|
|
||||||
|
// Navigate based on actual role from backend
|
||||||
|
navigateByUserRole(response.role)
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('Error Google Register:', error)
|
console.error('Error Google Register:', error)
|
||||||
|
if (error.response?.data?.detail) {
|
||||||
|
errorMessage.value = `Error: ${error.response.data.detail}`
|
||||||
|
} else {
|
||||||
errorMessage.value = `Error con Google: ${error.message || 'Intenta de nuevo'}`
|
errorMessage.value = `Error con Google: ${error.message || 'Intenta de nuevo'}`
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false
|
isLoading.value = false
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,6 +19,9 @@ const firebaseConfig = {
|
|||||||
const app = initializeApp(firebaseConfig);
|
const app = initializeApp(firebaseConfig);
|
||||||
export const auth = getAuth(app);
|
export const auth = getAuth(app);
|
||||||
export const googleProvider = new GoogleAuthProvider();
|
export const googleProvider = new GoogleAuthProvider();
|
||||||
|
googleProvider.setCustomParameters({
|
||||||
|
prompt: 'select_account'
|
||||||
|
});
|
||||||
|
|
||||||
// Detect if the user is on a mobile device
|
// Detect if the user is on a mobile device
|
||||||
const isMobile = () => {
|
const isMobile = () => {
|
||||||
@ -35,11 +38,13 @@ export const signInWithGoogle = async (): Promise<{ user: any; token: string }>
|
|||||||
if (isMobile()) {
|
if (isMobile()) {
|
||||||
console.log("DEBUG: Intentando signInWithRedirect...");
|
console.log("DEBUG: Intentando signInWithRedirect...");
|
||||||
await signInWithRedirect(auth, googleProvider);
|
await signInWithRedirect(auth, googleProvider);
|
||||||
|
// On mobile, the page reloads, so we return a promise that doesn't resolve
|
||||||
|
// here as the app will re-initialize on the callback URL.
|
||||||
return new Promise(() => { });
|
return new Promise(() => { });
|
||||||
} else {
|
} else {
|
||||||
console.log("DEBUG: Intentando signInWithPopup...");
|
console.log("DEBUG: Intentando signInWithPopup...");
|
||||||
const result = await signInWithPopup(auth, googleProvider);
|
const result = await signInWithPopup(auth, googleProvider);
|
||||||
const token = await result.user.getIdToken();
|
const token = await result.user.getIdToken(true); // Force refresh to get fresh token
|
||||||
return { user: result.user, token };
|
return { user: result.user, token };
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@ -49,20 +54,21 @@ export const signInWithGoogle = async (): Promise<{ user: any; token: string }>
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Call this once when the app loads (e.g., in App.vue or main.ts) to
|
* Call this once when the app loads (e.g., in AuthView.vue) to
|
||||||
* handle the result from a Google redirect login on mobile.
|
* handle the result from a Google redirect login on mobile.
|
||||||
* Returns null if there is no pending redirect result.
|
|
||||||
*/
|
*/
|
||||||
export const getGoogleRedirectResult = async (): Promise<{ user: any; token: string } | null> => {
|
export const getGoogleRedirectResult = async (): Promise<{ user: any; token: string } | null> => {
|
||||||
try {
|
try {
|
||||||
const result = await getRedirectResult(auth);
|
const result = await getRedirectResult(auth);
|
||||||
if (result && result.user) {
|
if (result && result.user) {
|
||||||
const token = await result.user.getIdToken();
|
const token = await result.user.getIdToken(true);
|
||||||
|
console.log("DEBUG: Redirect result obtained for:", result.user.email);
|
||||||
return { user: result.user, token };
|
return { user: result.user, token };
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error("DEBUG: Error en getRedirectResult:", error);
|
console.error("DEBUG: Error en getRedirectResult:", error);
|
||||||
return null;
|
// Throw the error so the UI can catch it and show a message
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@ -11,15 +11,17 @@ const isLogin = ref(true)
|
|||||||
const toggleAuth = () => { isLogin.value = !isLogin.value }
|
const toggleAuth = () => { isLogin.value = !isLogin.value }
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
|
const redirectErrorMessage = ref('')
|
||||||
|
|
||||||
// Handle redirect result from Google Sign-In on mobile
|
// Handle redirect result from Google Sign-In on mobile
|
||||||
// (signInWithRedirect reloads the page; we catch the result here on load)
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
try {
|
try {
|
||||||
const result = await getGoogleRedirectResult()
|
const result = await getGoogleRedirectResult()
|
||||||
if (result) {
|
if (result) {
|
||||||
|
console.log('Procesando resultado de redirección de Google...')
|
||||||
const response = await authService.googleLogin(result.token)
|
const response = await authService.googleLogin(result.token)
|
||||||
authStore.login(response.access_token, response.role, response.full_name)
|
authStore.login(response.access_token, response.role, response.full_name)
|
||||||
|
|
||||||
const role = response.role.toUpperCase()
|
const role = response.role.toUpperCase()
|
||||||
if (role === 'ADMIN') router.push('/admin')
|
if (role === 'ADMIN') router.push('/admin')
|
||||||
else if (role === 'DRIVER') router.push('/driver')
|
else if (role === 'DRIVER') router.push('/driver')
|
||||||
@ -28,6 +30,7 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error('Google redirect result error:', e)
|
console.error('Google redirect result error:', e)
|
||||||
|
redirectErrorMessage.value = `Error al volver de Google: ${e.message || 'Error desconocido'}`
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
@ -70,6 +73,12 @@ onMounted(async () => {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Alerta de error en redirección -->
|
||||||
|
<div v-if="redirectErrorMessage" class="redirect-error">
|
||||||
|
<span class="material-icons">warning</span>
|
||||||
|
{{ redirectErrorMessage }}
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Formularios con transición -->
|
<!-- Formularios con transición -->
|
||||||
<Transition name="auth-slide" mode="out-in">
|
<Transition name="auth-slide" mode="out-in">
|
||||||
<LoginForm v-if="isLogin" @toggle="toggleAuth" />
|
<LoginForm v-if="isLogin" @toggle="toggleAuth" />
|
||||||
@ -180,6 +189,25 @@ onMounted(async () => {
|
|||||||
border-bottom-color: var(--active-color);
|
border-bottom-color: var(--active-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ─── Errores de Redirección ─── */
|
||||||
|
.redirect-error {
|
||||||
|
margin: 1rem;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background: rgba(239, 68, 68, 0.1);
|
||||||
|
border: 1px solid rgba(239, 68, 68, 0.2);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
color: #ef4444;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-weight: 600;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.redirect-error .material-icons {
|
||||||
|
font-size: 1.125rem;
|
||||||
|
}
|
||||||
|
|
||||||
/* ─── Transición entre formularios ─── */
|
/* ─── Transición entre formularios ─── */
|
||||||
.auth-slide-enter-active,
|
.auth-slide-enter-active,
|
||||||
.auth-slide-leave-active {
|
.auth-slide-leave-active {
|
||||||
|
|||||||
Reference in New Issue
Block a user