Example #1
0
  cartRulesCheck : (req, res, next) => {

    const token = jwt.verify(req.headers[`x-access-token`], `silverSecret`);
    const userId = token._doc._id;
    const order = req.params.orderId || req.params.cartId;
    if (!token) {
      const error = new Error(`Header x-access-token required`);
      error.statusCode = 404;
      next(error);
    } else {
      Order.findOne({ _id : order })
        .then((orderFinded) => {
          if (!orderFinded) {
            const error = new Error(`Not Found`);
            error.statusCode = 404;
            next(error);
          } else if (orderFinded.userId === userId) {
            next()
          } else {
            const error = new Error(`Permission denied`);
            error.statusCode = 403;
            next(error)
          }
        })
        .catch((error) => {
          next(new Error(error))
        })
    }


  }
Example #2
0
module.exports =  function (req, res) {
    var token = req.cookies.surveyor;

    if (!token) {
        res.status(401).json({});
        return;
    }

    var title = req.body.title;
    var body = req.body.body;
    var options = req.body.options;

    crypto.verify(token).then(function (data) {
        console.log('data', data);
    }).then(function () {
        return Survey.create({
            title: title,
            body: body,
            options: options
        });
    }).then(function (results) {
        console.log(results);
        res.status(201).json({});
    }).catch(function (error) {
        console.log(error);
        res.status(400).json({});
    });
};
        this.verify = function (data, optionalReporterOverride) {

            var reporter = approvalsExtras.getCurrentReporter(optionalReporterOverride);

            var writer = new StringWriter(options, data);
            FileApprover.verify(namer, writer, reporter);
        };
Example #4
0
    it('Should verify the packaged zxp', function (done) {

        zxpSignCmd.verify(verifyOptions, function (error, result) {

            expect(error).to.be.a('null');
            done();
        });
    });
Example #5
0
    it('Should add info to the verification', function (done) {
        verifyOptions.info = true;

        zxpSignCmd.verify(verifyOptions, function (error, result) {

            expect(error).to.be.a('null');
            done();
        });
    });
Example #6
0
    it('Should throw an error because no input is provided', function (done) {
        verifyOptions.input = null;
        zxpSignCmd.verify(verifyOptions, function (error, result) {

            expect(error).to.be.an('error');
            expect(result).to.be.a('undefined');
            done();
        });
    });
Example #7
0
	app.get('/users/verify', function(req, res){
		usersImpl.verify(req.query.token, function(err, data){
			if(err == undefined){
				routeUtils.respond(req, res, data);
			}else{
				routeUtils.respond(req, res, err);
			}
		});
	});
 function(done) {
   //Verify the captcha
   reCaptcha.verify(req.body.grecaptcha, function(response) {
     if (!response) {
       done(null);
     } else {
       done("Invalid captcha!");
     }
   });
 },
Example #9
0
ProfileController.prototype.verify = function(req, res){
	var 
		email = req.body.email,
		pw = req.body.pw;
	
	profileObj.verify(email, pw, function(err, obj){
		if(err){
			utilObj.errResponse(res, err);
		}else{
			utilObj.objResponse(res, obj);
		}
	});
}
module.exports = function validateAuth(req, res, next) {
  let token = req.headers.token;

  if(!token) return next({code: 400, error: `No token provided.`});

  tokenCheck.verify(token)
    .then(user => {
      req.user = user;
      next();
    })
    .catch(() => {
      return next({
        code: 403,
        error: `Invalid token.`
      });
    });
};
Example #11
0
  adminCheck : (req, res, next) => {

    const token = jwt.verify(req.headers[`x-access-token`], `silverSecret`);
    const userId = token._doc._id;

    User.findOne({ _id : userId })
      .then((user) => {
        if (!user || user.rules !== `Admin`) {
          const error = new Error(`Permission denied`);
          error.statusCode = 403;
          next(error)
        } else {
          next()
        }
      })
      .catch((error) => {
        next(new Error(error))
      })
  },
Example #12
0
  checkOwnCar : (req, res, next) => {
    const token = jwt.verify(req.headers[`x-access-token`], `silverSecret`);
    const userId = token._doc._id;


    const stockId = req.body.stockId;
    User.findOne({ _id : userId })
      .then((user) => {
        if (!user) {
          const error = new Error(`Permission denied, car not Found`);
          error.statusCode = 403;
          next(error)
        } else {
          next()
        }
      })
      .catch((error) => {
        next(new Error(error))
      })
  },
Example #13
0
  wizard.validateInput(config, function(err, results){
    if (err){
      callback(err, null);
    } else {
      wizard.verify(config, function(err, results){
        if(err){
          callback(err, null);
        } else {
          wizard.configure(config, function(err, results){
            if(err){
              callback(err, null);
            } else {
              callback(null, results);
              // Launch Gateway
            }
          });

        }
      });
    }
  });
Example #14
0
  processImages: (req, res, next) => {
    // Ignore requests outside of the uploads folder
    if(!req.path.match(/^\/uploads\//)) return next();

    // Ignore requests where no query params exist
    if(typeof req.query !== 'object' || Object.keys(req.query).length === 0) return next();

    // Decode the path and get the mime type
    let targetFile = Path.join(__basedir, decodeURI(req.path));
    let mimeType = Mime.lookup(targetFile);

    // Ignore all files that aren't supported raster images
    if(!['image/gif', 'image/jpeg', 'image/png'].includes(mimeType)) return next();

    // Is the URL signed?
    if(!SignedUrl.verify(req.originalUrl, process.env.AUTH_SECRET)) {
      return res.status(HttpCodes.FORBIDDEN).end();
    }

    // Determine cache filename. We use a shortened hash of the path (relative to the app root) so
    // we can cleanup cache files when the original gets deleted.
    //
    // Cache filenames are formatted like this:
    //
    //  pathHash.key.extension
    //
    //  - Where pathHash is the first 10 chars of SHA256(path), and path is relative to the website
    //    root (e.g. '/uploads/2017/03/image.jpg').
    //  - Where key is a key from a signed URL.
    //  - Where extension is the lowercase file extension
    //
    let key = req.query.key || '';
    let extension = Path.extname(targetFile).toLowerCase();
    let pathHash = Crypto.createHash('sha256').update(decodeURI(req.path)).digest('hex').substring(0, 10);
    let cacheFile = Path.join(__basedir, 'cache/images', pathHash + '.' + key + extension);

    // Check for an existing cache file
    Fs.stat(cacheFile, (err) => {
      if(!err) {
        // We have a hit! Send the file from cache.
        res.header('Content-Type', mimeType).sendFile(cacheFile);
        return;
      }

      // Nothing in cache. Does the target file exist?
      Fs.stat(targetFile, (err) => {
        if(err) return next();

        // Process the image
        Promise.resolve(Gm(targetFile))
          // Skip animated images since resize, crop, rotate, etc. produce undesired results. It
          // *is* possible to process animations, but it's very time consuming, memory intensive,
          // and the resulting files are usually much larger than the originals due to the loss of
          // optimizations.
          //
          // See: github.com/Postleaf/postleaf/issues/44
          //
          .then((image) => {
            return new Promise((resolve, reject) => {
              image.identify('%n\n', (err, info) => {
                if(err) reject(err);

                info = info.split('\n');
                let numFrames = parseInt(info[0]);

                if(numFrames > 1) {
                  reject(new Error('Unable to process images with animation.'));
                }

                resolve(image);
              });
            });
          })
          // Resize
          .then((image) => {
            return new Promise((resolve, reject) => {
              if(req.query.width || req.query.height) {
                let width = req.query.width ? parseInt(req.query.width) : null;
                let height = req.query.height ? parseInt(req.query.height) : null;

                // Determine the image's current size
                image.size((err, size) => {
                  if(err) return reject(err);

                  // Only resize if requested dimensions are smaller than the original
                  if(width < size.width && height < size.height) {
                    image.resize(width, height);
                  }

                  resolve(image);
                });
              } else {
                resolve(image);
              }
            });
          })
          // Crop
          .then((image) => {
            if(req.query.crop) {
              let crop = req.query.crop.split(',');
              let x1 = parseInt(crop[0]);
              let y1 = parseInt(crop[1]);
              let x2 = parseInt(crop[2]);
              let y2 = parseInt(crop[3]);
              let cropWidth = Math.abs(x2 - x1);
              let cropHeight = Math.abs(y2 - y1);
              let x = Math.min(x1, x2);
              let y = Math.min(y1, y2);

              if(cropWidth > 0 && cropHeight > 0) {
                image.crop(cropWidth, cropHeight, x, y);
              }
            }

            return image;
          })
          // Thumbnail
          .then((image) => {
            return new Promise((resolve, reject) => {
              if(req.query.thumbnail) {
                let args = req.query.thumbnail.split(',');
                let width = args[0] ? parseInt(args[0]) : null;
                let height = args[1] ? parseInt(args[1]) : width;

                if(!width && !height) return resolve(image);

                // Determine the image's current size
                image.size((err, size) => {
                  if(err) return reject(err);

                  if(size.width < size.height) {
                    // Resize to width and crop to the desired height
                    image
                      .resize(width, null)
                      .gravity('Center')
                      .crop(width, height);
                  } else {
                    // Resize to height and crop to desired width
                    image
                      .resize(null, height)
                      .gravity('Center')
                      .crop(width, height);
                  }

                  resolve(image);
                });
              } else {
                resolve(image);
              }
            });
          })
          // Rotate
          .then((image) => {
            if(req.query.rotate) {
              let angle = parseInt(req.query.rotate);

              if(angle > 0 && angle < 360) {
                image.rotate('transparent', angle);
              }
            }

            return image;
          })
          // Flip
          .then((image) => {
            switch(req.query.flip) {
            case 'h':
              image.flop();
              break;
            case 'v':
              image.flip();
              break;
            case 'both':
              image.flip().flop();
              break;
            }

            return image;
          })
          // Grayscale
          .then((image) => {
            if(req.query.grayscale) {
              image.type('Grayscale');
            }

            return image;
          })
          // Colorize
          .then((image) => {
            if(req.query.colorize) {
              let rgb = req.query.colorize.split(',');
              let red = 100 - (parseInt(rgb[0]) || 0);
              let green = 100 - (parseInt(rgb[1]) || 0);
              let blue = 100 - (parseInt(rgb[2]) || 0);

              if(
                red >= 0 && red <= 100 &&
                green >= 0 && green <= 100 &&
                blue >= 0 && blue <= 100
              ) {
                image.colorize(red, green, blue);
              }
            }

            return image;
          })
          // Blur
          .then((image) => {
            if(req.query.blur) {
              let radius = parseInt(req.query.blur);

              if(radius > 0) {
                image.blur(0, radius);
              }
            }

            return image;
          })
          // Colors
          .then((image) => {
            if(req.query.colors) {
              let colors = parseInt(req.query.colors);

              if(colors > 0) {
                image.colors(colors);
              }
            }

            return image;
          })
          // Quality
          .then((image) => {
            if(req.query.quality) {
              let quality = parseInt(req.query.quality);

              if(quality >= 1 && quality <= 100) {
                image.quality(quality);
              }
            }

            return image;
          })
          // Write and serve the image to cache
          .then((image) => {
            // Create the cache directory if it doesn't exist
            Mkdirp.sync(Path.dirname(cacheFile));

            // Write the cache file
            image.write(cacheFile, (err) => {
              if(err) throw new Error(err);
              res.header('Content-Type', mimeType).sendFile(cacheFile);
              return;
            });
          })
          // Something went wrong, fallback and serve the static image
          .catch(() => next());
      });
    });
  }
 it('should allow `rowspan`', function() {
   var result = whitelister.verify('rowspan');
   expect(result).to.be.ok();
 });
 it('should return true when the tag is in the whitelist', function() {
   var result = whitelister.verify('style');
   expect(result).to.be.ok();
 });
 return new Promise((resolve, reject) => {
   jwt.verify(token, sekrit, (err, payload) => {
     if(err) return reject(err);
     return resolve(payload);
   });
 });
 it('should allow `bgcolor`', function() {
   var result = whitelister.verify('bgcolor');
   expect(result).to.be.ok();
 });
 it('should allow `font-face`', function() {
   var result = whitelister.verify('font-face');
   expect(result).to.be.ok();
 });
 it('should return false when the tag is not in the whitelist', function() {
   var result = whitelister.verify('hack');
   expect(result).not.to.be.ok();
 });
Example #21
0
  addToOrder : (req, res, next) => {

    const token = jwt.verify(req.headers[`x-access-token`], `silverSecret`);
    const userId = token._doc._id;


    const stockId = req.body.stockId;
    const orderId = req.body.orderId;

    if (!userId || !stockId) {
      const error = new Error(`UserId,StockId required`);
      error.statusCode = 404;
      next(error);
    } else if (orderId) {
      Orders.findOneAndUpdate({
        orderId : orderId
      },
        { $push : { items : { stockId : stockId } } })
        .then((temp) => {
          if (!temp) {
            const order = new Orders();
            order.items.push({ stockId : stockId });
            order.userId = userId;
            order.save((error) => {
              if (error) {
                next(error)
              }
            });
            res.json(order._id)
          } else {
            res.json(temp._id)
          }

        })
        .catch((error) => {
          next(new Error(error))
        })
    } else {
      Orders.findOneAndUpdate({
        userId : userId
      },
        { $push : { items : { stockId : stockId } } })
        .then((temp) => {
          if (!temp) {
            const order = new Orders();
            order.items.push({ stockId : stockId });
            order.userId = userId;
            order.save((error) => {
              if (error) {
                next(error)
              } else {
                res.json(order._id)
              }
            });
          } else {
            res.json(temp._id)
          }

        })
        .catch((error) => {
          next(new Error(error))
        })
    }
  },
 it('should allow `src`', function() {
   var result = whitelister.verify('src');
   expect(result).to.be.ok();
 });