2017-01-10 46 views
0

因此,我遵循YouTube授權使用會話令牌的教程。主會話代碼如下。Ember Js中的自定義會話。如何設置/訪問會話信息

//app/services/session.js 
import Ember from 'ember'; 

export default Ember.Service.extend({ 
    token: null, 
    authenticate(log, pass) { 
     return Ember.$.ajax({ 
      method: 'POST', 
      url: '/token', 
      data: {username: log, password: pass} 

     }).then((info)=>{ 
      this.set('token',info.access_token); 
     }); 
    } 
}); 

服務器設置在這裏。

//server/index.js 

const bodyParser = require('body-parser'); 

module.exports = function(app) { 
    app.use(bodyParser.urlencoded({ extended: true})); 

    app.post('/token', function(req, res){ 
     console.log(res); 

     if(req.body.username === 'erik' && 
      req.body.password === 'password') { 
       res.send({ access_token: 'secretcode'}); 
      } else { 
       res.status(400).send({ error: 'invalid_grant'}); 
      } 


    }); 

    app.get('/api/students', function(req, res) { 

     if(req.headers.authorization !== 'Bearer secretcode'){ 
      return res.status(401).send('Unauthorized'); 
     } 

     return res.status(200).send({ 
      students: [ 
       { id: 1, name: 'Erik', age: 23}, 
       { id: 2, name: 'Bob', age: 52} 
      ] 
     }); 



    }); 
}; 

那麼如何在會話令牌上設置多個信息。像user_id?所以我給訪問一個頁面只有當會話包含user_id或者只是用它的控制器像

click_if_authenticated(){ //use session.user_id here} 

回答

1

我建議您授權用戶ember-simple-auth庫。如果爲零丁,它可以讓您檢查會話的狀態,並顯示您需要的內容。此外,可以定義需要認證用戶的路由,以及不需要認證的用戶等。我認爲這比您嘗試創建的路由更容易。

+0

該任務是與pouchdb一起實現它。在ember-simple-auth的情況下,我在什麼時候與pouchdb交互?在指南中,它使用component-componentjs-service-mock_server來存儲數據。有任何想法如何解決這個問題? –