2016-02-25 119 views
3

我想知道是否有人使用離子和firebase並允許持久性驗證。當我創建IPA/APK並將應用程序下載到我的設備時,每當我關閉應用程序時,我都必須重新登錄。Ionic Framework和Firebase持久驗證驗證

使用$ authWithPassword登錄時,回調函數包括uid和令牌。如果我使用導入ngStorage作爲依賴項,如何使用uid和令牌來保持auth?

對於登錄,用戶登錄調用登錄功能,該功能鏈接到我的工廠中的Auth.login功能。

login: function(user) { 
     return auth.$authWithPassword({ 
      email: user.email, 
      password: user.password 
     }, function(error, authData) { 
      switch(error.code) { 
       case "INVALID_EMAIL": 
        console.log("Log in with a valid email."); 
        break 
       case "INVALID_PASSWORD": 
        console.log("Password or email is incorrect"); 
        break 
       default: 
        console.log("Enter a valid email and password"); 
      } 
     }) 
     .then(function(authData) { 
      console.log("login: Logged in with uid: ", authData); 
      $localStorage.uid = authData.uid; 
      $localStorage.token = authData.token; 

     }) 
     .catch(function(error) { 
      alert("Error: " + error); 
     }); 

我不知道我將如何堅持用uid和令牌認證。沒有用戶密碼可以做到嗎?

在此先感謝您的幫助。

回答

3

很久以前,我確實找到了答案,但忘記了在這裏更新。希望對於使用離子框架的人使用Firebase身份驗證會很有幫助。

如問題部分所示,只要確保在登錄時保存令牌即可。這應該適用於社交媒體登錄firebase也提供。

當我第一次嘗試作爲第一次開發者時,對我自己來說並不明顯,但每次打開應用程序時都可以使用保存的令牌登錄用戶。

在您的應用程序離子的.RUN()的一部分,注入$本地存儲,$ firebaseAuth和$狀態添加如下內容:

if($localStorage.token) { 
    var token = $localStorage.token; 

    var ref = new Firebase('https://yourfirebaselink.firebaseio.com/'); 

    var auth = $firebaseAuth(ref); 

    auth.$authWithCustomToken(token, function(error, authData) { 
    if (error) { 
     console.log("Authentication Failed!", error); 
    } else { 
     console.log("Authenticated successfully with payload:", authData); 
    } 
    }).then(function(authData) { 
    $state.go('main'); 
    return true; 
    }).catch(function(error) { 
    console.log("Please sign in", error); 
    delete $localStorage.uid; 
    delete $localStorage.token; 
    }); 

} else { 
    $state.go('login'); 
    console.log('not logged in'); 
} 

總之,如果有保存到本地存儲,它使用令牌使用firebases $ authWithCustomToken()登錄。

+0

您不應該使用'localstorage'來保存這種類型的數據[因爲它被清理](http://ionicframework.com/docs/v2/api/platform/storage/LocalStorage/)。它將數據存儲在設備的緩存中,隨時可以在設備需要資源時進行清理。 – peteb