Compare commits

...

2 Commits

Author SHA1 Message Date
HardiReady 141a340aad Add upload image dimension check/limitation for rank, squad and decoration images (CC-69) 2019-02-03 12:16:22 +01:00
HardiReady 68ad467e4d * Add image dimension check for rank submit/update
* Update server dependencies
* Update gitignore after api package rename
2019-02-03 11:49:48 +01:00
15 changed files with 773 additions and 431 deletions

6
.gitignore vendored
View File

@ -4,7 +4,7 @@
dist/ dist/
tmp/ tmp/
etc/ etc/
api/apib/documentation.apib server/apib/documentation.apib
# dependencies # dependencies
node_modules node_modules
@ -47,8 +47,8 @@ Thumbs.db
# Internal Data # Internal Data
public/ public/
mongodb-data/ mongodb-data/
api/resource/ server/resource/
api/apib/dredd/data/tmp-resource server/apib/dredd/data/tmp-resource
backup/ backup/
# System # System

View File

@ -3,6 +3,9 @@
// HTTP status codes by name // HTTP status codes by name
const codes = require('../routes/http-codes'); const codes = require('../routes/http-codes');
// library to check image dimensions from file buffer
const sizeOf = require('buffer-image-size');
/** /**
* check if id has valid UUID format * check if id has valid UUID format
* *
@ -22,4 +25,14 @@ const idValidator = (req, res, next) => {
next(); next();
}; };
const imageDimensionValidator = (imageFileBuf, maxWidth, maxHeight) => {
const dimensions = sizeOf(imageFileBuf);
if (dimensions.width > maxWidth || dimensions.height > maxHeight) {
let err = new Error(`Image exceeds maximum dimensions of ${maxWidth}px width and ${maxHeight}px height`);
err.status = codes.wrongrequest;
return err;
}
};
exports.idValidator = idValidator; exports.idValidator = idValidator;
exports.imageDimensionValidator = imageDimensionValidator;

814
server/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -21,24 +21,25 @@
"dependencies": { "dependencies": {
"async": "^2.5.0", "async": "^2.5.0",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"body-parser": "~1.13.2", "body-parser": "^1.18.3",
"buffer-image-size": "^0.6.4",
"cors": "^2.8.4", "cors": "^2.8.4",
"cron": "^1.3.0", "cron": "^1.3.0",
"debug": "^3.1.0", "debug": "^3.1.0",
"express": "^4.16.2", "express": "^4.16.2",
"imagemin": "^5.2.2", "imagemin": "^5.2.2",
"imagemin-pngquant": "^5.0.0", "imagemin-pngquant": "^5.0.0",
"jimp": "^0.2.27", "jimp": "^0.6.0",
"jsonwebtoken": "^7.4.3", "jsonwebtoken": "^7.4.3",
"lodash": "^4.17.4", "lodash": "^4.17.4",
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"mongoose": "^5.0.3", "mongoose": "^5.0.3",
"morgan": "~1.6.1", "morgan": "^1.9.1",
"multer": "^1.3.0", "multer": "^1.3.0",
"node-html-parser": "^1.1.10", "node-html-parser": "^1.1.10",
"node-sha1": "^1.0.1", "node-sha1": "^1.0.1",
"q": "^1.5.0", "q": "^1.5.0",
"serve-favicon": "~2.3.0", "serve-favicon": "^2.5.0",
"supports-color": "^5.1.0" "supports-color": "^5.1.0"
}, },
"devDependencies": { "devDependencies": {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 794 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 61 KiB

View File

@ -13,6 +13,7 @@ const codes = require('./http-codes');
const apiAuthenticationMiddleware = require('../middleware/auth-middleware'); const apiAuthenticationMiddleware = require('../middleware/auth-middleware');
const checkHl = require('../middleware/permission-check').checkHl; const checkHl = require('../middleware/permission-check').checkHl;
const genericGetById = require('./_generic').genericGetById;
const routerHandling = require('../middleware/router-handling'); const routerHandling = require('../middleware/router-handling');
const idValidator = require('../middleware/validators').idValidator; const idValidator = require('../middleware/validators').idValidator;
const resourceLocation = require('../middleware/resource-location').resourceLocation().concat('/decoration/'); const resourceLocation = require('../middleware/resource-location').resourceLocation().concat('/decoration/');
@ -22,140 +23,175 @@ const DecorationModel = require('../models/decoration');
const AwardingsModel = require('../models/awarding'); const AwardingsModel = require('../models/awarding');
// util // util
const genericGetById = require('./_generic').genericGetById; const imageDimensionValidator = require('../middleware/validators').imageDimensionValidator;
const MAX_MEDAL_IMAGE_WIDTH = 100;
const MAX_MEDAL_IMAGE_HEIGHT = 150;
const MAX_RIBBON_IMAGE_WIDTH = 150;
const MAX_RIBBON_IMAGE_HEIGHT = 50;
const decoration = new express.Router(); const decorationRouter = new express.Router();
// routes ********************** // routes **********************
decoration.route('/') decorationRouter.route('/')
.get((req, res, next) => { .get((req, res, next) => {
const filter = {}; const filter = {};
if (req.query.fractFilter) { if (req.query.fractFilter) {
filter.fraction = req.query.fractFilter.toUpperCase(); filter.fraction = req.query.fractFilter.toUpperCase();
} }
if (req.query.q) { if (req.query.q) {
filter.name = {$regex: req.query.q, $options: 'i'}; filter.name = {$regex: req.query.q, $options: 'i'};
} }
DecorationModel.find(filter, {}, { DecorationModel.find(filter, {}, {
sort: { sort: {
fraction: 'asc', fraction: 'asc',
isMedal: 'asc', isMedal: 'asc',
sortingNumber: 'asc', sortingNumber: 'asc',
name: 'asc', name: 'asc',
}, },
}, (err, items) => { }, (err, items) => {
if (err) { if (err) {
err.status = codes.servererror; err.status = codes.servererror;
return next(err); return next(err);
} }
if (items && items.length > 0) { if (items && items.length > 0) {
res.locals.items = items; res.locals.items = items;
} else { } else {
res.locals.items = []; res.locals.items = [];
} }
res.locals.processed = true; res.locals.processed = true;
next(); next();
}); });
}) })
.post(apiAuthenticationMiddleware, checkHl, upload.single('image'), (req, res, next) => { .post(apiAuthenticationMiddleware, checkHl, upload.single('image'), (req, res, next) => {
const decoration = new DecorationModel(req.body); if (req.file) {
// timestamp and default are set automatically by Mongoose Schema Validation const decoration = new DecorationModel(req.body);
decoration.save((err) => {
if (err) {
err.status = codes.wrongrequest;
err.message += ' in fields: ' + Object.getOwnPropertyNames(err.errors);
return next(err);
}
res.status(codes.created);
res.locals.items = decoration;
fs.appendFile(resourceLocation + decoration._id + '.png',
new Buffer(req.file.buffer),
(err) => {
if (err) next(err);
});
next();
});
})
.all( const imageFileBuffer = req.file.buffer;
routerHandling.httpMethodNotAllowed const err = imageDimensionValidator(imageFileBuffer,
); (decoration.isMedal ? MAX_MEDAL_IMAGE_WIDTH : MAX_RIBBON_IMAGE_WIDTH),
(decoration.isMedal ? MAX_MEDAL_IMAGE_HEIGHT : MAX_RIBBON_IMAGE_HEIGHT));
if (err) {
return next(err);
}
decoration.route('/:id') // timestamp and default are set automatically by Mongoose Schema Validation
.get(idValidator, (req, res, next) => { decoration.save((err) => {
return genericGetById(req, res, next, DecorationModel); if (err) {
}) err.status = codes.wrongrequest;
err.message += ' in fields: ' + Object.getOwnPropertyNames(err.errors);
return next(err);
}
res.status(codes.created);
res.locals.items = decoration;
fs.appendFile(resourceLocation + decoration._id + '.png',
new Buffer(req.file.buffer),
(err) => {
if (err) next(err);
});
next();
});
} else {
const err = new Error('no image file provided');
err.status = codes.wrongmediasend;
next(err);
}
})
.patch(apiAuthenticationMiddleware, checkHl, upload.single('image'), (req, res, next) => { .all(
if (!req.body || (req.body._id && req.body._id !== req.params.id)) { routerHandling.httpMethodNotAllowed
// 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(.) decorationRouter.route('/:id')
req.body.updatedAt = new Date(); .get(idValidator, (req, res, next) => {
req.body.$inc = {__v: 1}; return genericGetById(req, res, next, DecorationModel);
})
if (req.file) { .patch(apiAuthenticationMiddleware, checkHl, upload.single('image'), (req, res, next) => {
const file = resourceLocation + req.params.id + '.png'; if (!req.body || (req.body._id && req.body._id !== req.params.id)) {
fs.unlink(file, (err) => { // little bit different as in PUT. :id does not need to be in data, but if the _id and url id must
if (err) next(err); // match
fs.appendFile(file, new Buffer(req.file.buffer), (err) => { const err = new Error(
if (err) next(err); '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.
}
// PATCH is easier with mongoose than PUT. You simply update by all data that comes from outside. no need // optional task 3: increment version manually as we do not use .save(.)
// to reset attributes that are missing. req.body.updatedAt = new Date();
DecorationModel.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, item) => { req.body.$inc = {__v: 1};
if (err) {
err.status = codes.wrongrequest;
} else if (!item) {
err = new Error('item not found');
err.status = codes.notfound;
} else {
res.locals.items = item;
}
next(err);
});
})
.delete(apiAuthenticationMiddleware, checkHl, (req, res, next) => { DecorationModel.findById(req.body._id, (err, item) => {
const id = req.params.id; if (err) {
DecorationModel.findByIdAndRemove(id, (err, item) => { return next(err);
if (err) { }
err.status = codes.wrongrequest; if (req.file) {
} else if (!item) { const imageFileBuffer = req.file.buffer;
err = new Error('item not found'); const imageDimensionError = imageDimensionValidator(imageFileBuffer,
err.status = codes.notfound; (item.isMedal ? MAX_MEDAL_IMAGE_WIDTH : MAX_RIBBON_IMAGE_WIDTH),
} (item.isMedal ? MAX_MEDAL_IMAGE_HEIGHT : MAX_RIBBON_IMAGE_HEIGHT));
if (imageDimensionError) {
return next(imageDimensionError);
}
// deleted all awardings linked to this decoration const file = resourceLocation + req.params.id + '.png';
AwardingsModel.find({decorationId: id}).remove().exec(); fs.unlink(file, (err) => {
if (err) next(err);
fs.appendFile(file, new Buffer(req.file.buffer), (err) => {
if (err) next(err);
});
});
}
// delete graphic // PATCH is easier with mongoose than PUT. You simply update by all data that comes from outside. no
fs.unlink(resourceLocation.concat(id).concat('.png'), // need to reset attributes that are missing.
(err) => { DecorationModel.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, item) => {
// we don't set res.locals.items and thus it will send a 204 (no content) at the end. see last handler if (err) {
res.locals.processed = true; err.status = codes.wrongrequest;
next(err); } else if (!item) {
}); err = new Error('item not found');
}); err.status = codes.notfound;
}) } else {
res.locals.items = item;
}
next(err);
});
});
})
.all( .delete(apiAuthenticationMiddleware, checkHl, (req, res, next) => {
routerHandling.httpMethodNotAllowed const id = req.params.id;
); DecorationModel.findByIdAndRemove(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 decoration
AwardingsModel.find({decorationId: id}).remove().exec();
// delete graphic
fs.unlink(resourceLocation.concat(id).concat('.png'),
(err) => {
// we don't set res.locals.items and thus it will send a 204 (no content) at the end. see last
// handler
res.locals.processed = true;
next(err);
});
});
})
.all(
routerHandling.httpMethodNotAllowed
);
// this middleware function can be used, if you like or remove it // 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 // it looks for object(s) in res.locals.items and if they exist, they are send to the client as json
decoration.use(routerHandling.emptyResponse); decorationRouter.use(routerHandling.emptyResponse);
module.exports = decoration; module.exports = decorationRouter;

View File

@ -22,6 +22,9 @@ const RankModel = require('../models/rank');
// util // util
const genericGetById = require('./_generic').genericGetById; const genericGetById = require('./_generic').genericGetById;
const imageDimensionValidator = require('../middleware/validators').imageDimensionValidator;
const MAX_IMAGE_WIDTH = 120;
const MAX_IMAGE_HEIGHT = 120;
const ranks = new express.Router(); const ranks = new express.Router();
@ -53,20 +56,32 @@ ranks.route('/')
}) })
.post(apiAuthenticationMiddleware, checkHl, upload.single('image'), (req, res, next) => { .post(apiAuthenticationMiddleware, checkHl, upload.single('image'), (req, res, next) => {
const rank = new RankModel(req.body); if (req.file) {
// timestamp and default are set automatically by Mongoose Schema Validation const imageFileBuffer = req.file.buffer;
rank.save((err) => { const err = imageDimensionValidator(imageFileBuffer, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
if (err) { if (err) {
err.status = codes.wrongrequest; return next(err);
next(err);
} }
res.status(codes.created);
res.locals.items = rank; const rank = new RankModel(req.body);
fs.appendFile(resourceLocation + rank._id + '.png', new Buffer(req.file.buffer), // timestamp and default are set automatically by Mongoose Schema Validation
(err) => { rank.save((err) => {
if (err) {
err.status = codes.wrongrequest;
next(err); next(err);
}); }
}); res.status(codes.created);
res.locals.items = rank;
fs.appendFile(resourceLocation + rank._id + '.png', new Buffer(imageFileBuffer),
(err) => {
next(err);
});
});
} else {
const err = new Error('no image file provided');
err.status = codes.wrongmediasend;
next(err);
}
}) })
.all( .all(
@ -94,10 +109,16 @@ ranks.route('/:id')
req.body.$inc = {__v: 1}; req.body.$inc = {__v: 1};
if (req.file) { if (req.file) {
const imageFileBuffer = req.file.buffer;
const err = imageDimensionValidator(imageFileBuffer, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
if (err) {
return next(err);
}
const file = resourceLocation + req.params.id + '.png'; const file = resourceLocation + req.params.id + '.png';
fs.unlink(file, (err) => { fs.unlink(file, (err) => {
if (err) next(err); if (err) next(err);
fs.appendFile(file, new Buffer(req.file.buffer), fs.appendFile(file, new Buffer(imageFileBuffer),
(err) => { (err) => {
if (err) next(err); if (err) next(err);
}); });

View File

@ -22,6 +22,9 @@ const SquadModel = require('../models/squad');
// util // util
const genericGetById = require('./_generic').genericGetById; const genericGetById = require('./_generic').genericGetById;
const imageDimensionValidator = require('../middleware/validators').imageDimensionValidator;
const MAX_IMAGE_WIDTH = 150;
const MAX_IMAGE_HEIGHT = 150;
const squads = new express.Router(); const squads = new express.Router();
@ -54,6 +57,12 @@ squads.route('/')
const squad = new SquadModel(req.body); const squad = new SquadModel(req.body);
// timestamp and default are set automatically by Mongoose Schema Validation // timestamp and default are set automatically by Mongoose Schema Validation
if (req.file) { if (req.file) {
const imageFileBuffer = req.file.buffer;
const err = imageDimensionValidator(imageFileBuffer, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
if (err) {
return next(err);
}
squad.save((err) => { squad.save((err) => {
if (err) { if (err) {
err.status = codes.wrongrequest; err.status = codes.wrongrequest;
@ -62,10 +71,9 @@ squads.route('/')
} }
res.status(codes.created); res.status(codes.created);
res.locals.items = squad; res.locals.items = squad;
fs.appendFile(resourceLocation.concat(squad._id).concat('.png'), fs.appendFile(resourceLocation.concat(squad._id).concat('.png'), new Buffer(imageFileBuffer), (err) => {
new Buffer(req.file.buffer), (err) => { next(err);
next(err); });
});
}); });
} else { } else {
const err = new Error('no image file provided'); const err = new Error('no image file provided');
@ -98,11 +106,16 @@ squads.route('/:id')
req.body.$inc = {__v: 1}; req.body.$inc = {__v: 1};
if (req.file) { if (req.file) {
const imageFileBuffer = req.file.buffer;
const err = imageDimensionValidator(imageFileBuffer, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
if (err) {
return next(err);
}
const file = resourceLocation.concat(req.params.id) const file = resourceLocation.concat(req.params.id)
.concat('.png'); .concat('.png');
fs.unlink(file, (err) => { fs.unlink(file, (err) => {
if (err) next(err); if (err) next(err);
fs.appendFile(file, new Buffer(req.file.buffer), (err) => { fs.appendFile(file, new Buffer(imageFileBuffer), (err) => {
if (err) next(err); if (err) next(err);
}); });
}); });

View File

@ -66,7 +66,7 @@ export class EditDecorationComponent implements OnInit, OnDestroy {
if (this.fileList) { if (this.fileList) {
file = this.fileList[0]; file = this.fileList[0];
this.decorationService.submitDecoration(this.decoration, file) this.decorationService.submitDecoration(this.decoration, file)
.subscribe(rank => { .subscribe(decoration => {
this.router.navigate(['..'], {relativeTo: this.route}); this.router.navigate(['..'], {relativeTo: this.route});
}); });
} else { } else {
@ -83,12 +83,15 @@ export class EditDecorationComponent implements OnInit, OnDestroy {
} }
delete this.decoration['__v']; delete this.decoration['__v'];
this.decorationService.submitDecoration(this.decoration, file) this.decorationService.submitDecoration(this.decoration, file)
.subscribe(rank => { .subscribe(decoration => {
setTimeout(() => { setTimeout(() => {
this.imagePreviewSrc = 'resource/decoration/' + this.decoration._id + '.png?' + Date.now(); this.imagePreviewSrc = 'resource/decoration/' + this.decoration._id + '.png?' + Date.now();
}, 300); }, 300);
fileInput.value = ''; fileInput.value = '';
this.snackBarService.showSuccess('generic.save.success'); this.snackBarService.showSuccess('generic.save.success');
}, error => {
const errorMsg = error._body ? JSON.parse(error._body).error.message : error.error.error.message;
this.snackBarService.showError('Error: '.concat(errorMsg), 15000);
}); });
} }
} }

View File

@ -74,9 +74,9 @@ export class EditRankComponent implements OnInit, OnDestroy {
this.router.navigate(['..'], {relativeTo: this.route}); this.router.navigate(['..'], {relativeTo: this.route});
}); });
} else { } else {
this.translate.get('ranks.submit.field.image').subscribe((fieldNameIMage) => { this.translate.get('ranks.submit.field.image').subscribe((fieldNameImage) => {
this.translate.get('public.error.message.required', this.translate.get('public.error.message.required',
{fieldName: fieldNameIMage}).subscribe((message) => { {fieldName: fieldNameImage}).subscribe((message) => {
this.snackBarService.showError(message, 4000); this.snackBarService.showError(message, 4000);
}) })
}); });
@ -93,6 +93,9 @@ export class EditRankComponent implements OnInit, OnDestroy {
}, 300); }, 300);
fileInput.value = ''; fileInput.value = '';
this.snackBarService.showSuccess('generic.save.success'); this.snackBarService.showSuccess('generic.save.success');
}, error => {
const errorMsg = error._body ? JSON.parse(error._body).error.message : error.error.error.message;
this.snackBarService.showError('Error: '.concat(errorMsg), 15000);
}); });
} }
} }

View File

@ -69,7 +69,7 @@ export class EditSquadComponent implements OnInit, OnDestroy {
if (this.fileList) { if (this.fileList) {
file = this.fileList[0]; file = this.fileList[0];
this.squadService.submitSquad(this.squad, file) this.squadService.submitSquad(this.squad, file)
.subscribe(rank => { .subscribe(squad => {
this.saved = true; this.saved = true;
this.router.navigate(['..'], {relativeTo: this.route}); this.router.navigate(['..'], {relativeTo: this.route});
}); });
@ -87,12 +87,15 @@ export class EditSquadComponent implements OnInit, OnDestroy {
} }
delete this.squad['__v']; delete this.squad['__v'];
this.squadService.submitSquad(this.squad, file) this.squadService.submitSquad(this.squad, file)
.subscribe(rank => { .subscribe(squad => {
setTimeout(() => { setTimeout(() => {
this.imagePreviewSrc = 'resource/squad/' + this.squad._id + '.png?' + Date.now(); this.imagePreviewSrc = 'resource/squad/' + this.squad._id + '.png?' + Date.now();
}, 300); }, 300);
fileInput.value = ''; fileInput.value = '';
this.snackBarService.showSuccess('generic.save.success'); this.snackBarService.showSuccess('generic.save.success');
}, error => {
const errorMsg = error._body ? JSON.parse(error._body).error.message : error.error.error.message;
this.snackBarService.showError('Error: '.concat(errorMsg), 15000);
}); });
} }
} }

View File

@ -54,7 +54,6 @@ export class StatisticComponent implements OnInit {
} }
} else if (url.includes('right:war')) { } else if (url.includes('right:war')) {
const id = idFetchPattern.exec(url)[1]; const id = idFetchPattern.exec(url)[1];
console.log(id)
this.campaignService.getCampaignByWarId(id).subscribe((campaign) => { this.campaignService.getCampaignByWarId(id).subscribe((campaign) => {
this.switchCampaign(campaign); this.switchCampaign(campaign);
}); });