loopback/lib/middleware/token.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

2014-01-06 23:52:08 +00:00
/*!
2013-11-13 19:49:08 +00:00
* Module dependencies.
*/
var loopback = require('../loopback');
var RemoteObjects = require('strong-remoting');
2013-12-03 00:37:42 +00:00
var assert = require('assert');
2013-11-13 19:49:08 +00:00
2014-01-06 23:52:08 +00:00
/*!
2013-11-13 19:49:08 +00:00
* Export the middleware.
*/
module.exports = token;
2014-01-06 23:52:08 +00:00
/**
* **Options**
*
* - `cookies` - An `Array` of cookie names
* - `headers` - An `Array` of header names
* - `params` - An `Array` of param names
* - `model` - Specify an AccessToken class to use
*
* Each array is used to add additional keys to find an `accessToken` for a `request`.
*
* The following example illustrates how to check for an `accessToken` in a custom cookie, query string parameter
* and header called `foo-auth`.
*
* ```js
* app.use(loopback.token({
* cookies: ['foo-auth'],
* headers: ['foo-auth', 'X-Foo-Auth'],
* cookies: ['foo-auth', 'foo_auth']
* }));
* ```
*
* **Defaults**
*
* By default the following names will be checked. These names are appended to any optional names. They will always
* be checked, but any names specified will be checked first.
*
* - **access_token**
* - **X-Access-Token**
* - **authorization**
* - **access_token**
*
* **NOTE:** The `loopback.token()` middleware will only check for [signed cookies](http://expressjs.com/api.html#req.signedCookies).
*
* @header loopback.token(options)
*/
2013-11-14 23:27:36 +00:00
function token(options) {
2013-11-13 19:49:08 +00:00
options = options || {};
2013-12-03 01:16:43 +00:00
var TokenModel = options.model || loopback.AccessToken;
2013-11-14 21:01:47 +00:00
assert(TokenModel, 'loopback.token() middleware requires a AccessToken model');
2013-11-13 19:49:08 +00:00
return function (req, res, next) {
2013-11-14 21:01:47 +00:00
TokenModel.findForRequest(req, options, function(err, token) {
if(err) return next(err);
if(token) {
req.accessToken = token;
next();
} else {
return next();
}
});
2013-11-13 19:49:08 +00:00
}
}