opt-cc/api/routes/users.js

265 lines
7.9 KiB
JavaScript

"use strict";
// modules
const express = require('express');
const fs = require('fs');
const logger = require('debug')('me2u5:users');
// HTTP status codes by name
const codes = require('./http-codes');
const apiAuthenticationMiddleware = require('../middleware/auth-middleware');
const sortCollectionBy = require('../middleware/util').sortCollection;
const routerHandling = require('../middleware/router-handling');
// Mongoose Model using mongoDB
const UserModel = require('../models/user');
const RankModel = require('../models/rank');
const AwardingModel = require('../models/awarding');
const resultSet = {'__v': 0, 'updatedAt': 0, 'timestamp': 0};
const users = express.Router();
// routes **********************
users.route('/')
.get((req, res, next) => {
if (req.query.simple) {
UserModel.find({}, res.locals.filter, res.locals.limitskip, (err, items) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
// if the collection is empty we do not send empty arrays back.
res.locals.items = items;
res.locals.processed = true;
next();
})
}
else {
const nameQuery = req.query.q;
const fractionFilter = req.query.fractFilter;
UserModel.find({}, res.locals.filter, res.locals.limitskip, (err, users) => {
if (err) return next(err);
if (users.length === 0) {
res.locals.items = users;
res.locals.processed = true;
next();
}
let resUsers = [];
let rowsLength = users.length;
users.forEach((user) => {
// filter by name
if (!nameQuery || (nameQuery && user.username.toLowerCase().includes(nameQuery.toLowerCase()))) {
getExtendedUser(user, next, (extUser) => {
// filter by fraction
if (!fractionFilter || (fractionFilter && extUser.squad && extUser.squad.fraction.toLowerCase() === fractionFilter)) {
resUsers.push(extUser);
} else {
rowsLength -= 1;
}
if (resUsers.length === rowsLength) {
resUsers = sortCollectionBy(resUsers, 'username');
res.locals.items = resUsers;
res.locals.processed = true;
return next();
}
});
} else {
rowsLength -= 1;
// no user matching query - return empty []
if (rowsLength === 0) {
res.locals.items = resUsers;
res.locals.processed = true;
next();
}
}
})
})
}
})
.post(apiAuthenticationMiddleware, (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);
res.locals.items = user;
next();
});
})
.all(routerHandling.httpMethodNotAllowed);
users.route('/:id')
.get((req, res, next) => {
UserModel.findById(req.params.id, (err, item) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
else if (!item) {
err = new Error("item not found");
err.status = codes.notfound;
return next(err);
} else if (req.query.simple) {
res.locals.items = item;
next();
}
getExtendedUser(item, next, (extUser) => {
res.locals.items = extUser;
res.locals.processed = true;
return next();
})
});
})
.patch(apiAuthenticationMiddleware, (req, res, next) => {
if (!req.body || (req.body._id && req.body._id !== req.params.id)) {
// little bit different as in PUT. :id does not need to be in data, but if the _id and url id must match
const err = new Error('id of PATCH resource and send JSON body are not equal ' + req.params.id + " " + req.body._id);
err.status = codes.notfound;
next(err);
return; // prevent node to process this function further after next() has finished.
}
// optional task 3: increment version manually as we do not use .save(.)
req.body.updatedAt = new Date();
req.body.$inc = {__v: 1};
// PATCH is easier with mongoose than PUT. You simply update by all data that comes from outside. no need to reset attributes that are missing.
UserModel.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
}
else if (!item) {
err = new Error("item not found");
err.status = codes.notfound;
} else if (req.query.simple) {
res.locals.items = item;
res.locals.processed = true;
return next();
}
else {
UserModel.findById(item._id, (err, user) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
if (!user) {
res.locals.items = {};
res.locals.processed = true;
return next();
}
getExtendedUser(user, next, (extUser) => {
res.locals.items = extUser;
res.locals.processed = true;
return next();
})
})
}
})
})
.delete(apiAuthenticationMiddleware, (req, res, next) => {
UserModel.findByIdAndRemove(req.params.id, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
}
else if (!item) {
err = new Error("item not found");
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 = __dirname + '/../resource/signature/' + req.params.id + '.png';
if (fs.existsSync(fileMinified)) {
fs.unlink(fileMinified);
}
const file = __dirname + '/../resource/signature/big/' + req.params.id + '.png';
if (fs.existsSync(file)) {
fs.unlink(file);
}
// 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
);
// 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);
/**
* Create model for single extended user and
* return via callback
*/
let getExtendedUser = (user, next, callback) => {
let extUser = {};
UserModel.findById(user._id, resultSet)
.populate('squadId', resultSet).exec((err, member) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
extUser._id = user._id;
extUser.username = user.username;
extUser.squad = member.squadId;
if (extUser.squad) {
RankModel.findOne({
level: member.rankLvl,
fraction: member.squadId.fraction
}, resultSet, (err, rank) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
extUser.rank = rank;
}).then(() => {
addAwards(extUser).then(() => {
callback(extUser);
})
})
} else {
extUser.rank = null;
addAwards(extUser).then(() => {
callback(extUser);
})
}
})
};
let addAwards = (extUser) => {
return AwardingModel.find({userId: extUser._id}, resultSet, {sort: {date: 'desc'}})
.populate('decorationId', resultSet)
.exec((err, awards) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
extUser.awards = awards;
})
};
module.exports = users;