2017-05-09 16:23:44 -04:00
|
|
|
var origin = require('./origin');
|
|
|
|
var constants = require('./constants.js');
|
2014-05-08 08:47:51 -04:00
|
|
|
|
|
|
|
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
|
2017-05-09 16:23:44 -04:00
|
|
|
var requestedMethod = req.headers[constants['AC_REQ_METHOD']];
|
2014-05-08 08:47:51 -04:00
|
|
|
if (!requestedMethod) return next();
|
|
|
|
|
|
|
|
// 6.2.4
|
2017-05-09 16:23:44 -04:00
|
|
|
var requestedHeaders = req.headers[constants['AC_REQ_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'];
|
2017-05-09 16:23:44 -04:00
|
|
|
var allowedHeaders = constants['ALLOW_HEADERS']
|
|
|
|
.concat(options.allowHeaders);
|
2014-05-08 08:47:51 -04:00
|
|
|
|
|
|
|
res.once('header', function() {
|
|
|
|
// 6.2.7
|
2017-05-09 16:23:44 -04:00
|
|
|
res.header(constants['AC_ALLOW_ORIGIN'], originHeader);
|
|
|
|
res.header(constants['AC_ALLOW_CREDS'], true);
|
2014-05-08 08:47:51 -04:00
|
|
|
|
2014-10-10 03:14:36 -04:00
|
|
|
// 6.2.8
|
|
|
|
if (options.preflightMaxAge) {
|
2017-05-09 16:23:44 -04:00
|
|
|
res.header(constants['AC_MAX_AGE'], options.preflightMaxAge);
|
2014-10-10 03:14:36 -04:00
|
|
|
}
|
|
|
|
|
2014-05-08 08:47:51 -04:00
|
|
|
// 6.2.9
|
2017-05-09 16:23:44 -04:00
|
|
|
res.header(constants['AC_ALLOW_METHODS'], allowedMethods.join(', '));
|
2014-05-08 08:47:51 -04:00
|
|
|
|
|
|
|
// 6.2.10
|
2017-05-09 16:23:44 -04:00
|
|
|
res.header(constants['AC_ALLOW_HEADERS'], allowedHeaders.join(', '));
|
2014-05-08 08:47:51 -04:00
|
|
|
|
|
|
|
});
|
|
|
|
|
2017-05-09 16:23:44 -04:00
|
|
|
res.send(constants['HTTP_NO_CONTENT']);
|
2014-05-08 08:47:51 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
};
|