Example #1
0
 it('only returns true if passed md5(full_name)', function () {
   var matt = new Director('abcdef', { full_name: 'Matt' });
   matt.isAuthorized(md5('Matt')).should.be.true;
   matt.isAuthorized(md5('Matf')).should.be.false;
   matt.isAuthorized('Matt').should.be.false;
   matt.isAuthorized('').should.be.false;
 });
Example #2
0
    db.connection.query('SELECT * FROM users WHERE email = \'' + mail + '\'', function(err, result, fields) {
        if (!err) {
            if (result[0]) {
                var pass = md5("pass" + Math.random() * 100000000000 + new Date().getTime() + "a").substring(3, 9);
                var code = md5(pass);
                db.connection.query('UPDATE users SET  password="' + code + '" WHERE  email = "' + mail + '" LIMIT 1', function(error, r, fields) {
                    if (error) {
                        callback({ok: false, e: 'db fail'});
                    }
                    if (r) {
                        exec('php /home/trigger/node/sendpass.php ' + result[0].email + ' ' + result[0].name + ' ' + pass, function(error, stdout, stderr) {
                            if (!error) {
                                callback({ok: true, m: 'Привет, ' + result[0].name + ' на твой ящик ' + result[0].email + ' отправлен новый пароль ;)'});
                            } else {
                                callback({ok: false, e: 'sending mail fail'});
                            }
                        });

                    }
                });
            } else {
                callback({ok: false, e: 'no user'});
            }
        } else {
            callback({ok: false, e: 'db fail'});
        }
    });
Example #3
0
        iterateResults(function analyze(tn, en, res) {
            res.stdout_md5 = md5(res.stdout);
            res.stderr_md5 = md5(res.stderr);

            if (res.testcase.meta.skip) {
                res.status = 'skip';
            } else if (res.diff_expect) {
                res.status = 'fail';
            } else {
                res.status = 'pass';
            }
        });
Example #4
0
function parseTestCaseSync(filePath) {
    var text = fs.readFileSync(filePath, 'utf-8');
    var pos, i1, i2;
    var meta = {};
    var tmp;
    var expect = '';

    i1 = text.indexOf('/*---'); i2 = text.indexOf('---*/');
    if (i1 >= 0 && i2 >= 0 && i2 >= i1) {
        meta = JSON.parse(text.substring(i1 + 5, i2));
    }

    pos = 0;
    for (;;) {
        i1 = text.indexOf('/*===', pos); i2 = text.indexOf('===*/', pos);
        if (i1 >= 0 && i2 >= 0 && i2 >= i1) {
            pos = i2 + 5;
            tmp = text.substring(i1 + 5, i2).split('\n').slice(1, -1);  // ignore first and last line
            expect += tmp.map(function (x) { return x + '\n'; }).join('');
        } else {
            break;
        }
    }

    return {
        filePath: filePath,
        name: path.basename(filePath, '.js'),
        meta: meta,
        expect: expect,
        expect_md5: md5(expect)
    };
}
Example #5
0
module.exports.auth = function (req, res) {
  var authInfo = req.body;

  if (!utils.checkFields(authInfo, ["username", "password"])) {
    res.status(500).json({
      error: "empty_fields"
    });
  } else {
    var userModel = db('users').find({
      username: authInfo.username,
      password: md5(authInfo.password)
    });

    if (typeof userModel === "undefined") {
      res.status(500).json({
        error: "not_found_user"
      });
    } else {
      var generatedToken = randomToken.generate(32);

      db('tokens').push({
        id: uuid(),
        user_id: userModel.id,
        token: generatedToken
      });

      res.status(200).json({
        result: {
          token: generatedToken
        }
      });
    }
  }
};
Example #6
0
module.exports.register = function (req, res) {
  var loginInfo = req.body;

  if (!utils.checkFields(loginInfo, ["username", "password"])) {
    res.status(500).json({
      error: "empty_fields"
    });
  } else {
    var userModel = db('users').find({
      username: loginInfo.username
    });

    if (typeof userModel === "undefined") {
      db('users').push({
        id: uuid(),
        username: loginInfo.username,
        password: md5(loginInfo.password)
      });

      res.status(200).json({status:"Ok"});
    } else {
      res.status(500).json({
        error: "exist_user"
      });
    }
  }
};
Example #7
0
var parse = function( opt, data, cb ){
    try{
        var $ = opt.window.$;
        var out = {url_list:[], content:undefined, image_list:[]}, lines=[];

        $("#artical #artical_real >p.pictext").remove();

        var img = $("#artical #artical_real >p img:first");
        if(img && img.attr('src').match(/^http/)) {
            out.image_list.push([img.attr('src'), img.attr('alt')]);
            img.parent().remove();
        }


        $("#artical #artical_real >p").each(function(){
            lines.push($(this).text().replace(/\r?\n +/g,''));
        });
        out.content = lines.join("\r\n");

        out.title = $('#artical #artical_topic').text();

        //获取分页信息
        out.total_page = 1;
        out.page = 1;

        //内容的标识
        var href_key = data.url.replace(/(-\d+)?\.shtm$/, "");
        out.content_key = md5(href_key);

        cb( undefined, out );
    }catch(e){
        cb( e.toString() );
    }
};
Example #8
0
 mongoose.connect('mongodb://localhost/test_in', function () {
     mongoose.connection.db.dropCollection("users")
     mongoose.connection.db.dropCollection("accesstokens")
     User({
         firstname: "Thomas",
         lastname: "Lacrierre",
         email: "lacroix@gmail.com",
         about: "",
         role: 1,
         password: md5("00000000")
     }).save(function (err, user) {
         if (err) throw err;
         idUser2 = user._id;
         User({
             firstname: "Pierre",
             lastname: "Medard",
             email: "medard@gmail.com",
             about: "",
             role: 1,
             password: md5("00000000")
         }).save(function (err, user) {
             if (err) throw err;
             idUser = user._id;
             done()
         });
     });
 });
Example #9
0
// Base64(MD5(Implode(Sort(Params) + SecretKey, ':')))
// Implode(Sort(Params) + SecretKey, ':')
// Sort(Params) + SecretKey
function checkSignature(body) {

  var incomingSignature = body.ik_sign;

  var signature = Object.keys(body)
    .filter(function(key) {
      return key != 'ik_sign';
    })
    .sort()
    .map(function(key) {
      return body[key];
    });

  console.log(signature);
  signature.push(interkassaConfig.secret);

  console.log(signature);

  signature = signature.join(':');

  console.log(signature);

  signature = new Buffer(md5(signature, {asBytes: true})).toString('base64');

  console.log(signature, '==', incomingSignature);

  return signature == incomingSignature;
}
Example #10
0
                mkdir(__dirname + '/../uploads/' + req.user.username + '/networks', function(err) {
                    if (err) console.error(err);

                    var hashDate = Date.now();
                    var fileExtension = filename.substring(filename.lastIndexOf('.'));

                    filename = md5(hashDate + filename) + fileExtension;

                    uploadPath = '/uploads/' + req.user.username + '/networks/' + filename;
                    var stream = fs.createWriteStream(__dirname + '/..' + uploadPath);
                    file.pipe(stream);
                    stream.on('close', function() {
                        console.log('File ' + filename + ' is uploaded');

                        // Update the database with the avatars paths
                        user.profile.social[req.params.position].logo = uploadPath;
                        user.save(function(err) {
                            if (err) {
                                return res.status(400).send("Could not add image");
                            } else {
                                return res.status(200).send(uploadPath);
                            }
                        });
                    });

                });
Example #11
0
                mkdir(__dirname + '/../uploads/' + req.user.username, function(err) {
                    if (err) console.error(err);

                    var hashDate = Date.now();
                    var fileExtension = filename.substring(filename.lastIndexOf('.'));

                    filename = md5(hashDate + filename) + fileExtension;

                    uploadPath = '/uploads/' + req.user.username + '/' + filename;
                    var stream = fs.createWriteStream(__dirname + '/../uploads/' + req.user.username + '/' + filename);
                    file.pipe(stream);
                    stream.on('close', function() {
                        console.log('File ' + filename + ' is uploaded');

                        if (user.uploads.length >= app.settings.maxImages) {
                            return res.status(403).send("Maximum number of pictures reached: " + app.settings.maxImages);
                        }

                        // Update the database with the avatars paths
                        user.uploads.push(uploadPath);
                        user.save(function(err) {
                            if (err) {
                                return res.status(400).send("Could not add image");
                            } else {
                                return res.status(200).send(uploadPath);
                            }
                        });
                    });

                });
Example #12
0
            docs.forEach(function(item) {
                item.id = t;
                positionOfElement = previousStarts.contains(item.start);
                if (positionOfElement > -1) {
                    console.log("Already contains");
                    console.log(previousEnds[positionOfElement]);
                    if (previousEnds[positionOfElement] < item.end && previousEnds[positionOfElement] !== undefined && returnN[positionOfElement] !== undefined) {

                        previousEnds[positionOfElement] = item.end;
                        returnN[positionOfElement].end = new Date(new Date(item.end).getTime() + (1000 * 60 * 60 * 2)).toISOString();

                    }
                } else {
                    if (item.duration > minDuration) {
                        previousStarts.push(item.start);
                        previousEnds.push(item.end);
                        item.start = new Date(new Date(item.start).getTime()).toISOString();
                        item.end = new Date(new Date(item.end).getTime()).toISOString();
                        event[t] = new icalendar.VEvent(md5(JSON.stringify(item)));
                        event[t].setSummary(item.title);
                        event[t].setDate(new Date(item.start), new Date(item.end));
                        event[t].toString();
                    }
                }





                t++;
            });
Example #13
0
Hue.prototype.pair = function(self) {
  self.roundtrip(self, 'device/' + self.deviceID, { method: 'POST', pathname: '/api' },
                 { username: md5(steward.uuid), devicetype: 'steward' }, function(err, state, response, result) {
    var i, results, errors;

    self.waitingP = false;
    self.timer = setTimeout(function() { self.heartbeat(self); },  1 * 1000);
    logger.debug('pair: ' + state + ' code ' + response.statusCode, { err: stringify(err), result: stringify(result) });

    if ((err) || (state !== 'end')) return;

    if (!!(results = result.results)) {
      for (i = 0; i < results.length; i++) {
        if (results[i].success) {
          self.username = results[i].success.username;
          self.changed();
          db.run('INSERT INTO deviceProps(deviceID, key, value) VALUES($deviceID, $key, $value)',
                         { $deviceID: self.deviceID, $key: 'username', $value: self.username });
          return;
        }
      }
    }

    errors = result.errors;
    for (i = 0; i < errors.length; i++) {
      if (errors[i].type == 101) {
        self.waitingP = true;
        break;
      }
      logger.error('device/' + self.deviceID, { event: 'controller', parameter: 'pair', diagnostic: stringify(errors[i]) });
    }
    self.changed();
  });
};
Example #14
0
router.get('/', function (req, res) {
	if ((req.query.login) && (req.query.password)) {
		req.db.get(collectionName).findOne({
			login: req.query.login,
			password: md5(req.query.password + req.conf.salt)
		}, {
			fields: {
				_id: false,
				key: true,
				role: true
			}
		}, function (e, user) {
			if (user) {
				res.send(user);
			} else {
				res.send({
					status: 'error',
					message: 'User not found'
				});
			}
		});
	} else {
		res.send({
			status: 'error',
			message: 'Missing login and password'
		});
	}
});
Example #15
0
exports.hit = function(userId, page) {

  var type = 'pageview'

  var hashedid = md5(userId)
  var url = 'http://google-analytics.com/collect?' +
            'v='    + '1'           + '&' +
            'tid='  + tracking_id   + '&' +
            'cid='  + hashedid      + '&' +
            't='    + type          + '&' +
            'dh='   + 'meadle.me'   + '&' +
            'dp='   + page

  request({
    'method':'POST',
    'uri': url,

  }, function(err, response, body) {

    if (err) {
      logger.error('Error sending api hit to google analytics')
      logger.error(err)
    }
    
  })

}
Example #16
0
            controller : function(req, res, next){
                var uname = req.body.loginname;
                var passwd = req.body.passwd;
                var nickname = req.body.nickname;
                var errorMsg;

                if(!uname) {
                    errorMsg = '用户名不能为空!';
                } else if(!passwd){
                    errorMsg = '密码不能为空!';
                }

                if(errorMsg) {
                    return res.render('notify/notify', {
                        error : errorMsg
                    });
                }
                userSvc.register({
                    loginname : uname,
                    password : md5(passwd),
                    nickname : nickname
                }, 0, function(err, user){
                    next(err || '注册成功!');                 
                });
            }
Example #17
0
File: user.js Project: GLTYPE/API
exports.createUser = function createUser(req, res) {
    if (!req.body.firstname || req.body.firstname.length == 0 ||
        req.body.firstname.length > 50)
        return res.status(400).end("Error firstname (Caracter number must be between 1 and 50)");
    if (!req.body.lastname || req.body.lastname.length == 0 ||
        req.body.lastname.length > 50)
        return res.status(400).end("Error lastname (Caracter number must be between 1 and 50)");
    if (!req.body.email || req.body.email.length == 0 ||
        req.body.email.length > 50)
        return res.status(400).end("Error email (Caracter number must be between 1 and 50)");
    if (!req.body.role || parseInt(req.body.role) < 0 || parseInt(req.body.role) > 4)
        return res.status(400).end("Error role");
    if (!req.body.password || req.body.password.length < 8 ||
        req.body.password.length > 20)
        return res.status(400).end("Error password (Caracter number must be between 8 and 20)");
    User({
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        picture: req.body.picture ? req.body.picture : "",
        email: req.body.email,
        about: req.body.about ? req.body.about : "",
        role: req.body.role,
        password: md5(req.body.password)
    }).save(function (err, user) {
        if (err) {
            if (err.toString().search("to be unique") != -1) return res.status(400).end("This email already exists");
            console.log(err.toString());
            return res.status(500).end("Internal error");
        }
        res.status(201).json(user);
    });
}
Example #18
0
var parse = function( opt, data, cb ){
    try{
        var $ = opt.window.$;
        var out = {url_list:[], content:undefined, image_list:[]}, lines=[];

        $("#ContentBody >p").each(function(){
            var html = $(this).html().replace(/\(\s*,\s*\)/gi, '');
            var text = $('<p>'+html+'</p>').text().replace(/\r?\n +/g,'').trim();
            if(text.length>0) {
                lines.push(text);
            }
        });
        out.content = lines.join("\r\n");

        out.title = $('.titlebox .newsContent h1').text().trim();

        $("#ContentBody img").each(function(){
            if($(this).attr('src').match(/^http/)) {
                out.image_list.push([$(this).attr('src'), $(this).attr('alt')]);
            }
        });

        //获取分页信息
        out.total_page = 1;
        out.page = 1;

        //内容的标识
        var href_key = data.url.replace(/(-\d+)?\.html$/, "");
        out.content_key = md5(href_key);

        cb( undefined, out );
    }catch(e){
        cb( e.toString() );
    }
};
Example #19
0
 function() {
     var resultFileBuffer = fs.readFileSync(destinationImagePath);
     var hash = md5(resultFileBuffer);
     var expectedHash = '25e530d4b79f9e782cb3662be8713c9a';
     t.equal(hash, expectedHash, 'md5 hash of output image');
     tweetFile.close();
     fs.unlinkSync(tweetFilePath);
 });
Example #20
0
 function() {
     var resultFileBuffer = fs.readFileSync(destinationImagePath);
     var hash = md5(resultFileBuffer);
     var expectedHash = '1f401cfdf414185dc3a16cf4dbf17c9b';
     t.equal(hash, expectedHash, 'md5 hash of output image');
     tweetFile.close();
     fs.unlinkSync(tweetFilePath);
 });
Example #21
0
  $scope.gravatar = function (email) {
    if (!email) {
      return '';
    }

    var hash = md5(email.toLowerCase());
    return 'https://secure.gravatar.com/avatar/' + hash + '?d=identicon';
  }
Example #22
0
function checkSignature(body) {

  var signature = md5(body.LMI_PAYEE_PURSE + body.LMI_PAYMENT_AMOUNT + body.LMI_PAYMENT_NO +
    body.LMI_MODE + body.LMI_SYS_INVS_NO + body.LMI_SYS_TRANS_NO + body.LMI_SYS_TRANS_DATE +
    webmoneyConfig.secretKey + body.LMI_PAYER_PURSE + body.LMI_PAYER_WM).toUpperCase();

  return signature == body.LMI_HASH;
}
    Contact.find({}, function(err, contacts) {
      if (contacts.length === 0) {
        console.log('no contacts found, seeding...');
        var newContact = new Contact({
          email: 'jkat98@gmail.com',
          name: {
              first: 'Jason',
              last: 'Krol'
          },
          phone: '215-123-1234',
          gravatar: md5('jkat98@gmail.com')
        });
        newContact.save(function(err, contact) {
          console.log('successfully inserted contact: ' + contact._id);
        });

        newContact = new Contact({
          email: 'testerson@example.com',
          name: {
            first: 'Steve',
            last: 'Testerson'
          },
          phone: '215-123-1234',
          gravatar: md5('testerson@example.com')
        });
        newContact.save(function(err, contact) {
          console.log('successfully inserted contact: ' + contact._id);
        });

        newContact = new Contact({
          email: 'nancy@testerson.com',
          name: {
            first: 'Nancy',
            last: 'Testerson'
          },
          phone: '215-123-1234',
          gravatar: md5('nancy@testerson.com')
        });
        newContact.save(function(err, contact) {
          console.log('successfully inserted contact: ' + contact._id);
        });
      } else {
        console.log('found ' + contacts.length + ' existing contacts!');
      }
    });
Example #24
0
 models.Image.findOne({ filename: { $regex: req.params.image_id } }, function(err, image) {
     var newComment = new models.Comment(req.body);
     newComment.gravatar = md5(newComment.email);
     newComment.image_id = image._id;
     newComment.save(function(err, comment) {
         if (err) throw err;
         res.redirect('/images/' + image.uniqueId + '#' + comment._id);
     });
 });
Example #25
0
Payment.prototype.getPackage = function (params, options) {
  options = _.defaults((options = options || {}), {
    signOnly: false
  });
  var sorted = cm.sortByKeyCap(params);
  var sign = md5(cm.gbk(cm.toQuerystring(sorted) + '&key=' + this.partnerKey)).toUpperCase();
  return options.signOnly ? sign : cm.toQuerystring(sorted, {
    value: cm.encodeURIComponentWithLowerCase
  }) + '&sign=' + sign;
};
Example #26
0
function checkSignature(body) {

  var signature = body.MNT_ID + body.MNT_TRANSACTION_ID + body.MNT_AMOUNT +
    body.MNT_CURRENCY_CODE + (body.MNT_SUBSCRIBER_ID || '') + (+body.MNT_TEST_MODE ? '1' : '0') + payanywayConfig.secret;

  console.log(signature);
  signature = md5(signature);

  console.log(signature);
  return signature == body.MNT_SIGNATURE;
}
Example #27
0
						.on('invitation_reply', function(e) {
							if(e.answer && Game.players[e.to]) {
								Game.players[e.to].waiting = false;
								Game.players[player.id].waiting = false;

								var roomName = md5(e.me + player.id);
								Game.sockets[player.id].emit('goto_room', roomName);
								Game.sockets[e.to].emit('goto_room', roomName);
								Game.rooms[roomName] = new Room(roomName, [Game.players[e.to], Game.players[player.id]], [Game.sockets[player.id], Game.sockets[e.to]])
							}
						});
Example #28
0
 mongoose.connect('mongodb://localhost/test_in', function () {
     mongoose.connection.db.dropCollection("users");
     mongoose.connection.db.dropCollection("ingredients");
     mongoose.connection.db.dropCollection("accesstokens");
     User({
         firstname: "Thomas",
         lastname: "Lacroix",
         email: "lacroix@gmail.com",
         about: "",
         role: 1,
         password: md5("00000000")
     }).save(function (err, user) {
         if (err) throw err;
     });
     User({
         firstname: "Pierre",
         lastname: "Medard",
         email: "medard@gmail.com",
         about: "",
         role: 3,
         password: md5("00000000")
     }).save(function (err, user) {
         if (err) throw err;
         IdUser = user._id;
         var account = {
             email: "medard@gmail.com",
             password: '00000000'
         };
         request(url)
             .post('/users/connect')
             .type('json')
             .send(JSON.stringify(account))
             .end(function (err, res) {
                 if (err) {
                     throw err;
                 }
                 token = JSON.parse(res.text).token;
                 done();
             });
     });
 });
Example #29
0
 value: function(email) {
   var existingGravatar = this._gravatar;
   if (existingGravatar.indexOf("gravatar.com") > -1) {
     existingGravatar = existingGravatar.replace("https://secure.gravatar.com/avatar/", "");
     this._gravatar = existingGravatar;
   } else if (existingGravatar.indexOf("user_gravatar.png") > -1) {
     this._gravatar = "968b8e7fb72b5ffe2915256c28a9414c";
   } else if (email) {
     this._gravatar = MD5(email);
   }
   return this._gravatar;
 }
Example #30
0
Client.prototype.redirecttransaction = function(attributes, callback) {
  var signature = md5(attributes.transaction.amount + attributes.transaction.currency + this.options.account + this.options.site_id + attributes.transaction.id);
  var body;

  body = ''+
  '<?xml version="1.0" encoding="utf-8"?>'+
  '<redirecttransaction ua="'+this.options.userAgent+'">'+
    '<merchant>'+
      '<account>'+this.options.account+'</account>'+
      '<site_id>'+this.options.site_id+'</site_id>'+
      '<site_secure_code>'+this.options.site_secure_code+'</site_secure_code>'+
      '<notification_url>'+attributes.merchant.notification_url+'</notification_url>'+
      '<redirect_url>'+attributes.merchant.redirect_url+'</redirect_url>'+
      '<cancel_url>'+attributes.merchant.cancel_url+'</cancel_url>'+
      '<close_window>'+attributes.merchant.close_window+'</close_window>'+
    '</merchant>'+
    '<customer>'+
      '<locale>'+attributes.customer.locale+'</locale>'+
      '<ipaddress>'+attributes.customer.ipaddress+'</ipaddress>'+
      '<forwardedip>'+attributes.customer.forwardedip+'</forwardedip>'+
      '<firstname>'+attributes.customer.firstname+'</firstname>'+
      '<lastname>'+attributes.customer.lastname+'</lastname>'+
      '<address1>'+attributes.customer.address1+'</address1>'+
      '<address2>'+attributes.customer.address2+'</address2>'+
      '<housenumber>'+attributes.customer.housenumber+'</housenumber>'+
      '<zipcode>'+attributes.customer.zipcode+'</zipcode>'+
      '<city>'+attributes.customer.city+'</city>'+
      '<state>'+attributes.customer.state+'</state>'+
      '<country>'+attributes.customer.country+'</country>'+
      '<phone>'+attributes.customer.phone+'</phone>'+
      '<email>'+attributes.customer.email+'</email>'+
    '</customer>'+
    '<transaction>'+
      '<id>'+attributes.transaction.id+'</id>'+
      '<currency>'+attributes.transaction.currency+'</currency>'+
      '<amount>'+attributes.transaction.amount+'</amount>'+
      '<description>'+attributes.transaction.description+'</description>'+
      '<var1>'+attributes.transaction.var1+'</var1>'+
      '<var2>'+attributes.transaction.var2+'</var2>'+
      '<var3>'+attributes.transaction.var3+'</var3>'+
      '<items>'+attributes.transaction.items+'</items>'+
      '<manual>'+attributes.transaction.manual+'</manual>'+
      '<gateway>'+attributes.transaction.gateway+'</gateway>'+
      '<daysactive>'+attributes.transaction.daysactive+'</daysactive>'+
    '</transaction>'+
    '<google_analytics>'+
      '<account>'+attributes.google_analytics.account+'</account>'+
    '</google_analytics>'+
    '<signature>'+(attributes.signature || signature)+'</signature>'+
  '</redirecttransaction>';

  this.post(body, callback);
};