У меня следующая проблема. Я реализовал облачную функцию Firebase, которая возвращает профиль пользователя из Firestore. Мои облачные функции требуют, чтобы вы вошли в Firebase, чтобы иметь возможность запрашивать их.
Теперь в моем приложении я реализовал, что на FirebaseAuth.instance.onAuthStateChanged
вызывается облачная функция для получения профиля пользователя. Однако, когда я вхожу в приложение, вызванный вызов возвращает PlatformException с причиной UNAUTHENTICATED, хотя в строке перед этим я проверяю текущего пользователя с помощью FirebaseAuth.instance.currentUser()
и получаю правильный и действительный идентификатор пользователя. В Firebase нет журналов, включающих эту функцию, только для других функций, которые все выполняются успешно и также вызываются на FirebaseAuth.instance.onAuthStateChanged
.
Вот облачная функция, которая в основном очень проста:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
export default functions.https.onCall(async (data, context) => {
console.info(`[api-userProfile] called with userUid=${data.userUid}`);
const user: FirebaseFirestore.QuerySnapshot = await admin
.firestore()
.collection("userProfiles")
.where("userUid", "==", data.userUid)
.get();
if (user.docs.length === 1) {
console.info(
`[api-userProfile] returning user for userUid=${data.userUid}`
);
return user.docs[0].data();
}
console.info(`[api-userProfile] could not find userUid=${data.userUid}`);
return null;
});
И вот как я это называю:
final _disposeBag = CompositeSubscription();
final userProfile = BehaviorSubject<UserProfile>();
final _userProfilesFn =
CloudFunctions.instance.getHttpsCallable(functionName: "api-userProfile");
UserProfileStore() {
_disposeBag.add(FirebaseAuth.instance.onAuthStateChanged
.map((v) => v != null ? v : throw "")
.handleError((v) => userProfile.add(null))
.asyncMap((v) {
print(v.uid); // here the correct uid is printed
return _userProfilesFn.call({"userUid": v.uid});
})
.map((v) => v as Map)
.map((v) => UserProfile.fromJson(v))
.addTo(userProfile)
.listen((_) {}));
}
И выдается сообщение об ошибке (первая строка - идентификатор пользователя, вошедшего в систему):
I/flutter ( 9370): DXrcqtU34Dh8UfZYnsNdxn31hqx2
E/flutter ( 9370): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(functionsError, Cloud function failed with exception., {code: UNAUTHENTICATED, details: null, message: UNAUTHENTICATED})
E/flutter ( 9370): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:569
E/flutter ( 9370): #1 MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:321
E/flutter ( 9370): <asynchronous suspension>
E/flutter ( 9370): #2 MethodChannelCloudFunctions.callCloudFunction
package:cloud_functions_platform_interface/src/method_channel_cloud_functions.dart:43
E/flutter ( 9370): #3 HttpsCallable.call
package:cloud_functions/src/https_callable.dart:33
E/flutter ( 9370): #4 new UserProfileStore.<anonymous closure>