lundi 9 janvier 2017

Custom sessions in Ember Js. How to set/access session information

So I followed a youtube tutorial on how authorize using session tokens. The main session code was the following.

//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 set over here.

//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}
            ]
        });



    });
};

So how do I set multiple info on the session token. Like the user_id? So I give access to a page only if session contains a user_id or just using it in controller like

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




Aucun commentaire:

Enregistrer un commentaire