Skip to content

Instantly share code, notes, and snippets.

@por
Created November 7, 2013 14:44
Show Gist options
  • Save por/7355716 to your computer and use it in GitHub Desktop.
Save por/7355716 to your computer and use it in GitHub Desktop.
var rendrMw = require('rendr/server/middleware')
, _ = require('underscore')
;
module.exports = function(dataAdapter, method, options) {
return function(req, res, next) {
if (req.path !== options.appPath && req.method !== method.toLowerCase()) return;
res.format({
json: function() {
// pass to apiProxy
// make the `path` look like it would in a normal request to /api/-/users/authorize
var proxyReq = _.clone(req);
proxyReq.path = options.apiPath;
rendrMw.apiProxy(dataAdapter)(proxyReq, res, next);
},
html: function() {
// make request using dataAdapter
// maybe instead of hardcoding path, could reuse i.e. User model.
var spec = {
path: options.apiPath,
method: method
};
dataAdapter.request(req, spec, function(err, response, body) {
if (response.status === 400) {
res.redirect(options.appPath + '?error=' + body.error);
} else {
res.redirect(options.successRedirect);
}
});
}
});
};
};
// usage
var passThruMiddleware = require('./middleware/passThruMiddleware').bind(null, dataAdapter);
app.use(passThruMiddleware('POST', {
appPath: '/login',
apiPath: '/users/authorize',
successRedirect: '/dashboard',
));
var rendrMw = require('rendr/server/middleware')
, dataAdapter = require('./dataAdapter')
, _ = require('underscore')
;
app.post('/login', function(req, res, next) {
res.format({
json: function() {
// pass to apiProxy
// make the `path` look like it would in a normal request to /api/-/users/authorize
var proxyReq = _.clone(req);
proxyReq.path = '/users/authorize';
rendrMw.apiProxy(dataAdapter)(proxyReq, res, next);
},
html: function() {
// make request using dataAdapter
// maybe instead of hardcoding path, could reuse i.e. User model.
var spec = {
path: '/users/authorize',
method: 'post'
};
dataAdapter.request(req, spec, function(err, response, body) {
if (response.status === 400) {
res.redirect('/login?error=' + body.error);
} else {
res.redirect('/dashboard');
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment