Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to Express 4 #3235

Closed
wants to merge 13 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions lib/hooks/blueprints/actionUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var actionUtil = {
populateRequest: function(query, req) {
var DEFAULT_POPULATE_LIMIT = req._sails.config.blueprints.defaultLimit || 30;
var _options = req.options;
var aliasFilter = req.param('populate');
var aliasFilter = req.params['populate'] || req.query.populate;
var shouldPopulate = _options.populate;

// Convert the string representation of the filter list to an Array. We
Expand Down Expand Up @@ -153,7 +153,7 @@ var actionUtil = {
*/
parsePk: function ( req ) {

var pk = req.options.id || (req.options.where && req.options.where.id) || req.param('id');
var pk = req.options.id || (req.options.where && req.options.where.id) || req.params['id'] || (req.body && req.body.id);

// TODO: make this smarter...
// (e.g. look for actual primary key of model and look for it
Expand Down Expand Up @@ -314,7 +314,7 @@ var actionUtil = {
* @param {Request} req
*/
parseSort: function (req) {
var sort = req.param('sort') || req.options.sort;
var sort = req.params['sort'] || req.options.sort || req.query.sort;
if (typeof sort == 'undefined') {return undefined;}
if (typeof sort == 'string') {
try {
Expand All @@ -329,7 +329,7 @@ var actionUtil = {
*/
parseLimit: function (req) {
var DEFAULT_LIMIT = req._sails.config.blueprints.defaultLimit || 30;
var limit = req.param('limit') || (typeof req.options.limit !== 'undefined' ? req.options.limit : DEFAULT_LIMIT);
var limit = req.params['limit'] || req.query.limit || (typeof req.options.limit !== 'undefined' ? req.options.limit : DEFAULT_LIMIT);
if (limit) { limit = +limit; }
return limit;
},
Expand All @@ -340,7 +340,7 @@ var actionUtil = {
*/
parseSkip: function (req) {
var DEFAULT_SKIP = 0;
var skip = req.param('skip') || (typeof req.options.skip !== 'undefined' ? req.options.skip : DEFAULT_SKIP);
var skip = req.params['skip'] || req.query.skip || (typeof req.options.skip !== 'undefined' ? req.options.skip : DEFAULT_SKIP);
if (skip) { skip = +skip; }
return skip;
}
Expand Down
116 changes: 58 additions & 58 deletions lib/hooks/controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,97 +6,97 @@ var util = require('sails-util');
*/
module.exports = function(sails) {

var onRoute = require('./onRoute')(sails);
var onRoute = require('./onRoute')(sails);

return {
return {

defaults: {},
defaults: {},

// Don't allow sails to lift until ready is explicitly set below
ready: false,
// Don't allow sails to lift until ready is explicitly set below
ready: false,

configure: function () {
sails.controllers = { };
},

/**
* Initialize is fired first thing when the hook is loaded
*
* @api public
*/
initialize: function(cb) {
/**
* Initialize is fired first thing when the hook is loaded
*
* @api public
*/
initialize: function(cb) {

// Register route syntax for binding controllers.
sails.on('route:typeUnknown', onRoute);
// Register route syntax for binding controllers.
sails.on('route:typeUnknown', onRoute);

// Load controllers from app and register their actions as middleware.
this.loadAndRegisterControllers(cb);
},
// Load controllers from app and register their actions as middleware.
this.loadAndRegisterControllers(cb);
},

explicitActions: {},

/**
* Wipe everything and (re)load middleware from controllers. Merge any
/**
* Wipe everything and (re)load middleware from controllers. Merge any
* controllers already defined in the sails.controllers namespace.
*
* @api private
*/
loadAndRegisterControllers: function(cb) {
var self = this;
*
* @api private
*/
loadAndRegisterControllers: function(cb) {
var self = this;

// Remove all controllers from middleware hash,
// but retain the reference between this and sails.middleware.controllers
_.each(_.keys(self.middleware), function(key) {
delete self.middleware[key];
});

// Load app controllers
sails.modules.loadControllers(function modulesLoaded (err, modules) {
// Load app controllers
sails.modules.loadControllers(function modulesLoaded (err, modules) {

if (err) return cb(err);
if (err) return cb(err);

sails.controllers = _.merge(sails.controllers, modules);
sails.controllers = _.merge(sails.controllers, modules);

// Register controllers
_.each(sails.controllers, function(controller, controllerId) {
// Register controllers
_.each(sails.controllers, function(controller, controllerId) {

// Override whatever was here before
if ( !util.isDictionary(self.middleware[controllerId]) ) {
self.middleware[controllerId] = {};
}
// Override whatever was here before
if ( !util.isDictionary(self.middleware[controllerId]) ) {
self.middleware[controllerId] = {};
}

// Register this controller's actions
_.each(controller, function(action, actionId) {
// Register this controller's actions
_.each(controller, function(action, actionId) {

// action ids are case insensitive
actionId = actionId.toLowerCase();
// action ids are case insensitive
actionId = actionId.toLowerCase();

// If the action is set to `false`, explicitly disable it
if (action === false) {
delete self.middleware[controllerId][actionId];
return;
}
// If the action is set to `false`, explicitly disable it
if (action === false) {
delete self.middleware[controllerId][actionId];
return;
}

// Ignore non-actions (special properties)
//
// TODO:
// Some of these properties are injected by `moduleloader`
// They should be hidden in the prototype or omitted instead.
if (_.isString(action) || _.isBoolean(action)) {
return;
}
// Ignore non-actions (special properties)
//
// TODO:
// Some of these properties are injected by `moduleloader`
// They should be hidden in the prototype or omitted instead.
if (_.isString(action) || _.isBoolean(action)) {
return;
}

// Otherwise mix it in (this will override CRUD blueprints from above)
// Otherwise mix it in (this will override CRUD blueprints from above)
action._middlewareType = 'ACTION: '+controllerId+'/'+actionId;
self.middleware[controllerId][actionId] = action;
self.middleware[controllerId][actionId] = action;
self.explicitActions[controllerId] = self.explicitActions[controllerId] || {};
self.explicitActions[controllerId][actionId] = true;
});
});

});
});

return cb();
});
}
};
return cb();
});
}
};
};
1 change: 1 addition & 0 deletions lib/hooks/cors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ module.exports = function(sails) {
// If we have an origin header...
if (req.headers && req.headers.origin) {

if(!routeCorsConfig) routeCorsConfig = {};
// Get the allowed origins
var origins = (routeCorsConfig.origin || sails.config.cors.origin).split(',');

Expand Down
49 changes: 20 additions & 29 deletions lib/hooks/csrf/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,6 @@ module.exports = function(sails) {

initialize: function(cb) {

// Quick trim function--could move this into sails.util at some point
function trim (str) {return str.trim();}

// Add res.view() method to compatible middleware
sails.on('router:before', function () {

Expand All @@ -77,36 +74,12 @@ module.exports = function(sails) {
var allowCrossOriginCSRF = sails.config.csrf.origin.split(',').map(trim).indexOf(req.headers.origin) > -1;

if (sails.config.csrf.protectionEnabled) {
var connect = require('connect');

try {
return connect.csrf()(req, res, function() {
if (util.isSameOrigin(req) || allowCrossOriginCSRF) {
res.locals._csrf = req.csrfToken();
} else {
res.locals._csrf = null;
}

next();
});
} catch(err) {
// Only attempt to handle invalid csrf tokens
if (err.message != 'invalid csrf token') throw err;

var isRouteDisabled = sails.config.csrf.routesDisabled.split(',').map(trim).indexOf(req.path) > -1;

if (isRouteDisabled) {
if (util.isSameOrigin(req) || allowCrossOriginCSRF) {
res.locals._csrf = req.csrfToken();
return next();
} else {
// Return an Access-Control-Allow-Origin header in case this is a xdomain request
if (req.headers.origin) {
res.set('Access-Control-Allow-Origin', req.headers.origin);
res.set('Access-Control-Allow-Credentials', true);
}
return res.forbidden("CSRF mismatch");
}
}
}

// Always ok
res.locals._csrf = null;
Expand All @@ -127,10 +100,28 @@ module.exports = function(sails) {

cb();

},

invalidToken: function(err, req, res, next){

var isRouteDisabled = sails.config.csrf.routesDisabled.split(',').map(trim).indexOf(req.path) > -1;

if (isRouteDisabled) {
return next();
} else {
// Return an Access-Control-Allow-Origin header in case this is a xdomain request
if (req.headers.origin) {
res.set('Access-Control-Allow-Origin', req.headers.origin);
res.set('Access-Control-Allow-Credentials', true);
}
return res.status(403).send("CSRF mismatch");
}
}

};

// Quick trim function--could move this into sails.util at some point
function trim (str) {return str.trim();}

function csrfToken (req, res, next) {
// Allow this endpoint to be disabled by setting:
Expand Down
Binary file added lib/hooks/http/assets/favicon.ico
Binary file not shown.
12 changes: 5 additions & 7 deletions lib/hooks/http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,13 @@ module.exports = function(sails) {
'session',
'bodyParser',
'handleBodyParserError',
'csrf',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'router',
'www',
'favicon',
'404',
'500'
'favicon'
],

// Default middleware definitions are injected
Expand Down Expand Up @@ -109,11 +107,11 @@ module.exports = function(sails) {
// Cookie parser middleware to use
// (or false to disable)
//
// Defaults to `express.cookieParser`
// Defaults to `cookie-parser`
//
// Example override:
// cookieParser: (function cookieParser (req, res, next) {})(),
cookieParser: express.cookieParser,
cookieParser: require('cookie-parser'),



Expand Down Expand Up @@ -165,7 +163,7 @@ module.exports = function(sails) {
sails.config.paths.public = path.resolve(sails.config.appPath, sails.config.paths.public);

// Merge in legacy `sails.config.express` object for backwards-compat.
sails.util.defaultsDeep(sails.config.http, sails.config.express||{});
sails.util.defaultsDeep(sails.config.http, sails.config.express || {});

// If no custom middleware order is specified, make sure the default one is used.
// This lets you override default middleware without having to explicitly include the
Expand Down
29 changes: 20 additions & 9 deletions lib/hooks/http/initialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,32 @@ module.exports = function(sails) {

route = _.cloneDeep(route);

// TODO: Add support for error domains..?

app[route.verb || 'all'](route.path, route.target);
});

// When Sails unbinds routes, remove them from the internal Express router
sails.on('router:unbind', function(route) {
var newRoutes = [];
_.each(app.routes[route.method], function(expressRoute) {
if (expressRoute.path != route.path) {
newRoutes.push(expressRoute);
}
});
app.routes[route.method] = newRoutes;
var newRoutes = [];
_.each(app._router.stack, function(expressRoute) {
if(!_.isObject(expressRoute.route)) return newRoutes.push(expressRoute);
if (expressRoute.route.path !== route.path || !expressRoute.route.methods[route.verb]) {
newRoutes.push(expressRoute);
}
});
app._router.stack = newRoutes;
});

// 404 and 500 middleware should be attached at the very end
sails.once('ready', function loadDefault404And500Errors(){
app.use(function handleUnmatchedRequest(req, res, next) {
// Explicitly ignore error arg to avoid inadvertently
// turning this into an error handler
sails.emit('router:request:404', req, res);
});

app.use(function handleError(err, req, res, next) {
sails.emit('router:request:500', err, req, res);
});
});

// When Sails is ready, start the express server
Expand Down
Loading