Firebase Auth на Expo истекает аутентификация через пару часов - PullRequest
0 голосов
/ 28 июня 2019

У меня есть приложение Expo, использующее AppAuth для аутентификации в Google.После аутентификации пользователя в Google я создаю учетные данные Firebase с токеном Google ID и регистрируюсь в них с помощью Firebase.

Аутентификация и чтение в Firebase работают хорошо, через пару часов, когда пользователь возвращается, пользовательбольше не проходит проверку подлинности с помощью Firebase.

PS: при обновлении или закрытии приложения проверка подлинности пользователя выполняется своевременно.

Постоянство должно быть включено по умолчанию, согласно документации, но я также пытался форсировать его с помощью .setPersistence(firebase.auth.Auth.Persistence.LOCAL), но безуспешно.

Вот мой код:

  onSignIn = googleUser => {
    // We need to register an Observer on Firebase Auth to make sure auth is initialized.
    var unsubscribe = firebase.auth().onAuthStateChanged(
      function(firebaseUser) {
        unsubscribe();

        firebase
          .auth()
          .setPersistence(firebase.auth.Auth.Persistence.LOCAL)
          .then(() => {
            // Check if we are already signed-in Firebase with the correct user.
            if (!this.isUserEqual(googleUser, firebaseUser)) {
              // Build Firebase credential with the Google ID token.
              var credential = firebase.auth.GoogleAuthProvider.credential(
                googleUser.idToken,
                googleUser.accessToken
              );
              // Sign in with credential from the Google user.
              firebase
                .auth()
                .signInWithCredential(credential)
                .then(function(result) {
                  if (result.additionalUserInfo.isNewUser) {
                    firebase
                      .firestore()
                      .collection("users")
                      .doc(result.user.email)
                      .set({
                        email: result.user.email,
                        profile_picture:
                          result.additionalUserInfo.profile.picture,
                        first_name:
                          result.additionalUserInfo.profile.given_name,
                        last_name:
                          result.additionalUserInfo.profile.family_name,
                        full_name: result.additionalUserInfo.profile.name,
                        locale: result.additionalUserInfo.profile.locale,
                        provider_id: result.additionalUserInfo.providerId,
                        created_at: Date.now()
                      })
                      .then(function(snapshot) {});
                  } else {
                    firebase
                      .firestore()
                      .collection("users")
                      .doc(result.user.email)
                      .update({
                        last_logged_in: Date.now()
                      });
                  }
                })
                .catch(function(error) {
                  console.log(error);
                  // Handle Errors here.
                  var errorCode = error.code;
                  var errorMessage = error.message;
                  // The email of the user's account used.
                  var email = error.email;
                  // The firebase.auth.AuthCredential type that was used.
                  var credential = error.credential;
                });
          } else {
              console.log("User already signed-in Firebase.");
            }
          });
      }.bind(this)
    );
  };

signInAsync = async () => {
    const authState = await AppAuth.authAsync(config);
    await this.cacheAuthAsync(authState);
    this.onSignIn(authState);
    return authState;
  };

Я ожидаю, что сеанс и аутентификация будут открыты иобновляться автоматически.

...