2017-01-10 48 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来存储数据。有任何想法如何解决这个问题? –