Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. const validator = require('validator');
  2. const { errorHandler } = require('./helper');
  3.  
  4. module.exports = {
  5. role(arr) {
  6. return function(req, res, next) {
  7. var returnBoolean = false
  8. if(req.user.role == 'developer'){ returnBoolean = true; next(); } // If developer always allow access
  9. else{ arr.forEach(role => {
  10. if(role == req.user.role){ returnBoolean = true; next(); } // If role matches allow access
  11. }); }
  12. if(!returnBoolean) errorHandler(req, res, { status: 401, message: 'No permitido' })
  13. }
  14. },
  15. sanitize() {
  16. return function(req, res, next) {
  17. var goForward = true
  18. if(req.params.id){ // If there is a MongoID
  19. if(!validator.isMongoId(req.params.id)){ errorHandler(req, res, { status: 404, message: 'El ID no es válido' }); goForward = false }
  20. }
  21. if(goForward){
  22. if(Object.keys(req.body).length != 0){ // If it sends data though req.body // If req.body is not an empty object
  23. Object.keys(req.body).forEach(function(key) { // Iterating req.body
  24. 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)
  25. delete req.body[key]
  26. } else {
  27. if(typeof req.body[key] == 'string'){ // Avoiding issues when sending numbers, such as __v: 0
  28. if(req.body[key].length > 128){
  29. req.body[key] = req.body[key].substring(0, 128)
  30. }
  31. validator.trim(req.body[key])
  32. validator.escape(req.body[key])
  33. }
  34. }
  35. });
  36. next()
  37. } else { next(); } // If req.body is an empty object
  38. }
  39. }
  40. }
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement