Example #1
0
	app.post('/api/colname', function(req, res){
		// required values
		var wallId = req.body.wallId
		  , colNum = req.body.colNum
		  , title = req.body.title;
		
		// sanitize and escape values
		sanitize(wallId).xss();
		sanitize(wallId).escape();
		sanitize(colNum).xss();
		sanitize(colNum).escape();
		sanitize(title).xss();
		sanitize(title).escape();
		
		// check user can view accociated wall
		hasPermission(wallId, req.user.id, function(result){
			if(result) {
				textPermission(wallId, req.user.id, function(textResult){
					// if the user is not a view on wall
					if(textResult != "view"){
						// create new wall and return json object
						ColName.create({
							wallId: wallId,
							colNum: colNum,
							title: title
						}).success(function(colname){
							res.json(colname);
						}).error(function(){
							res.send(500, {"error" : "internal server error"});
						});
					} else {
						res.send(401, {"error" : "unauthorized"});
					}
				});
			} else {
				res.send(401, {"error" : "unauthorized"});
			}
		});
	});
exports.generatePdfOfChart = function(req, res){
	try {
		check(req.body.zona).notNull();
		check(req.body.umbral).notNull().isNumeric();
		check(req.body.img).notNull();
		
		zona = sanitize(req.body.zona).xss();
		zona = sanitize(zona).entityDecode();
		
		umbral = sanitize(req.body.umbral).xss();
		umbral = sanitize(umbral).entityDecode();		
		
		img = sanitize(req.body.img).xss();
		img = sanitize(img).entityDecode();		
		
		var data = img.replace(/^data:image\/\w+;base64,/, "");
		var buf = new Buffer(data, 'base64');
		
		fs.writeFile('public/downloads/pdf/chart.png', buf, function(err) {
	    if (err) throw err;
	    
	    doc = new PDFDocument({size: 'LEGAL',layout: 'landscape'});
	    doc.fontSize(25);
	    doc.text('Occupation with threshold ' + umbral + ' dBm (' + zona + ')', {align: 'center'});
			doc.image('public/downloads/pdf/chart.png', { width: 850, height: 460});
			doc.write('public/downloads/pdf/occupation.pdf',function(){
				fs.unlink('public/downloads/pdf/chart.png', function(){
				if (err) throw err;
					res.send('0');
				});
			});
	  });
		
	} catch (e) {
	  	res.render('index'); 
	  	console.log(e.message);
	}
};
Example #3
0
	app.post('/api/walluser', function(req, res){
		// required data
		var userId = req.body.userId
		  , wallId = req.body.wallId
		  , permission = req.body.permission;
		
		// sanitise and escape
		sanitize(userId).xss();
		sanitize(userId).escape();
		sanitize(wallId).xss();
		sanitize(wallId).escape();
		sanitize(permission).xss();
		sanitize(permission).escape();
		
		// check for wall permission
		hasPermission(wallId, req.user.id, function(result){
			if(result) {
				textPermission(wallId, req.user.id, function(textResult){
					// check is not a wall viewer only
					if(textResult != "view"){
						WallUser.create({
							userId: userId,
							wallId: wallId,
							permission: permission
						}).success(function(colname){
							res.json(colname);
						}).error(function(){
							res.send(500, {"error" : "internal server error"});
						});
					} else {
						res.send(401, {"error" : "unauthorized"});
					}
				});
			} else {
				res.send(401, {"error" : "unauthorized"});
			}
		});
	});
Example #4
0
exports.create = function(req, res, next) {
    //开始校验输入数值的正确性
    var _id = sanitize(req.body._id).trim();
    var name = sanitize(req.body.name).trim();
    var merchant_id = sanitize(req.body.merchant_id).trim();
    var state = sanitize(req.body.state).trim();
    var inventar_num = sanitize(req.body.inventar_num).trim();
    var district_code = sanitize(req.body.district_code).trim();

    if(!inventar_num) return res.json({status:'资产编号不能为空!'});
    if(!name) return res.json({status:'名字不能为空!'});
    if(!merchant_id) return res.json({status:'请选择所属商户!'});
    if(!state) return res.json({status:'请选择状态!'});
    if(!district_code) return res.json({status:'地区编号不能为空!'});
    if(_id){
        //流水号不为空,说明是更新
        Store.update(req.body, function(err, rs){
            if(err) return next(err);
            res.json({status:'success'});
        });
    }else{
        //创建门店仓库
        Warehouse.create(name, function(err, info){
            if(err) return next(err);
            //获得门店仓库的ID,并与门店关联
            req.body.warehouse_id = info.insertId;
            req.body.create_time = getNow();

            Store.create(req.body, function(err, info){
                if(err) return next(err);
                //return info.insertId;
                res.json({status:'success'});
            });
        });
    }
};
Example #5
0
    get_topic_by_id(topic_id,function(err,topic,tags,author){
      if(!topic){
        res.render('notify/notify',{error: '此话题不存在或已被删除。'});
        return; 
      }
      if(topic.author_id == req.session.user._id || req.session.user.is_admin){
        var title = sanitize(req.body.title).trim();
        title = sanitize(title).xss();
        var content = req.body.t_content;
        var topic_tags=[];
        if(req.body.topic_tags != ''){
          topic_tags = req.body.topic_tags.split(',');
        }

        if(title == ''){
          tag_ctrl.get_all_tags(function(err,all_tags){
            if(err) return next(err);
            for(var i=0; i<topic_tags.length; i++){
              for(var j=0; j<all_tags.length; j++){
                if(topic_tags[i] == all_tags[j]._id){
                  all_tags[j].is_selected = true;
                }
              } 
            }
            res.render('topic/edit',{action:'edit',edit_error:'标题不能是空的。',topic_id:topic._id, content:content,tags:all_tags});
            return;
          });
        }else{
          //保存话题
          //删除topic_tag,标签topic_count减1
          //保存新topic_tag  
          topic.title = title;
          topic.content = content;
          topic.update_at = new Date();
          topic.save(function(err){
            if(err) return next(err);

            var proxy = new EventProxy();
            var render = function(){
              res.redirect('/topic/'+topic._id);
            }
            proxy.assign('tags_removed_done','tags_saved_done',render);

            // 删除topic_tag
            var tags_removed_done = function(){
              proxy.trigger('tags_removed_done');
            };
            TopicTag.find({topic_id:topic._id},function(err,docs){
              if(docs.length == 0){
                proxy.trigger('tags_removed_done');
              }else{
                proxy.after('tag_removed',docs.length,tags_removed_done);
                // delete topic tags
                for(var i=0; i<docs.length; i++){
                  (function(i){
                    docs[i].remove(function(err){
                      if(err) return next(err);
                      tag_ctrl.get_tag_by_id(docs[i].tag_id,function(err,tag){
                        if(err) return next(err);
                        proxy.trigger('tag_removed');
                        tag.topic_count -= 1;
                        tag.save();
                      });
                    });
                  })(i); 
                }
              }
            });
          
            // 保存topic_tag
            var tags_saved_done = function(){
              proxy.trigger('tags_saved_done');
            } 
            //话题可以没有标签
            if(topic_tags.length == 0){
              proxy.trigger('tags_saved_done');
            }else{
              proxy.after('tag_saved',topic_tags.length,tags_saved_done);
              //save topic tags 
              for(var i=0; i<topic_tags.length; i++){
                (function(i){
                  var topic_tag = new TopicTag();
                  topic_tag.topic_id = topic._id;
                  topic_tag.tag_id = topic_tags[i];
                  topic_tag.save(function(err){
                    if(err) return next(err);
                    proxy.trigger('tag_saved');
                  });
                  tag_ctrl.get_tag_by_id(topic_tags[i],function(err,tag){
                    if(err) return next(err);
                    tag.topic_count += 1;
                    tag.save();
                  });
                })(i);
              }
            }

            //发送at消息
            at_ctrl.send_at_message(content,topic._id,req.session.user._id);
          });
        } 
      }else{
        res.render('notify/notify',{error:'对不起,你不能编辑此话题。'});
        return;
      }
    });
Example #6
0
 tail.stdout.on('data', function (data) {
     var lines = sanitizer(data.toString('utf-8')).xss().split('\n');
     lines.pop();
     io.sockets.emit('lines', lines);
 });
Example #7
0
 sanitize: function (attr) {
     return sanitize(this.get(attr)).xss();
 },
Example #8
0
exports.signup = function (req, res, next) {
  var name = sanitize(req.body.name).trim();
  name = sanitize(name).xss();
  var loginname = name.toLowerCase();
  var pass = sanitize(req.body.pass).trim();
  pass = sanitize(pass).xss();
  var email = sanitize(req.body.email).trim();
  email = email.toLowerCase();
  email = sanitize(email).xss();
  var re_pass = sanitize(req.body.re_pass).trim();
  re_pass = sanitize(re_pass).xss();

  if (name === '' || pass === '' || re_pass === '' || email === '') {
    res.render('sign/signup', {error: '信息不完整。', name: name, email: email});
    return;
  }

  if (name.length < 4) {
    res.render('sign/signup', {error: '用户名至少需要4个字符。', name: name, email: email});
    return;
  }

  try {
    check(name, '用户名只能使用0-9,a-z,A-Z。').isAlphanumeric();
  } catch (e) {
    res.render('sign/signup', {error: e.message, name: name, email: email});
    return;
  }

  if (pass !== re_pass) {
    res.render('sign/signup', {error: '两次密码输入不一致。', name: name, email: email});
    return;
  }

  try {
    check(email, '不正确的电子邮箱。').isEmail();
  } catch (e) {
    res.render('sign/signup', {error: e.message, name: name, email: email});
    return;
  }

  User.getUsersByQuery({'$or': [{'loginname': loginname}, {'email': email}]}, {}, function (err, users) {
    if (err) {
      return next(err);
    }
    if (users.length > 0) {
      res.render('sign/signup', {error: '用户名或邮箱已被使用。', name: name, email: email});
      return;
    }

    // md5 the pass
    pass = md5(pass);
    // create gavatar
    var avatar_url = 'http://www.tianxiawuai.com/' + md5(email.toLowerCase()) + '?size=48';

    User.newAndSave(name, loginname, pass, email, avatar_url, false, function (err) {
      if (err) {
        return next(err);
      }
      // 发送激活邮件
      mail.sendActiveMail(email, md5(email + config.session_secret), name);
      res.render('sign/signup', {
        success: '欢迎加入 ' + config.name + '!我们已给您的注册邮箱发送了一封邮件,请点击里面的链接来激活您的帐号。'
      });
    });
  });
};
Example #9
0
var setAdmin = module.exports.setAdmin = function(adminType, isAdmin, userId, callback) {
    // Ensure we're using a real principal id. If we weren't, we would be dangerously upserting an invalid row
    var validator = new Validator();
    validator.check(userId, {'code': 400, 'msg': 'Attempted to update a principal with a non-principal id'}).isPrincipalId();
    if (validator.hasErrors()) {
        return callback(validator.getError());
    }

    Cassandra.runQuery(util.format('UPDATE "Principals" SET "%s" = ? WHERE "principalId" = ?', adminType), [sanitize(isAdmin).toBooleanStrict().toString(), userId], function(err) {
        if (err) {
            return callback(err);
        }

        return invalidateCachedUsers([userId], callback);
    });
};
Example #10
0
 var positions = map(req.param('positions').split('\n'), function(p) {return sanitize(p).trim();});
Example #11
0
  Topic.getTopicById(topic_id, function (err, topic, tags) {
    if (!topic) {
      res.render('notify/notify', {error: '此话题不存在或已被删除。'});
      return;
    }

    if (String(topic.author_id) === req.session.user._id || req.session.user.is_admin) {
      var title = sanitize(req.body.title).trim();
      title = sanitize(title).xss();
      var content = req.body.t_content;
      var topic_tags = [];
      if (req.body.topic_tags !== '') {
        topic_tags = req.body.topic_tags.split(',');
      }

      if (title === '') {
        Tag.getAllTags(function (err, all_tags) {
          if (err) {
            return next(err);
          }
          for (var i = 0; i < topic_tags.length; i++) {
            for (var j = 0; j < all_tags.length; j++) {
              if (topic_tags[i] === all_tags[j]._id) {
                all_tags[j].is_selected = true;
              }
            }
          }
          res.render('topic/edit', {action: 'edit', edit_error: '标题不能是空的。', topic_id: topic._id, content: content, tags: all_tags});
        });
      } else {
        //保存话题
        //删除topic_tag,标签topic_count减1
        //保存新topic_tag
        topic.title = title;
        topic.content = content;
        topic.update_at = new Date();
        topic.save(function (err) {
          if (err) {
            return next(err);
          }

          var proxy = new EventProxy();
          var render = function () {
            res.redirect('/topic/' + topic._id);
          };
          proxy.assign('tags_removed_done', 'tags_saved_done', render);
          proxy.fail(next);

          // 删除topic_tag
          var tags_removed_done = function () {
            proxy.emit('tags_removed_done');
          };
          TopicTag.getTopicTagByTopicId(topic._id, function (err, docs) {
            if (docs.length === 0) {
              proxy.emit('tags_removed_done');
            } else {
              proxy.after('tag_removed', docs.length, tags_removed_done);
              // delete topic tags
              docs.forEach(function (doc) {
                doc.remove(proxy.done(function () {
                  Tag.getTagById(doc.tag_id, proxy.done(function (tag) {
                    proxy.emit('tag_removed');
                    tag.topic_count -= 1;
                    tag.save();
                  }));
                }));
              });
            }
          });
          // 保存topic_tag
          var tags_saved_done = function () {
            proxy.emit('tags_saved_done');
          };
          //话题可以没有标签
          if (topic_tags.length === 0) {
            proxy.emit('tags_saved_done');
          } else {
            proxy.after('tag_saved', topic_tags.length, tags_saved_done);
            //save topic tags
            topic_tags.forEach(function (tag) {
              TopicTag.newAndSave(topic._id, tag, proxy.done('tag_saved'));
              Tag.getTagById(tag, proxy.done(function (tag) {
                tag.topic_count += 1;
                tag.save();
              }));
            });
          }
          //发送at消息
          at.sendMessageToMentionUsers(content, topic._id, req.session.user._id);
        });
      }
    } else {
      res.render('notify/notify', {error: '对不起,你不能编辑此话题。'});
    }
  });
Example #12
0
exports.put = function (req, res, next) {
  var title = sanitize(req.body.title).trim();
  title = sanitize(title).xss();
  var content = req.body.t_content;
  var topic_tags = [];
  if (req.body.topic_tags !== '') {
    topic_tags = req.body.topic_tags.split(',');
  }

  var edit_error =
      title === '' ?
    '标题不能是空的。' :
    (title.length >= 5 && title.length <= 100 ? '' : '标题字数太多或太少。');
  if (edit_error) {
    Tag.getAllTags(function (err, tags) {
      if (err) {
        return next(err);
      }
      for (var i = 0; i < topic_tags.length; i++) {
        for (var j = 0; j < tags.length; j++) {
          if (topic_tags[i] === tags[j]._id) {
            tags[j].is_selected = true;
          }
        }
      }
      res.render('topic/edit', {tags: tags, edit_error: edit_error, title: title, content: content});
    });
  } else {
    Topic.newAndSave(title, content, req.session.user._id, function (err, topic) {
      if (err) {
        return next(err);
      }

      var proxy = new EventProxy();
      var render = function () {
        res.redirect('/topic/' + topic._id);
      };

      proxy.assign('tags_saved', 'score_saved', render);
      proxy.fail(next);
      // 话题可以没有标签
      if (topic_tags.length === 0) {
        proxy.emit('tags_saved');
      }
      var tags_saved_done = function () {
        proxy.emit('tags_saved');
      };
      proxy.after('tag_saved', topic_tags.length, tags_saved_done);
      //save topic tags
      topic_tags.forEach(function (tag) {
        TopicTag.newAndSave(topic._id, tag, proxy.done('tag_saved'));
        Tag.getTagById(tag, proxy.done(function (tag) {
          tag.topic_count += 1;
          tag.save();
        }));
      });
      User.getUserById(req.session.user._id, proxy.done(function (user) {
        user.score += 5;
        user.topic_count += 1;
        user.save();
        req.session.user = user;
        proxy.emit('score_saved');
      }));

      //发送at消息
      at.sendMessageToMentionUsers(content, topic._id, req.session.user._id);
    });
  }
};
Example #13
0
exports.edit = function(req, res, next){
	if(!req.session.user)
		return res.redirect('/login');

	var id = req.params.id;

	if(id.length != 24){
		res.render('error', {
			error: '无此信息或已被删除!'
		});
	}

	var method = req.method.toLowerCase();
	if(method == 'get'){

		Article.getUnion({
			_id: id
		}, function(err, art, user){
			if(err)
				return next(err);

			if(!art)
				return res.render('error', {error: '无此信息或已被删除!'});

			if(art.author_id != req.session.user._id || !req.session.user.isAdmin){
				res.render('error', {
					error: '对不起,你不能编辑此文章!'
				});
				return
			}

			res.render('article_edit', {
				action: 'article_edit',
				article_id: art._id,
				title: art.title,
				content: art.content
			});

		})
		return
	}
	// post
	var title = sanitize(req.body.title).trim();
	var content = req.body.content;

	if(!title){
		res.render('article_edit', {
			error: '标题不能为空',
			content: content
		});
		return
	}

	if(!content){
		res.render('article_edit', {
			error: '内容不能为空',
			title: title
		});
		return
	}


	Article.getUnion({
		_id: id
	}, function(err, art){
		if(err)
			return next(err);

		if(!art)
			return res.render('error', {error: '无此信息或已被删除!'});

		if(art.author_id != req.session.user._id || !req.session.user.isAdmin){
			res.render('error', {
				error: '对不起,你不能编辑此文章!'
			});
			return
		}

		art.title = title;
		art.content = content;
		art.update_at = Date.now();
		art.edit_id = req.session.user._id;

		art.save(function(err){
			if(err)
				return next(err);

			res.redirect('/');
		});

	})


}
Example #14
0
exports.setting = function (req, res, next) {
  if (!req.session.user) {
    res.redirect('/');
    return;
  }

  // 显示出错或成功信息
  function showMessage (msg, data, isSuccess) {
    var data = data || req.body;
    var data2 = {
      name: data.name,
      email: data.email,
      url: data.url,
      profile_image_url: data.profile_image_url,
      location: data.location,
      signature: data.signature,
      profile: data.profile,
      weibo: data.weibo,
      githubUsername: data.github || data.githubUsername,
    };
    if (isSuccess) {
      data2.success = msg;
    } else {
      data2.error = msg;
    }
    res.render('user/setting', data2);
  }

  // post
  var action = req.body.action;
  if (action === 'change_setting') {
    var name = sanitize(req.body.name).trim();
    name = sanitize(name).xss();
    var email = sanitize(req.body.email).trim();
    email = sanitize(email).xss();
    var url = sanitize(req.body.url).trim();
    url = sanitize(url).xss();
    var profile_image_url = null;
    if (typeof req.body.profile_image_url === 'string') {
      profile_image_url = sanitize(sanitize(req.body.profile_image_url).trim()).xss();
    }
    var location = sanitize(req.body.location).trim();
    location = sanitize(location).xss();
    var signature = sanitize(req.body.signature).trim();
    signature = sanitize(signature).xss();
    var profile = sanitize(req.body.profile).trim();
    profile = sanitize(profile).xss();
    var weibo = sanitize(req.body.weibo).trim();
    weibo = sanitize(weibo).xss();
    var github = sanitize(req.body.github).trim();
    github = sanitize(github).xss();
    if (github.indexOf('@') === 0) {
      github = github.slice(1);
    }

    if (url !== '') {
      try {
        if ((url.indexOf('http://') < 0) && (url.indexOf('https://') < 0)) {
          url = 'http://' + url;
        }
        check(url, '不正确的个人网站。').isUrl();
      } catch (e) {
        return showMessage(e.message);
      }
    }
    if (weibo) {
      try {
        if (weibo.indexOf('http://') < 0) {
          weibo = 'http://' + weibo;
        }
        check(weibo, '不正确的微博地址。').isUrl();
      } catch (e) {
        return showMessage(e.message);
      }
    }

    User.getUserById(req.session.user._id, function (err, user) {
      if (err) {
        return next(err);
      }
      user.url = url;
      if (typeof profile_image_url === 'string') {
        user.profile_image_url = profile_image_url;
      }
      user.location = location;
      user.signature = signature;
      user.profile = profile;
      user.weibo = weibo;
      user.githubUsername = github;
      user.save(function (err) {
        if (err) {
          return next(err);
        }
        return res.redirect('/setting?save=success');
      });
    });

  }
  if (action === 'change_password') {
    var old_pass = sanitize(req.body.old_pass).trim();
    var new_pass = sanitize(req.body.new_pass).trim();

    User.getUserById(req.session.user._id, function (err, user) {
      if (err) {
        return next(err);
      }
      var md5sum = crypto.createHash('md5');
      md5sum.update(old_pass);
      old_pass = md5sum.digest('hex');

      if (old_pass !== user.pass) {
        return showMessage('当前密码不正确。', user);
      }

      md5sum = crypto.createHash('md5');
      md5sum.update(new_pass);
      new_pass = md5sum.digest('hex');

      user.pass = new_pass;
      user.save(function (err) {
        if (err) {
          return next(err);
        }
        return showMessage('密码已被修改。', user, true);

      });
    });
  }
};
Example #15
0
exports.quote = function(req, res, next) {

  var values = req.query;
  var pass = true;
  
  try {
    values.name = sanitize(values.name).xss().trim();
    check(values.name).notNull();
  } catch (e) {
    pass = false;
    req.session.flash.error.push("Quote: Name can't be left blank." );
  }
  
  try {
    values.email = sanitize(values.email).xss().trim();
    check(values.email).notNull().isEmail();
  } catch (e) {
    pass = false;
    req.session.flash.error.push( "Quote: Enter a valid email address." );
  }
  
  try {
    values.comment = sanitize(values.comment).xss().trim();
    check(values.comment).notNull();
  } catch (e) {
    pass = false;
    req.session.flash.error.push("Quote: Please provide a short description of your project." );
  }
  
  values.company = sanitize(values.company).xss().trim();
  values.url = sanitize(values.url).xss().trim();
  values.phone = sanitize(values.phone).xss().trim();
  values.deadline = sanitize(values.deadline).xss().trim();
  values.budget = sanitize(values.budget).xss().trim();
  
  if (!pass) {
    req.session.form.values = values;
    res.redirect('/');
  }
  
  else {
    var subject = 'Website Quote Request: from ' + values.name
      , html = "<h1>Website Quote:</h1>"+
        "<p>" +
        "<strong>Name:</strong> " + values.name + "<br>" +
        "<strong>Email:</strong> " + values.email + "<br>" +
        "<strong>Company:</strong> " + values.company + "<br>" +
        "<strong>URL:</strong> " + values.url + "<br>" +
        "<strong>Phone:</strong> " + values.phone + "<br>" +
        "<strong>Budget:</strong> " + values.budget + "<br>" +
        "<strong>Deadline:</strong> " + values.deadline + "<br>" +
        "<strong>Description:</strong> " + values.comment + "<br>" +
        "</p>";
    
    //'janet@oxygenproductions.com,ron@oxygenproductions.com,elliot@oxygenproductions.com,patrick@oxygenproductions.com',
    
    var transport = nodemailer.createTransport("Sendmail", "/usr/sbin/sendmail");
    var message = {
        generateTextFromHTML: true,
        from: '*****@*****.**',
        to: 'janet@oxygenproductions.com,ron@oxygenproductions.com,elliot@oxygenproductions.com,patrick@oxygenproductions.com',
        subject: subject, 
        html: html
    };
    transport.sendMail(message, function(error){  
      if(error){
        req.session.flash.error.push( 'There was an error processing your request.' );
        res.redirect('/');
      }
      
      var message2 = {
          generateTextFromHTML: true,
          from: '*****@*****.**',
          to: values.email,
          cc: '',
          subject: 'Thank you from Oxygen Productions, Inc.', 
          html: "Thank you for you request. Someone will be in touch with you shortly."
      };
      transport.sendMail(message2, function(error2) {
        res.send( 'Thank you! We will get back to you shortly.' );
      });
    });
  }
  
};
Example #16
0
 set: function(val) { return(sanitize(val).xss()); }
Example #17
0
exports.setting = function (req, res, next) {
  if (!req.session.user) {
    res.redirect('home');
    return;
  }
  var method = req.method.toLowerCase();
  if (method !== 'post') {
    get_user_by_id(req.session.user._id, function (err, user) {
      if (err) {
        return next(err);
      }
      if (req.query.save === 'success') {
        user.success = '保存成功。';
      }
      user.error = null;
      return res.render('user/setting', user);
    });
    return;
  }
  // post
  var action = req.body.action;
  if (action === 'change_setting') {
    var name = sanitize(req.body.name).trim();      
    name = sanitize(name).xss();
    var email = sanitize(req.body.email).trim();      
    email = sanitize(email).xss();
    var url = sanitize(req.body.url).trim();      
    url = sanitize(url).xss();
    var location = sanitize(req.body.location).trim();      
    location = sanitize(location).xss();
    var signature = sanitize(req.body.signature).trim();      
    signature = sanitize(signature).xss();
    var profile = sanitize(req.body.profile).trim();      
    profile = sanitize(profile).xss();
    var weibo = sanitize(req.body.weibo).trim();      
    weibo = sanitize(weibo).xss();
    var receive_at_mail = req.body.receive_at_mail === 'on' ? true: false;
    var receive_reply_mail = req.body.receive_reply_mail === 'on' ? true: false;

    if (url !== '') {
      try {
        if (url.indexOf('http://') < 0) {
          url = 'http://' + url;
        }
        check(url, '不正确的个人网站。').isUrl();
      } catch (e) {
        res.render('user/setting', {
          error:e.message,name:name,email:email,url:url,location:location,
          signature:signature,profile:profile,weibo:weibo,
          receive_at_mail: receive_at_mail,
          receive_reply_mail: receive_reply_mail
        });
        return;
      }
    }
    if (weibo) {
      try {
        if (weibo.indexOf('http://') < 0) {
          weibo = 'http://' + weibo;
        }
        check(weibo, '不正确的微博地址。').isUrl();
      } catch (e) {
        res.render('user/setting', {
          error:e.message,name:name,email:email,url:url,location:location,
          signature:signature,profile:profile,weibo:weibo,
          receive_at_mail: receive_at_mail,
          receive_reply_mail: receive_reply_mail
        });
        return;
      }
    }

    get_user_by_id(req.session.user._id,function(err,user){
      if (err) {
        return next(err);
      }
      user.url = url;
      user.location = location;
      user.signature = signature;
      user.profile = profile;
      user.weibo = weibo;
      user.receive_at_mail = receive_at_mail;
      user.receive_reply_mail = receive_reply_mail;
      user.save(function(err){
        if (err) {
          return next(err);
        }
        return res.redirect('/setting?save=success');
      });
    });

  }
  if (action === 'change_password') {
    var old_pass = sanitize(req.body.old_pass).trim();
    var new_pass = sanitize(req.body.new_pass).trim();

    get_user_by_id(req.session.user._id,function(err,user){
      if (err) {
        return next(err);
      }
      var md5sum = crypto.createHash('md5');
      md5sum.update(old_pass);
      old_pass = md5sum.digest('hex');

      if (old_pass !== user.pass) {
        res.render('user/setting', {
          error:'当前密码不正确。',name:user.name,email:user.email,url:user.url,location:user.location,
          signature:user.signature,profile:user.profile,weibo:user.weibo,
          receive_at_mail: user.receive_at_mail,
          receive_reply_mail: user.receive_reply_mail
        });
        return;
      }

      md5sum = crypto.createHash('md5');
      md5sum.update(new_pass);
      new_pass = md5sum.digest('hex');

      user.pass = new_pass;
      user.save(function (err) {
        if (err) {
          return next(err);
        }
        res.render('user/setting', {
          success: '密码已被修改。',
          name: user.name,
          email: user.email,
          url: user.url,
          location: user.location,
          signature: user.signature,
          profile: user.profile,weibo:user.weibo,
          receive_at_mail: user.receive_at_mail,
          receive_reply_mail: user.receive_reply_mail
        });
        return;

      });
    });
  }
};
Example #18
0
File: app.js Project: kmanley/ql.io
 _.each(v, function(val) {
     holder.params[k].push(sanitize(val).str);
 });
Example #19
0
 var staffers = map(req.param('staffers').split('\n'), function(s) {return sanitize(s).trim();});
Example #20
0
File: app.js Project: kmanley/ql.io
 _.each(v, function(val) {
     holder.headers[k].push(sanitize(val).str);
 });
Example #21
0
Strategy.prototype.authenticate = function(req, options) {
    options = options || {};
    var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField);
    var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField);
    var domain   = lookup(req.body, this._domainField)   || lookup(req.query, this._domainField);
    
    var username = sanitize(username).xss();
    
    if (!username || !password || !domain) {
        return this.fail(new BadRequestError(options.badRequestMessage || 'Missing credentials'));
    }
    
    var self = this;

    if (self._domainAllowed.indexOf(domain) < 0) {
        return this.fail(new BadRequestError(options.badRequestMessage || 'Domain not allowed'));
    }

    var client = self.clients[domain];
    var baseDN = self.baseDNs[domain];

    client.bind(domain + '\\' + username, password, function(err) {
        if (err) {
            return self.error(new InternalLdapError('Failed to bind to LDAP', err));
        }

        var search = {
            filter: '(sAMAccountName=' + username + ')',
            scope: 'sub'
        };
        client.search(baseDN, search, function(err, res) {
            if (err) {
                return self.error(new InternalLdapError('LDAP search error', err));
            }

            res.on('searchEntry', function(entry) {
                var profile = entry.object;

                self._verify(profile, function(err, user) {
                    if (err) {
                        return self.error(new InternalLdapError('LDAP verify failed', err));
                    }
                    if (!user) {
                        return self.error(new InternalLdapError('LDAP search failed', err));
                    }
                    self.success(user);
                });
            });

            res.on('error', function(err) {
                return self.error(new InternalLdapError('LDAP network error', err));
            });

            res.on('end', function(result) {
                if (result.status !== 0) {
                    return self.error(new InternalLdapError('LDAP connection terminated unexpectedly', err));
                }
            });
        });
    });

    function lookup(obj, field) {
        if (!obj) {
            return null;
        }
        var chain = field.split(']')
            .join('')
            .split('[');
        for (var i = 0, len = chain.length; i < len; i++) {
            var prop = obj[chain[i]];
            if (typeof(prop) === 'undefined') {
                return null;
            }
            if (typeof(prop) !== 'object') {
                return prop;
            }
            obj = prop;
        }
        return null;
    }
};
Example #22
0
  return function(value, rules, fail_msg) {
    // TODO optimize this, loops, init what need in fields
    // FIXME how about sequence check?
    validator.check(value, fail_msg);
    var type = rules.type;
    var f, v;
    for(var name in rules) {
      // f(v)
      (f = ruleValidator[name]) && f.apply(validator, Array.isArray(v = rules[name]) ? v : [v]);
    }
    if(type && (f=typeValidator[type])) f.apply(validator);

    filter.convert(value);
    for(var name in rules) {
      v = rules[name];
      if(typeof v === 'function') {
        v.apply(filter);
      }
      else {
        // f(v)
        (f = ruleFilter[name]) && f.apply(filter, Array.isArray(v = rules[name]) ? v : [v]);
      }
    }

    if(type && (f=typeFilter[type])) f.apply(validator);
    if(type ==='int') {
        return sanitize(filter.value()).toInt();
    }
    if(type ==='float') {
        return sanitize(filter.value()).toFloat();
    }
    if(type ==='date') {
        return new Date(filter.value());
    }
    if(type ==='arrayInt') {
        var oArr = filter.value(),
            nArr = [];

        oArr.forEach(function (value) {
            nArr.push(sanitize(value).toInt());
        });

        return nArr;
    }
    if(type ==='arrayFloat') {
        var oArr = filter.value(),
            nArr = [];

        oArr.forEach(function (value) {
            nArr.push(sanitize(value).toFloat());
        });

        return nArr;
    }
    if(type == 'arrayString') {
        var oArr = filter.value(),
            nArr = [];
//        console.log('type of :', typeof oArr);
        if (typeof oArr === 'string') {
            nArr.push(oArr);
            return _.compact(nArr);
        }

        return _.compact(oArr);
    }

    return filter.value();
  }
Example #23
0
	socket.on('message_to_server', function(data) { 
		var escaped_message = sanitize(data["message"]).escape();
		io.sockets.emit("message_to_client",{ message: escaped_message }); 
	});
Example #24
0
 oArr.forEach(function (value) {
     nArr.push(sanitize(value).toFloat());
 });
Example #25
0
	// trims, encodes, and prevents xss of input
	function sanitizeInput(input){
		var msg = sanitize(input).trim();
		msg = sanitize(msg).entityEncode();
		msg = sanitize(msg).xss();
		return msg;
	}
Example #26
0
	getFriends: function(userID, resultFn) {
		var query = 'select friends.*, users.name, users.points, users.email from users,friends where friends.user_id= ' + sanitize(userID).toInt() + ' and users.id = friends.friend_user_id';
		this.executeQuery(query, {}, resultFn);
	}
Example #27
0
exports.create = function (req, res, next) {
  if (!req.session.user) {
    res.render('notify/notify', {error: '未登入用户不能发布话题。'});
    return;
  }

  var method = req.method.toLowerCase();
  if(method == 'get'){
    tag_ctrl.get_all_tags(function(err,tags){
      if(err) return next(err);
      res.render('topic/edit',{tags:tags});
      return;
    });
  }

  if(method == 'post'){
    var title = sanitize(req.body.title).trim();
    title = sanitize(title).xss();
    var content = req.body.t_content;
    var topic_tags=[];
    if(req.body.topic_tags != ''){
      topic_tags = req.body.topic_tags.split(',');
    } 

    if(title == ''){
      tag_ctrl.get_all_tags(function(err,tags){
        if(err) return next(err);
        for(var i=0; i<topic_tags.length; i++){
          for(var j=0; j<tags.length; j++){
            if(topic_tags[i] == tags[j]._id){
              tags[j].is_selected = true;
            }
          } 
        }
        res.render('topic/edit',{tags:tags, edit_error:'标题不能是空的。', content:content});
        return;
      });
    }else if(title.length<10 || title.length>100){
      tag_ctrl.get_all_tags(function(err,tags){
        if(err) return next(err);
        for(var i=0; i<topic_tags.length; i++){
          for(var j=0; j<tags.length; j++){
            if(topic_tags[i] == tags[j]._id){
              tags[j].is_selected = true;
            }
          } 
        }
        res.render('topic/edit',{tags:tags, edit_error:'标题字数太多或太少', title:title, content:content});
        return;
      });
    }else{
      var topic = new Topic();
      topic.title = title;
      topic.content = content;
      topic.author_id = req.session.user._id;
      topic.save(function(err){
        if(err) return next(err);
      
        var proxy = new EventProxy();
        var render = function(){
          res.redirect('/topic/'+topic._id);
        }

        proxy.assign('tags_saved','score_saved',render)
        //话题可以没有标签
        if(topic_tags.length == 0){
          proxy.trigger('tags_saved');
        }
        var tags_saved_done = function(){
          proxy.trigger('tags_saved');
        };
        proxy.after('tag_saved',topic_tags.length,tags_saved_done);
        //save topic tags 
        for(var i=0; i<topic_tags.length; i++){
          (function(i){
            var topic_tag = new TopicTag();
            topic_tag.topic_id = topic._id;
            topic_tag.tag_id = topic_tags[i];
            topic_tag.save(function(err){
              if(err) return next(err);
              proxy.trigger('tag_saved');
            });
            tag_ctrl.get_tag_by_id(topic_tags[i],function(err,tag){
              if(err) return next(err);
              tag.topic_count += 1;
              tag.save();
            });
          })(i);
        }
        user_ctrl.get_user_by_id(req.session.user._id,function(err,user){
          if(err) return next(err);
          user.score += 5;
          user.topic_count += 1;
          user.save();
          req.session.user.score += 5;  
          proxy.trigger('score_saved');
        });

        //发送at消息
        at_ctrl.send_at_message(content,topic._id,req.session.user._id);
      });
    }
  } 
};
Example #28
0
/**
 * 性能测试 validator模块
 */

var sanitize = require('validator').sanitize;
var fs = require('fs');


var html = fs.readFileSync(__dirname + '/file.html', 'utf8');


var timeStart = Date.now();
for (var i = 0; i < 1000; i++) {
  var ret = sanitize(html).xss();
}
var timeEnd = Date.now();


//console.log(ret);
fs.writeFileSync(__dirname + '/result_validator.html', ret);

var spent = timeEnd - timeStart;
var speed = (((html.length * i) / spent * 1000) / 1024 / 1024).toFixed(2);
console.log('spent ' + spent + 'ms, ' + speed + 'MB/s');
Example #29
0
			_.each(dir,function(val,key){
				d[key] = sanitize(val).entityDecode();
			})
Example #30
0
	run: function (input) {
		return sanitize(input).xss();
	}