2014-05-08 08:47:51 -04:00
|
|
|
var restify = require('restify');
|
|
|
|
var origin = require('./origin');
|
|
|
|
|
2014-05-08 09:00:19 -04:00
|
|
|
//
|
|
|
|
// For now we use the "default headers" from restify.CORS
|
|
|
|
// Maybe this should just be a global setting on this module
|
|
|
|
// (ie. list of extra Access-Control-Expose-Headers, regardless of what the middleware config says)
|
|
|
|
//
|
|
|
|
|
|
|
|
//
|
|
|
|
// TODO:
|
|
|
|
// Handle the spec better around "simple methods" and "simple headers".
|
|
|
|
//
|
|
|
|
|
2014-05-08 08:47:51 -04:00
|
|
|
var DEFAULT_ALLOW_HEADERS = restify.CORS.ALLOW_HEADERS;
|
|
|
|
var HTTP_NO_CONTENT = 204;
|
|
|
|
|
|
|
|
exports.handler = function(options) {
|
|
|
|
|
|
|
|
return function(req, res, next) {
|
|
|
|
if (req.method !== 'OPTIONS') return next();
|
|
|
|
|
|
|
|
// 6.2.1 and 6.2.2
|
2016-10-05 09:09:39 -04:00
|
|
|
var originHeader = req.headers['origin'];
|
2014-05-08 08:47:51 -04:00
|
|
|
if (origin.match(originHeader, options.origins) === false) return next();
|
|
|
|
|
|
|
|
// 6.2.3
|
2016-10-05 09:09:39 -04:00
|
|
|
var requestedMethod = req.headers['access-control-request-method'];
|
2014-05-08 08:47:51 -04:00
|
|
|
if (!requestedMethod) return next();
|
|
|
|
|
|
|
|
// 6.2.4
|
2016-10-05 09:09:39 -04:00
|
|
|
var requestedHeaders = req.headers['access-control-request-headers'];
|
2014-05-08 08:47:51 -04:00
|
|
|
requestedHeaders = requestedHeaders ? requestedHeaders.split(', ') : [];
|
|
|
|
|
2016-10-05 09:09:39 -04:00
|
|
|
var allowedMethods = [requestedMethod, 'OPTIONS'];
|
|
|
|
var allowedHeaders = DEFAULT_ALLOW_HEADERS.concat(['x-requested-with'])
|
2014-05-08 08:47:51 -04:00
|
|
|
.concat(options.allowHeaders);
|
|
|
|
|
|
|
|
res.once('header', function() {
|
|
|
|
|
|
|
|
// 6.2.7
|
|
|
|
res.header('Access-Control-Allow-Origin', originHeader);
|
|
|
|
res.header('Access-Control-Allow-Credentials', true);
|
|
|
|
|
2014-10-10 03:14:36 -04:00
|
|
|
// 6.2.8
|
|
|
|
if (options.preflightMaxAge) {
|
|
|
|
res.header('Access-Control-Max-Age', options.preflightMaxAge);
|
|
|
|
}
|
|
|
|
|
2014-05-08 08:47:51 -04:00
|
|
|
// 6.2.9
|
|
|
|
res.header('Access-Control-Allow-Methods', allowedMethods.join(', '));
|
|
|
|
|
|
|
|
// 6.2.10
|
|
|
|
res.header('Access-Control-Allow-Headers', allowedHeaders.join(', '));
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
res.send(HTTP_NO_CONTENT);
|
|
|
|
};
|
|
|
|
|
|
|
|
};
|