spacedeck-open/middlewares/space_helpers.js

119 lines
2.9 KiB
JavaScript
Raw Normal View History

2017-04-07 01:29:05 +02:00
'use strict';
const db = require('../models/db');
2017-04-07 01:29:05 +02:00
var config = require('config');
module.exports = (req, res, next) => {
let spaceId = req.params.id;
let finalizeReq = (space, role) => {
if (role === "none") {
res.status(403).json({
"error": "access denied"
});
} else {
req['space'] = space;
req['spaceRole'] = role;
res.header("x-spacedeck-space-role", req['spaceRole']);
next();
}
};
var finalizeAnonymousLogin = function(space, spaceAuth) {
var role = "none";
if (spaceAuth && (spaceAuth === space.edit_hash)) {
role = "editor";
} else {
if (space.access_mode == "public") {
role = "viewer";
} else {
role = "none";
}
}
if (req.user) {
db.getUserRoleInSpace(space, req.user, function(newRole) {
2017-04-07 01:29:05 +02:00
if (newRole == "admin" && (role == "editor" || role == "viewer")) {
finalizeReq(space, newRole);
} else if (newRole == "editor" && (role == "viewer")) {
finalizeReq(space, newRole);
} else {
finalizeReq(space, role);
}
});
} else {
finalizeReq(space, role);
}
};
var userMapping = {
'_id': 1,
'nickname': 1,
'email': 1
};
db.Space.findOne({where: {
2017-04-07 01:29:05 +02:00
"_id": spaceId
}}).then(function(space) {
2017-04-07 01:29:05 +02:00
//.populate("creator", userMapping)
//if (err) {
// res.status(400).json(err);
//} else {
2017-04-07 01:29:05 +02:00
if (space) {
if (space.access_mode == "public") {
if (space.password) {
if (req.spacePassword) {
if (req.spacePassword === space.password) {
finalizeAnonymousLogin(space, req["spaceAuth"]);
2017-04-07 01:29:05 +02:00
} else {
res.status(403).json({
"error": "password_wrong"
2017-04-07 01:29:05 +02:00
});
}
} else {
res.status(401).json({
"error": "password_required"
});
2017-04-07 01:29:05 +02:00
}
} else {
finalizeAnonymousLogin(space, req["spaceAuth"]);
}
2017-04-07 01:29:05 +02:00
} else {
// space is private
// special permission for screenshot/pdf export from backend
if (req.query['api_token'] && req.query['api_token'] == config.get('phantom_api_secret')) {
finalizeReq(space, "viewer");
return;
}
if (req.user) {
db.getUserRoleInSpace(space, req.user, function(role) {
if (role == "none") {
2017-04-07 01:29:05 +02:00
finalizeAnonymousLogin(space, req["spaceAuth"]);
} else {
finalizeReq(space, role);
2017-04-07 01:29:05 +02:00
}
});
} else {
if (req.spaceAuth && space.edit_hash) {
finalizeAnonymousLogin(space, req["spaceAuth"]);
} else {
res.status(403).json({
"error": "auth_required"
});
2017-04-07 01:29:05 +02:00
}
}
}
} else {
res.status(404).json({
"error": "space_not_found"
});
2017-04-07 01:29:05 +02:00
}
});
}