opt-cc/server/routes/users.js

224 lines
8.2 KiB
JavaScript
Raw Normal View History

2018-03-12 09:26:44 +01:00
'use strict';
2017-05-10 11:04:06 +02:00
// modules
const express = require('express');
const fs = require('fs');
// HTTP status codes by name
const codes = require('./http-codes');
const apiAuthenticationMiddleware = require('../middleware/auth-middleware');
2017-06-08 13:14:53 +02:00
const checkHl = require('../middleware/permission-check').checkHl;
const checkMT = require('../middleware/permission-check').checkMT;
2017-10-10 19:03:52 +02:00
const offsetlimitMiddleware = require('../middleware/limitoffset-middleware-mongo');
2017-10-14 15:26:05 +02:00
const filterHandlerCreator = require('../middleware/filter-handler-mongo');
2017-05-10 11:04:06 +02:00
const routerHandling = require('../middleware/router-handling');
const idValidator = require('../middleware/validators').idValidator;
const resourceLocation = require('../middleware/resource-location').resourceLocation().concat('/signature/');
2017-05-10 11:04:06 +02:00
// Mongoose Model using mongoDB
const UserModel = require('../models/user');
2017-10-14 15:26:05 +02:00
const SquadModel = require('../models/squad');
2017-05-10 11:04:06 +02:00
const AwardingModel = require('../models/awarding');
const users = new express.Router();
2017-05-10 11:04:06 +02:00
2017-10-14 15:26:05 +02:00
users.get('/', filterHandlerCreator(UserModel.schema.paths));
2017-10-10 19:03:52 +02:00
users.get('/', offsetlimitMiddleware);
2017-05-10 11:04:06 +02:00
// routes **********************
users.route('/')
2018-02-26 09:04:27 +01:00
.get((req, res, next) => {
const finishFiltersAndExecute = () => {
// squad / fraction filter setup
if (req.query.fractFilter && req.query.fractFilter !== 'UNASSIGNED' && !req.query.squadId) {
SquadModel.find({'fraction': req.query.fractFilter}, {_id: 1}, (err, squads) => {
dbFilter['squadId'] = {$in: squads.map((squad) => squad.id)};
userQuery();
});
} else {
if (req.query.fractFilter === 'UNASSIGNED') {
dbFilter['squadId'] = {$eq: null};
}
userQuery();
}
};
2018-02-26 09:04:27 +01:00
const userQuery = () => {
UserModel.find(dbFilter, res.locals.filter, res.locals.limitskip)
.populate('squadId')
2018-03-12 09:26:44 +01:00
.collation({locale: 'en', strength: 2}) // case insensitive order
.sort('username')
.exec((err, users) => {
if (err) return next(err);
if (users.length === 0) {
res.locals.items = users;
res.locals.processed = true;
return next();
}
2018-10-05 10:21:50 +02:00
UserModel.countDocuments(dbFilter, (err, totalCount) => {
res.set('x-total-count', totalCount);
res.locals.items = users;
res.locals.processed = true;
return next();
});
});
2018-02-26 09:04:27 +01:00
};
const nameQuery = (!req.query.q) ? '' : req.query.q;
const dbFilter = {username: {'$regex': nameQuery, '$options': 'i'}};
2018-03-12 09:26:44 +01:00
if (req.query.squadId) dbFilter['squadId'] = {'$eq': req.query.squadId};
// decoration filter
const queryDecoId = req.query.decorationId;
if (queryDecoId) {
AwardingModel.find({decorationId: queryDecoId}, (err, awards) => {
const userIds = [...new Set(awards.map((award) => award.userId))];
dbFilter._id = {'$in': userIds};
finishFiltersAndExecute();
2018-03-12 09:26:44 +01:00
});
2018-02-26 09:04:27 +01:00
} else {
finishFiltersAndExecute();
2018-02-26 09:04:27 +01:00
}
})
.post(apiAuthenticationMiddleware, checkHl, (req, res, next) => {
const user = new UserModel(req.body);
// timestamp and default are set automatically by Mongoose Schema Validation
user.save((err) => {
if (err) {
err.status = codes.wrongrequest;
return next(err);
}
res.status(codes.created);
UserModel.populate(user, {path: 'squadId'}, (err, extUser) => {
res.locals.items = extUser;
res.locals.processed = true;
return next();
2018-03-12 09:26:44 +01:00
});
2018-02-26 09:04:27 +01:00
});
})
.all(routerHandling.httpMethodNotAllowed);
2017-05-10 11:04:06 +02:00
users.route('/:id')
2018-02-26 09:04:27 +01:00
.get(idValidator, (req, res, next) => {
UserModel.findById(req.params.id).populate('squadId').exec((err, user) => {
if (err) {
err.status = codes.servererror;
return next(err);
2018-03-12 09:26:44 +01:00
} else if (!user) {
err = new Error('item not found');
2018-02-26 09:04:27 +01:00
err.status = codes.notfound;
return next(err);
}
res.locals.items = user;
res.locals.processed = true;
return next();
});
})
.put(apiAuthenticationMiddleware, checkHl, (req, res, next) => {
// first check that the given element id is the same as the URL id
if (!req.body || req.body._id !== req.params.id) {
// the URL does not fit the given element
let err =
2018-03-29 22:14:04 +02:00
new Error('id of PUT resource and send JSON body are not equal ' + req.params.id + ' ' + req.body._id);
2018-02-26 09:04:27 +01:00
err.status = codes.notfound;
next(err);
return; // prevent node to process this function further after next() has finished.
}
// main difference of PUT and PATCH is that PUT expects all data in request: checked by using the schema
const user = new UserModel(req.body);
UserModel.findById(req.params.id, req.body, {new: true}, (err, item) => {
2018-03-29 22:14:04 +02:00
// with parameter {new: true} the TweetNModel will return the new and changed object
// from the DB and not the old one.
2018-02-26 09:04:27 +01:00
if (err) {
err.status = codes.wrongrequest;
return next(err);
2018-03-12 09:26:44 +01:00
} else if (!item) {
err = new Error('item not found');
2018-02-26 09:04:27 +01:00
err.status = codes.notfound;
return next(err);
} else if (user.__v !== item.__v) {
// checked that version is still accurate
2018-03-12 09:26:44 +01:00
err = new Error('version outdated. Meanwhile update on item happened. Please GET resource again');
2018-02-26 09:04:27 +01:00
err.status = codes.conflict;
return next(err);
}
// now update all fields in DB item with body data in variable video
2018-03-12 09:26:44 +01:00
for (let field in UserModel.schema.paths) {
2018-02-26 09:04:27 +01:00
if ((field !== '_id') && (field !== '__v')) {
// this includes undefined. is important to reset attributes that are missing in req.body
item.set(field, user[field]);
}
}
// update updatedAt and increase version
item.updatedAt = new Date();
item.increment(); // this sets __v++
item.save((err) => {
2018-02-26 09:04:27 +01:00
if (!err) {
res.locals.items = item;
} else {
err.status = codes.wrongrequest;
2018-07-15 15:38:33 +02:00
console.log(err);
2018-02-26 09:04:27 +01:00
err.message += ' in fields: ' + Object.getOwnPropertyNames(err.errors);
}
UserModel.populate(item, {path: 'squadId'}, (err, extUser) => {
res.locals.items = extUser;
res.locals.processed = true;
return next();
2018-03-12 09:26:44 +01:00
});
2018-02-26 09:04:27 +01:00
});
2018-03-12 09:26:44 +01:00
});
2018-02-26 09:04:27 +01:00
})
.delete(apiAuthenticationMiddleware, checkMT, (req, res, next) => {
2018-02-26 09:04:27 +01:00
UserModel.findByIdAndRemove(req.params.id, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
2018-03-12 09:26:44 +01:00
} else if (!item) {
err = new Error('item not found');
2018-02-26 09:04:27 +01:00
err.status = codes.notfound;
}
// deleted all awardings linked to this user
AwardingModel.find({userId: req.params.id}).remove().exec();
// check if signature exists and delete compressed and uncompressed file
const fileMinified = resourceLocation + req.params.id + '.png';
2018-02-26 09:04:27 +01:00
if (fs.existsSync(fileMinified)) {
fs.unlink(fileMinified, (err) => {
});
}
const file = resourceLocation + 'big/' + req.params.id + '.png';
2018-02-26 09:04:27 +01:00
if (fs.existsSync(file)) {
fs.unlink(file, (err) => {
});
}
// we don't set res.locals.items and thus it will send a 204 (no content) at the end. see last handler
// user.use(..)
res.locals.processed = true;
next(err); // this works because err is in normal case undefined and that is the same as no parameter
});
})
.all(
routerHandling.httpMethodNotAllowed
);
2017-05-10 11:04:06 +02:00
// this middleware function can be used, if you like or remove it
// it looks for object(s) in res.locals.items and if they exist, they are send to the client as json
users.use(routerHandling.emptyResponse);
module.exports = users;