2013-08-17 45 views

回答

7

未來在同一頁面內調用Firebase將使用相同的身份驗證。來自文檔:

對任何引用進行身份驗證都會將該客戶端認證爲整個Firebase,如果Firebase的互聯網連接丟失,Firebase將再次無縫處理認證,因此您只需在應用中執行一次操作即可。要更改客戶端的憑據(例如,當用戶登錄到其他帳戶時),只需使用新令牌重新進行身份驗證即可。

var ref = new Firebase(URL); 

ref.on('value', ...) // not authenticated 

ref.auth(TOKEN, function(error) { 
    if(!error) { 
     ref.on('value', ...); //authenticated 

     ref.child('...').on('value', ...); //also authenticated 

     new Firebase(URL); // also authenticated if I'm using the same URL 
    } 
}); 

ref.on('value', ...); // probably not authenticated (async call to auth probably not completed) 

如果你想要這個令牌生存頁面重新加載,那麼你需要將其存儲在某種方式使客戶可以在新的頁面上調用firebaseRef.auth(...)。

var ref = new Firebase(URL); 

// fetch a token stored in localStorage on a previous page load 
var token = localStorage.getItem('token'); 
if(!token || !tokenHasTimeLeft(token)) { 
    token = fetchTokenFromServer(); /* some API call to your custom auth server */- 
} 
login(token); 

function login(token) { 
    ref.auth(token, function(error) { 
     /** handle errors */ 
     localStorage.setItem('token', token); // store for future page loads 
    }); 
} 

// this method uses Base64.decode by Fred Palmer 
// https://code.google.com/p/javascriptbase64/ 
// it checks to see if the token stored has more 
// than 12 hours left before it expires 
function tokenHasTimeLeft(tok) { 
     try { 
     var body = JSON.parse(Base64.decode(tok.split('.')[1])); 
     var exp = body.exp? moment.unix(body.exp) : moment.unix(body.iat).add('hours', 24); 
     DEVMODE && console.log('parsed token', body); 
     return exp.diff(moment(), 'hours') > 12; 
     } 
     catch(e) { 
     console.warn(e); 
     return false; 
     } 
    }