簡體   English   中英

Flutter Getx:谷歌登錄和 map 數據到 firebase 自動讓我以同一用戶身份登錄?

[英]Flutter Getx: google signin and map data to firebase automatically logs me back in as same user?

我正在嘗試使用 google 登錄並將數據映射到 firebase 用戶。 我正在使用getX。 到目前為止,這有效但是,如果我注銷然后嘗試重新登錄,它會自動將我重新登錄為同一用戶。 如果需要,我將發送我的登錄頁面和注銷按鈕所在的頁面的代碼,但我懷疑這可能與我在這里包含的 AuthController 有關

class AuthController extends GetxController {
  static AuthController instance = Get.find();
  GoogleSignIn googleSignIn = GoogleSignIn();
  Rxn<User> firebaseUser = Rxn<User>();
  Rxn<UserModel> firestoreUser = Rxn<UserModel>();
  final RxBool admin = false.obs;
  String usersCollection = "users";

  @override
  void onReady() async {
    //run every time auth state changes
    ever(firebaseUser, handleAuthChanged);
    firebaseUser.bindStream(user);
    super.onReady();
  }

  handleAuthChanged(firebaseUser) async {
    //get user data from firestore
    if (firebaseUser?.uid != null) {
      firestoreUser.bindStream(streamFirestoreUser());
      print("You are logged in as ${firebaseUser.email}");
      await isAdmin();
    }
    //this is for new users
    if (firebaseUser == null) {
      print('Send to signin');
      Get.offAll(LoginPage());
    } else {
      Get.offAll(AppSetup());
    }
  }

  // Firebase user one-time fetch
  Future<User> get getUser async => auth.currentUser!;

  // Firebase user a realtime stream
  Stream<User?> get user => auth.authStateChanges();

  //Streams the firestore user from the firestore collection
  Stream<UserModel> streamFirestoreUser() {
    print('streamFirestoreUser()');

    return firebaseFirestore
        .doc('/users/${firebaseUser.value!.uid}')
        .snapshots()
        .map((snapshot) => UserModel.fromSnapshot(snapshot));
  }

  //get the firestore user from the firestore collection
  Future<UserModel> getFirestoreUser() {
    return firebaseFirestore
        .doc('/users/${firebaseUser.value!.uid}')
        .get()
        .then((documentSnapshot) => UserModel.fromSnapshot(documentSnapshot));
  }

  //Method to handle user sign in using email and password

  // User registration using email and password
  googleLogin(BuildContext context) async {
    final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
    if (googleUser != null) {
      final googleAuth = await googleUser.authentication;
      if (googleAuth.accessToken != null && googleAuth.idToken != null) {
        try {
          await auth
              .signInWithCredential(
            GoogleAuthProvider.credential(
                idToken: googleAuth.idToken,
                accessToken: googleAuth.accessToken),
          )
              .then((firebaseUser) async {
            print('uid: ' + firebaseUser.user!.uid.toString());
            print('email: ' + firebaseUser.user!.email.toString());

            //create the new user object from the login modelled data
            UserModel _newUser = UserModel(
              id: firebaseUser.user!.uid,
              email: firebaseUser.user!.email!,
              name: firebaseUser.user!.email!,
              photoURL: firebaseUser.user!.photoURL,
              cart: [],
            );
            //create the user in firestore here with the _addUserToFirestore function
            _updateUserFirestore(_newUser, firebaseUser.user!);
          });
        } on FirebaseAuthException catch (error) {
          Get.snackbar('auth.signUpErrorTitle'.tr, error.message!,
              snackPosition: SnackPosition.BOTTOM,
              duration: Duration(seconds: 10),
              backgroundColor: Get.theme.snackBarTheme.backgroundColor,
              colorText: Get.theme.snackBarTheme.actionTextColor);
        }
      }
    }
  }

  void _updateUserFirestore(UserModel user, User _firebaseUser) {
    firebaseFirestore.doc('/users/${_firebaseUser.uid}').update(user.toJson());
    update();
  }

  updateUserData(Map<String, dynamic> data) {
    logger.i("UPDATED");
    firebaseFirestore
        .collection(usersCollection)
        .doc(firebaseUser.value!.uid)
        .update(data);
  }

  //check if user is an admin user
  isAdmin() async {
    await getUser.then((user) async {
      DocumentSnapshot adminRef =
          await firebaseFirestore.collection('admin').doc(user.uid).get();
      if (adminRef.exists) {
        admin.value = true;
      } else {
        admin.value = false;
      }
      update();
    });
  }

  // This is the proper sign out method!
  Future<void> signOut() {
    return auth.signOut();
  }
}

只需將這行代碼添加到您的注銷 function

> await googleSignIn.signOut()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM