Firebase Auth登录状态持久性不起作用

时间:2018-06-24 17:27:25

标签: javascript firebase firebase-authentication

在ionic / AngularJS / Cordova IOS应用上。

我正在尝试使用邮件/密码设置持久性登录(后接Firebase documentationhttps://firebase.google.com/docs/auth/web/auth-state-persistence)。但是我无法弄清楚我的代码出了什么问题。我的应用程序从登录页面启动,当用户单击“ Connexion按钮”时,它会触发登录功能。

登录正常,但是当我关闭应用程序(不注销)并重新启动它时,我仍然在登录页面上。登录不是永久性的。

所以我想,一个问题可能是持久性调用的位置不正确...对吗?根据这篇文章:Firebase 3.0 session persistance可能与firebase.auth().onAuthStateChanged(function(user)有关,但是我不知道...

// EMAIL CONNEXION TRIGGERED WHEN CONNEXION BUTTON IS HIT

$scope.loginEmail = function($email, $password){
  
  firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    var alertPopup;
    
    function signInSuccess(response) {
  
				$state.go("menu.VN");
    }

    function signInError(response) {
    
        var errorCode = null;
        errorCode = response.code;
        if ($email === ""){
             alertPopup = $ionicPopup.alert({
                    title: 'Something wrong...',
                    cssClass: 'pop',
                    template: '<div class="center-form">Need an email address...</div>'
                });   
        }
}

return firebase.auth().signInWithEmailAndPassword($email, $password)
  .then(signInSuccess)
  .catch(signInError);

     })
     .catch(function(error) {
    // Handle persistence Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

};
<label>
          <span>Email</span>
          <input type="email" placeholder="" ng-model="data.email">
</label>

<label>
          <span>Password</span>
          <input type="password" placeholder="" ng-model="data.password">
</label>
    
<button ng-click="loginEmail(data.email, data.password )">Connexion</button>

1 个答案:

答案 0 :(得分:2)

要保持状态,您应该使用firebase.auth.Auth.Persistence.LOCAL而不是firebase.auth.Auth.Persistence.SESSION

Cordova iOS应用中的localStorage存在易变问题。 Firebase Auth过去依赖于localStorage,但是最新版本使用更可靠的indexedDB来保留用户状态。如果不可用,它将回退到localStorage。在这种情况下,您可以使用此Microsoft plugin for indexedDB

tldr;迁移到最新版本的Firebase Auth,并在indexedDB不可用时使用Cordova indexedDB插件。