Код: Выделить всё
submitRating[*] на стороне клиента: onauthstatechanged и auth.currentuser оба подтверждают, что пользователь входит.
Код: Выделить всё
getIdToken[*] на стороне сервера: Облачная функция получает запрос, но контекст. Auth null , которая запускает мою ошибку проверки. Код < /h2>
- Все мои услуги инициализированы из одного и того же приложения < /code> экземпляра. < /Li>
< /ol>) Я подтвердил, что auth.currentuser действителен до того, как эта функция будет вызвана.Код: Выделить всё
import { initializeApp } from "firebase/app"; import { initializeAuth, getReactNativePersistence } from "firebase/auth"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { getFirestore } from "firebase/firestore"; import { getStorage } from "firebase/storage"; import { getFunctions } from "firebase/functions"; const firebaseConfig = { apiKey: "XXX", authDomain: "XXX.firebaseapp.com", projectId: "XXX", // ... }; const app = initializeApp(firebaseConfig); export const auth = initializeAuth(app, { persistence: getReactNativePersistence(AsyncStorage), }); export const db = getFirestore(app); export const storage = getStorage(app); export const functions = getFunctions(app, "us-central1"); < /code> Вызов на стороне клиента (VoteScreen.js)Код: Выделить всё
import { httpsCallable } from "firebase/functions"; import { auth, functions } from "../firebaseConfig"; const handleVote = async () => { setIsSubmitting(true); const currentPhoto = votablePhotos[currentPhotoIndex]; try { console.log("Utilisateur actuel:", auth.currentUser.uid); const token = await auth.currentUser.getIdToken(); console.log("Token JWT récupéré:", token ? "Oui" : "Non"); const submitRating = httpsCallable(functions, 'submitRating'); const result = await submitRating({ photoId: currentPhoto.id, challengeId: currentPhoto.challengeId, themeRating: 5, qualityRating: 5, }); console.log("Succès:", result.data.message); goToNextPhoto(); } catch (error) { console.error("Erreur d'appel de la fonction:", error); // C'est ici que l'erreur s'affiche } finally { setIsSubmitting(false); } }; < /code> Cloud Function Code (functions/index.js
Код: Выделить всё
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.submitRating = functions.https.onCall(async (data, context) => {
functions.logger.log("Appel reçu. UID de l'authentification :", context.auth ? context.auth.uid : "Non authentifié");
if (!context.auth) {
// Cette erreur est systématiquement déclenchée
throw new functions.https.HttpsError(
"unauthenticated",
"Vous devez être connecté pour noter une photo."
);
}
// ... reste de la logique de la fonction ...
return { success: true, message: "Notation enregistrée !" };
});
Что я получаю (журналы)
Консоль приложения на стороне клиента:Код: Выделить всё
LOG Current user UID: iowfvS7nkNfPrTc9OOGVKumUSr42
LOG JWT Token successfully retrieved: Yes
ERROR Error calling function: [FirebaseError: You must be logged in to rate a photo.]
Код: Выделить всё
Call received. Auth UID: Unauthenticated
То, что я уже пробовал
Я прошел длинный процесс отладки и могу подтвердить, что проблема не связана с:[*] План биллинга : проект находится на (pay- as- go-go. />
[*]
[*]
[*]
[*] Функциональная область : Регион функции (
Код: Выделить всё
us-central1[*]
[*]
Код: Выделить всё
npm cache cleanЗаранее спасибо за вашу помощь!
Подробнее здесь: https://stackoverflow.com/questions/797 ... lient-side
Мобильная версия