fix: Google Sign-In - Firebase Admin credentials via env var + mobile redirect flow

This commit is contained in:
2026-02-23 19:31:47 -05:00
parent b75c4cc0a7
commit f5fa086356
4 changed files with 96 additions and 15 deletions

View File

@ -1,4 +1,5 @@
import os import os
import json
import shutil import shutil
from uuid import uuid4 from uuid import uuid4
from typing import Annotated, Optional from typing import Annotated, Optional
@ -12,11 +13,26 @@ from app.schemas.user import PassengerCreate, Token, UserResponse, LoginRequest,
import firebase_admin import firebase_admin
from firebase_admin import auth as firebase_auth, credentials from firebase_admin import auth as firebase_auth, credentials
# Initialize Firebase Admin # Initialize Firebase Admin SDK
# Supports two methods:
# 1. FIREBASE_SERVICE_ACCOUNT_JSON env var with the full JSON as a string (recommended for Render/production)
# 2. GOOGLE_APPLICATION_CREDENTIALS env var pointing to a JSON file path (local dev)
try: try:
if not firebase_admin._apps: if not firebase_admin._apps:
# Default initialization (uses GOOGLE_APPLICATION_CREDENTIALS) sa_json = os.environ.get("FIREBASE_SERVICE_ACCOUNT_JSON")
firebase_admin.initialize_app() if sa_json:
# Parse the JSON string directly from environment variable
sa_dict = json.loads(sa_json)
cred = credentials.Certificate(sa_dict)
firebase_admin.initialize_app(cred)
print("DEBUG: Firebase Admin initialized from FIREBASE_SERVICE_ACCOUNT_JSON env var")
elif os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
# Use file path from GOOGLE_APPLICATION_CREDENTIALS
firebase_admin.initialize_app()
print("DEBUG: Firebase Admin initialized from GOOGLE_APPLICATION_CREDENTIALS file")
else:
print("WARNING: No Firebase credentials found. Set FIREBASE_SERVICE_ACCOUNT_JSON or GOOGLE_APPLICATION_CREDENTIALS.")
firebase_admin.initialize_app()
except Exception as e: except Exception as e:
print(f"WARNING: Firebase Admin could not be initialized: {e}") print(f"WARNING: Firebase Admin could not be initialized: {e}")

View File

@ -1,5 +1,11 @@
import { initializeApp } from 'firebase/app'; import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider, signInWithPopup } from 'firebase/auth'; import {
getAuth,
GoogleAuthProvider,
signInWithPopup,
signInWithRedirect,
getRedirectResult
} from 'firebase/auth';
const firebaseConfig = { const firebaseConfig = {
apiKey: "AIzaSyAG8nmGLHYmXGkl018NjW2sMcIiutM4ne0", apiKey: "AIzaSyAG8nmGLHYmXGkl018NjW2sMcIiutM4ne0",
@ -14,17 +20,46 @@ const app = initializeApp(firebaseConfig);
export const auth = getAuth(app); export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider(); export const googleProvider = new GoogleAuthProvider();
export const signInWithGoogle = async () => { // Detect if the user is on a mobile device
try { const isMobile = () => {
return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent);
};
/**
* Signs in with Google.
* - Uses signInWithPopup on desktop (fast, no page reload)
* - Uses signInWithRedirect on mobile (avoids popup blocking on mobile browsers)
*/
export const signInWithGoogle = async (): Promise<{ user: any; token: string }> => {
if (isMobile()) {
// On mobile, redirect flow is more reliable
await signInWithRedirect(auth, googleProvider);
// The page will reload; the result is handled by getGoogleRedirectResult() on app load
// We return a never-resolving promise to keep the UI in loading state
return new Promise(() => { });
} else {
// On desktop, use popup
const result = await signInWithPopup(auth, googleProvider); const result = await signInWithPopup(auth, googleProvider);
// This gives you a Google Access Token. You can use it to access the Google API.
const token = await result.user.getIdToken(); const token = await result.user.getIdToken();
return { return { user: result.user, token };
user: result.user, }
token: token };
};
} catch (error) { /**
console.error("Error signing in with Google", error); * Call this once when the app loads (e.g., in App.vue or main.ts) to
throw error; * 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> => {
try {
const result = await getRedirectResult(auth);
if (result && result.user) {
const token = await result.user.getIdToken();
return { user: result.user, token };
}
return null;
} catch (error) {
console.error("Error getting redirect result:", error);
return null;
} }
}; };

View File

@ -1,10 +1,36 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import LoginForm from '@/components/auth/LoginForm.vue' import LoginForm from '@/components/auth/LoginForm.vue'
import RegisterForm from '@/components/auth/RegisterForm.vue' import RegisterForm from '@/components/auth/RegisterForm.vue'
import { getGoogleRedirectResult } from '@/firebaseConfig'
import { authService } from '@/services/authService'
import { useAuthStore } from '@/stores/auth'
const isLogin = ref(true) const isLogin = ref(true)
const toggleAuth = () => { isLogin.value = !isLogin.value } const toggleAuth = () => { isLogin.value = !isLogin.value }
const router = useRouter()
const authStore = useAuthStore()
// Handle redirect result from Google Sign-In on mobile
// (signInWithRedirect reloads the page; we catch the result here on load)
onMounted(async () => {
try {
const result = await getGoogleRedirectResult()
if (result) {
const response = await authService.googleLogin(result.token)
authStore.login(response.access_token, response.role, response.full_name)
const role = response.role.toUpperCase()
if (role === 'ADMIN') router.push('/admin')
else if (role === 'DRIVER') router.push('/driver')
else if (role === 'PROMOTER') router.push('/promoter')
else router.push('/map')
}
} catch (e) {
// No redirect result pending, or error — ignore silently
console.warn('Google redirect result:', e)
}
})
</script> </script>
<template> <template>

View File

@ -18,6 +18,10 @@ services:
value: "false" value: "false"
- key: PYTHON_VERSION - key: PYTHON_VERSION
value: 3.13.0 value: 3.13.0
# Firebase Admin SDK credentials (JSON string of service account)
# Set this manually in the Render dashboard — do NOT commit the actual value
- key: FIREBASE_SERVICE_ACCOUNT_JSON
sync: false
databases: databases:
- name: sibu-db - name: sibu-db