middleware/token: store the token in current ctx

This commit is contained in:
Miroslav Bajtoš 2014-11-10 18:37:35 +01:00
parent 8f5aea3e3b
commit 038c6a454e
2 changed files with 32 additions and 0 deletions

View File

@ -52,6 +52,8 @@ function token(options) {
if (req.accessToken !== undefined) return next();
TokenModel.findForRequest(req, options, function(err, token) {
req.accessToken = token || null;
var ctx = loopback.getCurrentContext();
if (ctx) ctx.set('accessToken', token);
next(err);
});
};

View File

@ -143,6 +143,36 @@ describe('app.enableAuth()', function() {
.end(done);
});
it('stores token in the context', function(done) {
var TestModel = loopback.createModel('TestModel', { base: 'Model' });
TestModel.getToken = function(cb) {
cb(null, loopback.getCurrentContext().get('accessToken') || null);
};
TestModel.remoteMethod('getToken', {
returns: { arg: 'token', type: 'object' },
http: { verb: 'GET', path: '/token' }
});
var app = loopback();
app.model(TestModel, { dataSource: null });
app.enableAuth();
app.use(loopback.context());
app.use(loopback.token({ model: Token }));
app.use(loopback.rest());
var token = this.token;
request(app)
.get('/TestModels/token?_format=json')
.set('authorization', token.id)
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
if (err) return done(err);
expect(res.body.token.id).to.eql(token.id);
done();
});
});
});
function createTestingToken(done) {