Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const validator = require('validator');
- const { errorHandler } = require('./helper');
- module.exports = {
- role(arr) {
- return function(req, res, next) {
- var returnBoolean = false
- if(req.user.role == 'developer'){ returnBoolean = true; next(); } // If developer always allow access
- else{ arr.forEach(role => {
- if(role == req.user.role){ returnBoolean = true; next(); } // If role matches allow access
- }); }
- if(!returnBoolean) errorHandler(req, res, { status: 401, message: 'No permitido' })
- }
- },
- sanitize() {
- return function(req, res, next) {
- var goForward = true
- if(req.params.id){ // If there is a MongoID
- if(!validator.isMongoId(req.params.id)){ errorHandler(req, res, { status: 404, message: 'El ID no es válido' }); goForward = false }
- }
- if(goForward){
- if(Object.keys(req.body).length != 0){ // If it sends data though req.body // If req.body is not an empty object
- Object.keys(req.body).forEach(function(key) { // Iterating req.body
- if(req.body[key] === "" || req.body[key] == null || req.body[key] == undefined){ // If you are sending me trash I'll delete it (I won't save trash in my DB)
- delete req.body[key]
- } else {
- if(typeof req.body[key] == 'string'){ // Avoiding issues when sending numbers, such as __v: 0
- if(req.body[key].length > 128){
- req.body[key] = req.body[key].substring(0, 128)
- }
- validator.trim(req.body[key])
- validator.escape(req.body[key])
- }
- }
- });
- next()
- } else { next(); } // If req.body is an empty object
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement