/* jshint node: true */ var passport = require('passport'), _ = require('lodash'), config = require('../../config.json'), User = require('./schemas/User'), Collaborator = require('./schemas/Collaborator'), Project = require('./schemas/Project'); var middleware = { enableCORS: function (req, res, next) { res.header('Access-Control-Allow-Credentials', true); // TODO Check https vs. http res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }, ensureAuthenticated: function (req, res, next) { if (! req.isAuthenticated()) { req.session.returnTo = req.path; return res.redirect('/login'); } next(); }, ensureIsStaff: function (req, res, next) { if (! req.user.isStaff) { return res.redirect('http://' + config.host + '/'); } next(); }, ensureLocals: function (req, res, next) { res.locals.token = req.csrfToken(); res.locals.logged_in = req.isAuthenticated() res.locals.user = req.user || { _id: undefined } res.locals.config = config res.locals.profile = null res.locals.ogImage = "http://okfocus.s3.amazonaws.com/images/vvalls-fb.png" res.locals.ogTitle = "VValls" res.locals.ogUrl = "http://vvalls.com/" res.locals.ogDescription = "3D gallery space, fully customizable" res.locals.ogAuthor = "VValls" res.locals.opt = {} next() }, ensureProject: function (req, res, next) { if (req.params.slug) { Project.findOne({ slug: req.params.slug }, function(err, project){ if (err) { console.error(err) req.project = null } else if (! project) { req.project = null } else { req.project = project } next() }) } else { req.project = null next() } }, ensureIsCollaborator: function(req, res, next) { req.isCollaborator = false req.isOwner = false req.isStaff = true if (! req.user || ! req.project) { next() } else if (String(req.user._id) === String(req.project.user_id)) { req.isOwner = true next() } else { Collaborator.findOne({ user_id: req.user._id, project_id: req.project._id }, function(err, collab) { if (err || ! collab) { next() } else { req.isCollaborator = true next() } }) } }, } module.exports = middleware