4
\$\begingroup\$

How should one break this component down to better perform unit test on its behaviors?

Issues:

  • Authentication middleware component makes external request.
  • Must recognize preflight and final flight. (Exceptions)
  • Must verify path.
  • Only want to expose crossOriginRequest.

Please criticize anything you see wrong in logic and implementation!

EDITED: 3-28-16 @ 3:40pm PST

var httpErrors = require('./errors');
var authentication = require('./auth');
// CORS permission for paths.
var HEADERS = {
 "img": [
 "GET"
 ]
};
function _acceptsMethod(requestMethod, requestPath) {
 return HEADERS[requestPath].indexOf(requestMethod) >= 0;
};
function _getMethods(requestPath) {
 return HEADERS[requestPath].join();
};
function _getCorsRequest(req) {
 return {
 preflight: ("OPTIONS" == req.method),
 endpoint: (req.originalUrl.split('/')[2] || null)
 };
}
var crossOriginRequest = function(req, res, next) {
 if (req.headers['origin']) {
 req.cors = false; 
 var cors = _getCorsRequest(req);
 // Access-Control-Allow-Origin needs to be set in preflight and flight.
 res.header('Access-Control-Allow-Origin', req.headers['origin']);
 if (cors.preflight && cors.endpoint) {
 if(!_acceptsMethod(req.headers["access-control-request-method"], cors.endpoint)){
 next(httpErrors.badRequest('Failed endpoint method requirments.'))
 return;
 }
 res.header('Access-Control-Allow-Methods', _getMethods(cors.endpoint));
 res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
 }
 if (!cors.preflight) {
 var auth = req.authentication = authentication.getAuthParameters(req);
 authentication.check(auth.endpoint, auth.auth, auth.cors)
 .then(function(user) {
 user = JSON.parse(user);
 if (user.data.cors) {
 req.cors = true;
 next();
 } else {
 next(httpErrors.forbidden('Access denied with CORS.', {
 error: user.data.cors
 }));
 return;
 }
 }).catch(function deniedAuth(err) {
 next(httpErrors.forbidden('Access denied.', err));
 return;
 }).done();
 } else {
 // Send empty body as to not overwrite "OK".
 res.status(200).send('');
 }
 } else {
 next();
 }
}
module.exports = crossOriginRequest;
asked Mar 25, 2016 at 0:13
\$\endgroup\$

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.