2017-09-26 59 views
0

我正在使用Meteor和React構建一個小應用程序。我沒有使用真棒Meteor帳戶庫來處理用戶身份驗證,因爲我需要使用外部API。流星,反應,身份驗證和授權問題

基本上Meteor的服務器端用作代理與API通信。

我創建了身份驗證,從流星的API:

Meteor.methods({ 
    'user.authentication': function (email, password) { 
    try { 
     const res = request.postSync(authenticate, { 
     method: 'POST', 
     json: true, 
     body: { 
      email, password 
     } 
     }); 

     if (res.response.statusCode === 200) { 
     return res.body; 
     } 

     throw new Meteor.Error(res.response.statusCode, res.response.body.error.message); 
    } catch (err) { 
     throw new Meteor.Error(400, err.message); 
    } 
    } 
}); 

這是工作的罰款......在登錄組件發送和接收數據成功的我想要做的「拯救」用戶會話使用流星會話:

Login.js:

onSubmit(e) { 
    e.preventDefault(); 

    const email = this.refs.email.value.trim(); 
    const password = this.refs.password.value.trim(); 

    Meteor.call('user.authentication', email, password, (error, res) => { 
    if (error) { 
     console.error(error.reason); 
    } else { 
     Session.set({ 
     user_id: res.response.user_id, 
     token: res.response.token 
     }); 
     history.push('/account'); 
    } 
    }); 

}

不幸的是我沒有看到會話值正確保存,所以我無法創建控件以將已驗證或未驗證的用戶重定向到正確的頁面...

我不知道我的方法是否正確.. 。我想知道我做錯了什麼,以及是否有更好的解決方案來處理它。

例如我不喜歡在客戶端保存token和user_id,我想將它保存在服務器端,就像Meteor爲他的用戶集合做的一樣,並且能夠處理我所有的API請求,而無需每次都傳遞令牌。 。

回答

1

不幸的是我沒有看到會話值正確保存,這樣我就可以不 創建控件重定向認證或未認證的用戶 至正確的網頁...

流星會議requires a key-value pair

因此,你可能應該努力:

Session.set("userAuth",{ 
    user_id: res.response.user_id, 
    token: res.response.token 
}); 

Session.set("userId", res.response.user_id); 
Session.set("userToken",res.response.token); 

例如我不喜歡保存令牌和user_id的客戶端,我 想保存像流星一樣的服務器端爲他的用戶 收集,並能夠處理我所有的API請求,而無需每次都通過 令牌...

事實上,流星會在客戶端成功登錄後使用瀏覽器的localStorage存儲用戶令牌。

使用帳戶登錄流星應用程序並檢查您的localStorage ;-)