示例#1
0
    app.post('/api/clients/edit', function(req, res) {

        if (validator.isHexadecimal(req.body._id)) {

            var checkName = validator.isAlphanumeric(req.body.new_name);
            var checkPassword = validator.isAlphanumeric(req.body.new_password);
            var checkEmail = validator.isEmail(req.body.new_email);
            var checkDevice = validator.isAlphanumeric(req.body.new_device);

            // Check if the new data is valid
            if (checkName & checkPassword & checkEmail & checkDevice) {

                Bill.update({
                        _id: req.body._id
                    }, {
                        $set: {
                            name: req.body.new_name,
                            password: req.body.new_password
                        }
                    },
                    function(err) {
                        if (!err) {
                            res.send("Edited successfully!");
                        } else {
                            res.send("Opss, something went wrong! :( \n\n" + err);
                        }
                    });

            } else {

                res.send("Opss: Invalid data!!");

            }

        } else {
            res.send("Opss: There is no valid data to find the client you want to edit!");
        }
        console.log("Edit Client Method!!");
    });
示例#2
0
exports.findPassword = function findPassword(req, res, next) {
    var email = validator.trim(req.body.email.toString());
    email = email.toLowerCase();
    if (!validator.isEmail(email)) {
        res.render('sign/forget-pass', {
            config: config,
            error: "邮箱地址不正确"
        });
        return;
    }
    //动态生成key和timestamp,存入数据库 重置密码时,做比较
    var retrieveKey = randomString(15);
    var retrieveTime = new Date().getTime();
    User.getUserByEmail(email, function(err, user) {
        if (err) {
            return next(err);
        }
        if (!user) {
            res.render('sign/forget-pass', {
                error: "此邮箱不存在",
                config: config
            });
            return;
        }
        user.retrieve_key = retrieveKey;
        user.retrieve_time = retrieveTime;
        user.save(function(err) {
            if (err) {
                return next(err);
            }
        });
        //发送重置密码邮件
        mail.sendResetPasswordEmail(user.email, retrieveKey, user.name);
        res.render('notify/notify', {
            success: "我们给您发送了一封重置密码的邮件,请在24小时内点击里面的链接来重置密码。",
            config: config
        });
    });
};
	/**
	* check that the phone number and/or email are valid
	* 
	* @param {object} contact form data
	*
	* @return {object | boolean} validation result
	*     true in case the inputs are valid
	*     the error response object in case an invalid input has been found
	*
	*/
	function validateInput(data) {
		debug('validating user input')

		if (data.email === '' && data.phone === ''){
			return {
				status: 400
				, message: '<p>At least an email address or a phone number is needed.</p><p>Please double-check your entry and try again.</p>'
			}
		}
		else if (data.email !== '' && !validator.isEmail(data.email))
			return {
				status: 400
				, message: '<p>Sorry, it seems that you have used an invalid email address.</p><p>Please double-check your entry and try again.</p>'
			}
		else if (data.phone !== '' && !validator.matches(data.phone, /[0-9]/))
			return {
				status: 400
				, message: '<p>Sorry, it seems that you have used an invalid phone number address.</p><p>Please double-check your entry and try again.</p><p>Accepted characters are numbers, space characters and "+".</p>'
			}
		
		return true
	}
exports.postVenmo = function(req, res, next) {
  req.assert('user', 'Phone, Email or Venmo User ID cannot be blank').notEmpty();
  req.assert('note', 'Please enter a message to accompany the payment').notEmpty();
  req.assert('amount', 'The amount you want to pay cannot be blank').notEmpty();

  var errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/api/venmo');
  }

  var token = _.findWhere(req.user.tokens, { kind: 'venmo' });

  var formData = {
    access_token: token.accessToken,
    note: req.body.note,
    amount: req.body.amount
  };

  if (validator.isEmail(req.body.user)) {
    formData.email = req.body.user;
  } else if (validator.isNumeric(req.body.user) &&
    validator.isLength(req.body.user, 10, 11)) {
    formData.phone = req.body.user;
  } else {
    formData.user_id = req.body.user;
  }

  request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) {
    if (err) return next(err);
    if (request.statusCode !== 200) {
      req.flash('errors', { msg: JSON.parse(body).error.message });
      return res.redirect('/api/venmo');
    }
    req.flash('success', { msg: 'Venmo money transfer complete' });
    res.redirect('/api/venmo');
  });
};
示例#5
0
module.exports = function validateLoginInput(data) {
  let errors = {};

  data.email = !isEmpty(data.email) ? data.email : "";
  data.password = !isEmpty(data.password) ? data.password : "";

  if (!Validator.isEmail(data.email)) {
    errors.email = "Email is invalid";
  }
  if (Validator.isEmpty(data.password)) {
    errors.password = "******";
  }

  if (Validator.isEmpty(data.email)) {
    errors.email = "Email field is required";
  }

  return {
    errors,
    isValid: isEmpty(errors)
  };
};
示例#6
0
const authUser = async function(userInfo){//returns token
    let unique_key;
    let auth_info = {};
    auth_info.status = 'login';
    unique_key = getUniqueKeyFromBody(userInfo);

    if(!unique_key) TE('Please enter an email or phone number to login');


    if(!userInfo.password) TE('Please enter a password to login');

    let user;
    if(validator.isEmail(unique_key)){
        auth_info.method='email';

        [err, user] = await to(User.findOne({where:{email:unique_key}}));
        console.log(err, user, unique_key);
        if(err) TE(err.message);

    }else if(validator.isMobilePhone(unique_key, 'any')){//checks if only phone number was sent
        auth_info.method='phone';

        [err, user] = await to(User.findOne({where:{phone:unique_key }}));
        if(err) TE(err.message);

    }else{
        TE('A valid email or phone number was not entered');
    }

    if(!user) TE('Not registered');

    [err, user] = await to(user.comparePassword(userInfo.password));

    if(err) TE(err.message);

    return user;

}
	.post(function(req,res) {
		if (req.session.error){
			var error = req.session.error
			delete req.session.error
		}

		var body = req.body

		if (body.email && body.password) {
			if (validator.isEmail(body.email)) {
				Users.findByEmail(body.email,function(err,user) {
					if (err) {
						res.session.error = err
						res.redirect('back')
					} else if (!user) {
						res.session.error = 'No account with that email'
						res.redirect('back')
					} else {
						if (sha.x2(body.password) == user.password) {
							delete user.password
							req.session.user = user
							res.redirect('/')
						} else {
							res.session.error = 'Password does not match.'
							res.redirect('back')
						}
					}
				})
			} else {
				req.session.error = 'Email is invalid.'
				res.redirect('back')
			}
		} else {
			req.session.error = 'Login request requires an email and password.'
			res.redirect('back')
		}

	})
示例#8
0
 db.users.findByEmail(email, function(err, user){
     if(user && user.activated){
         res.render('userRegistration',
             {msg:'This email already has an account'}
         );
     } else {
         if(!validator.isAlpha(name)){
             return res.render('userRegistration',
                 {msg: 'Name must be alphabets a-z and A-Z only'}
             );
         }
         if(username.length < 6 || !validator.isAlphanumeric(name)){
             return res.render('userRegistration',
                 {msg: 'Username must be at least 6 characters and alphanumeric'}
             );
         }
         if(password.length < 8){
             return res.render('userRegistration',
                 {msg: 'Password must be at least 8 characters'}
             );
         }
         if(!validateNusEmail(email) || !validator.isEmail(email)){
             return res.render('userRegistration',
                 {msg: 'Please enter a valid NUS Email address'}
             );
         }
         sendActivationEmail(name, activationId, email);
         db.users.save(username, password, name, email, userId, activationId, 
             function(err, user){
                 if (err) { throw err; }
                     req.logIn(user, function(err) {
                         if (err) { throw err; }
                         return res.redirect('/account');
                     });
             }
         );
     }
 });
示例#9
0
 return this.validates(field, function(){
   var valid = false;
   var value = this[field];
   
   switch(format){
     case 'email':
       valid = validator.isEmail(value);  
       break;
       
     case 'url':
       valid = validator.isURL(value);
       break;
       
     case 'ip':
       valid = validator.isIP(value);
       break;
       
     case 'uuid':
       valid = validator.isUUID(value);
       break;
       
     case 'date':
       valid = validator.isDate(value);
       break;
       
     case null:
       valid = validator.isNull(value);
       break;
     default:
       valid = validator.matches(value, format);
       break;
   }  
       
   if(value === null && options.allow_null) return true;
   
   if(!valid) this.errors.add(field, 'not a valid format');
   return valid;
 });
示例#10
0
exports.validateLogin = (post) => {

    var username = post.username;
    var password = post.password;

    var inputArray = [username, password];

    if (!security.validateType(inputArray, 'string')) {
        return {
            result: false,
            msg: "An error occured"
        };
    }

    username = xss(username);
    password = xss(password);

    if (username === "" || password === "") {
        return {
            result: false,
            msg: "You need to enter the username and password"
        };
    }

    if (!validation.isEmail(username)) {
        return {
            result: false,
            msg: "The selected username must be an e-mail address"
        };
    }

    return {
        result: true,
        msg: "Success",
        username,
        password
    };
};
示例#11
0
  User.afterRemote('create', function({ req, res }, user, next) {
    debug('user created, sending email');
    if (!user.email || !isEmail(user.email)) { return next(); }
    const redirect = req.session && req.session.returnTo ?
      req.session.returnTo :
      '/';

    var mailOptions = {
      type: 'email',
      to: user.email,
      from: '*****@*****.**',
      subject: 'Welcome to Free Code Camp!',
      redirect: '/',
      text: [
        'Greetings from San Francisco!\n\n',
        'Thank you for joining our community.\n',
        'Feel free to email us at this address if you have ',
        'any questions about Free Code Camp.\n',
        'And if you have a moment, check out our blog: ',
        'medium.freecodecamp.com.\n\n',
        'Good luck with the challenges!\n\n',
        '- the Free Code Camp Team'
      ].join('')
    };

    debug('sending welcome email');
    return Email.send(mailOptions, function(err) {
      if (err) { return next(err); }
      return req.logIn(user, function(err) {
        if (err) { return next(err); }

        req.flash('success', {
          msg: [ "Welcome to Free Code Camp! We've created your account." ]
        });
        return res.redirect(redirect);
      });
    });
  });
示例#12
0
	users.update = function (id, user, accessrole, callback) {

		var id = slugmaker(id);

		var update = {};
		if (user.hasOwnProperty("id")) update.id = user.id;
		if (user.hasOwnProperty("name")) update.name = user.name;
		if (user.hasOwnProperty("email") && validator.isEmail(user.email)) update.email = user.email;
		if (user.hasOwnProperty("url") && validator.isURL(user.url, {protocols: ['http', 'https', 'gopher'], require_tld: true, require_protocol: true})) update.url = user.url;
		if (user.hasOwnProperty("description")) update.description = user.description;
		if (user.hasOwnProperty("location")) update.location = user.location;
		if (user.hasOwnProperty("organisation")) update.organisation = user.organisation;
		if (user.hasOwnProperty("email")) {
			update.gravatar = crypto.createHash('md5').update(user.email.toLowerCase()).digest('hex');
			update.verified = false;
		}

		var _updateUser = function () {
			/* check if nothing to update */
			if (Object.keys(update).length === 0) return callback(null);
			db.collection("users").findAndModify({query: {id: id}, update: {$set: update}, new: true}, function (err, doc) {
				if (err) return callback(err);
				cache[doc.id] = doc;
				callback(err, doc);
			});
		};

		if (user.hasOwnProperty("password") && (accessrole === users.roles.admin)) {
			/* replace password */
			users.password(user.password, function (err, method, key, salt, it, time) {
				if (err) return callback(err);
				update.password = [method, key, salt, it];
				_updateUser();
			});
		} else {
			_updateUser();
		}
	};
示例#13
0
文件: user.js 项目: FCoQ/quibs.org
exports.changeemail = function(req, res) {
	var err = function(msg) {
		res.locals.msg = msg;
		util.redirect(req, res, '/panel');
		return;
	}

	if (!util.isset(req.body.email)) {
		return err("You didn't supply a valid email, try again.");
	}

	var email = req.body.email;
	if (!check.isEmail(email)) {
		return err("You didn't supply a valid email, try again.");
	}

	db.query("UPDATE users SET email=? WHERE id=?", [email, res.locals.__AUTH_USERDATA.id], function(error) {
		if (error) return err("Couldn't update email.");

		res.cookie('email', email, {maxAge: 94636000000})
		err("Email changed!");
	})
}
示例#14
0
        .validateRegistration(function(newUserAttributes) {
            var errors = [];

            if (!newUserAttributes.login) {
                errors.push('Missing username');
            } else if (!validator.isLength(newUserAttributes.login, 3, 10)) {
                errors.push('Username should be 3 to 10 characters long');
            }
            
            if (!newUserAttributes.password) {
                errors.push('Missing password');
            } else if (!validator.isLength(newUserAttributes.password, 3, 8)) {
                errors.push('Password should be 3 to 8 characters long');
            } else if (newUserAttributes.password != newUserAttributes.passwordsignup_confirm) {
                errors.push('Password confirmation does not match');
            }
            
            if ((newUserAttributes.e_mail) && (!validator.isEmail(newUserAttributes.e_mail))) {
                errors.push('A valid email is required');
            }
            
            return errors;
        })
示例#15
0
文件: auth.js 项目: bogdancernat/cliw
    loginEmail: function (req, res) {
      if(req.body.password.length >=5
          && validator.isEmail(req.body.email)) {
        passport.authenticate('local-login', {
          successRedirect: '/',
          failureRedirect: '/'
        })(req, res);

        // passport.authenticate('local-login', function (err, user) {
        //   if(err) {
        //     res.redirect('/login');
        //   } else {
        //     if(user === false) {
        //       res.redirect('/login');
        //     } else {
        //       res.redirect('/');
        //     }
        //   }
        // });
      } else {
        res.redirect('/');
      }
    },
示例#16
0
authenticationController.login = function (req, res, next) {
	if (plugins.hasListeners('action:auth.overrideLogin')) {
		return continueLogin(req, res, next);
	}

	var loginWith = meta.config.allowLoginWith || 'username-email';

	if (req.body.username && utils.isEmailValid(req.body.username) && loginWith.indexOf('email') !== -1) {
		async.waterfall([
			function (next) {
				user.getUsernameByEmail(req.body.username, next);
			},
			function (username, next) {
				req.body.username = username || req.body.username;
				continueLogin(req, res, next);
			},
		], next);
	} else if (loginWith.indexOf('username') !== -1 && !validator.isEmail(req.body.username)) {
		continueLogin(req, res, next);
	} else {
		res.status(500).send('[[error:wrong-login-type-' + loginWith + ']]');
	}
};
app.get('/send',function(req,res){
    var mailOptions={
        to : req.query.to,
        subject : req.query.subject+ ' - ' + 'Message de ' + req.query.name + ' <'+req.query.from+'>',
        text : req.query.text
    }
    console.log(mailOptions);

    if (req.query.name && req.query.from && validator.isEmail(req.query.from) && req.query.text && validator.isLength(req.query.text,1,512) && req.query.subject) {
        transporter.sendMail(mailOptions, function(error, response){
            if(error){
                console.log(error);
                res.end("error");
            } else {
                console.log("Message envoyé: " + response.message);
                res.end("sent");
            }
        });
    } else {
        res.end("error fields");
        console.log("Champs non remplis");
    }
});
示例#18
0
exports.postForgetPass = function(req, res, next) {
    var email = req.body.email;
    email = validator.trim(email);
    if (email === '') {
        return res.render('auth/forgetpass', {error: '请填写注册邮箱地址'});
    }
    if (!validator.isEmail(email)) {
        return res.render('auth/forgetpass', {error: '不正确的邮箱地址'});
    }
    authproxy.getUserByEmail(email, function(err, user) {
        if (err) return next(err);
        if (user) {
            var forgetkey = cryptofun.randomString(15);
            user.forgetkey = forgetkey;
            user.save(function(err) {
                if (err) return next(err);
            });
            //发送重置密码的邮件
            mail.sendResetPassMail(email, forgetkey, user.name);
            return res.render('notify/notify', {success: '我们给你的邮箱发送一封重置密码的邮件,请点击里面的连接以重置密码。'});
        }
    });
};
module.exports = function validateLoginFields(data) {
  let errors = {};
  // checking if data.email is empty. If yes then set data.email=data.email else set to ""
  data.email = !isEmpty(data.email) ? data.email : "";
  data.password = !isEmpty(data.password) ? data.password : "";
  //Compare with isEmail in the other project
  if (!Validator.isEmail(data.email)) {
    errors.email = "Email is invalid";
  }

  if (Validator.isEmpty(data.email)) {
    errors.email = "Email field is required";
  }

  if (Validator.isEmpty(data.password)) {
    errors.password = "******";
  }

  return {
    errors,
    isValid: isEmpty(errors)
  };
};
exports.postSignIn = function* (next) {
  var ctx = this;
  var body = ctx.request.body;

  // Sanitize
  body.username = v.trim(body.username).toLowerCase();

  // body.email = body.username;
  // Validate
  var errors = [];
  if (v.isNull(body.username)) {
    errors.push(['username', 'required']);
  }
  if (v.isNull(body.password)) {
    errors.push(['password', 'required']);
  }
  if (body.username.indexOf('@') !== -1 && !v.isEmail(body.username)) {
    errors.push(['username', 'Invalid email address']);
  }
  if (errors.length > 0) {
    delete body.password;
    ctx.flash = _.defaults({ errors: _.zipObject(errors) }, body);
    return ctx.redirect('/signin');
  }

  yield passport.authenticate('local', function* (error, user, info) {
    if (error) { throw error; }
    if (user === false) {
      errors.push(['error', 'Invalid username/email and password combination']);
      ctx.flash = _.defaults({ errors: _.zipObject(errors) }, body);
      ctx.redirect('/signin');
    } else {
      yield ctx.login(user);
      ctx.redirect('/');
    }
  }).call(this, next);
};
示例#21
0
    value: function validate(value, context) {
      var min = this.getOption('min'),
          max = this.getOption('max'),
          regex = this.getOption('regex'),
          message = this.getOption('message'),
          email = this.getOption('email'),
          url = this.getOption('url');

      if (!_.isString(value) && value !== undefined && value !== null) {
        this.addError('Invalid string');
        return this.getErrors();
      }

      var len = value ? value.length : 0;

      if (min !== undefined && max !== undefined && (len < min || len > max)) {
        this.addError('%(property)s must be less than %(max)d and greater than %(min)d characters');
      } else if (min !== undefined && len < min) {
        this.addError('%(property)s must be greater than %(min)d characters');
      } else if (max !== undefined && len > max) {
        this.addError('%(property)s must be less than %(max)d characters');
      }

      if (regex && !validator.matches(value, regex.pattern || regex)) {
        this.addError(regex.message || '%(value)s does not match ' + (regex.pattern || regex));
      }

      if (email && !validator.isEmail(value)) {
        this.addError(_.isString(email) ? email : '%(value)s is not a valid email');
      }

      if (url && !validator.isURL(value)) {
        this.addError(_.isString(url) ? url : '%(value)s is not a valid url');
      }

      return this.getErrors();
    }
示例#22
0
validator.prototype.validateParams = function (srcObj, params, callback) {
  var errObj = {};
  var paramKeys = Object.keys(params);
  for (i = 0; i < srcObj.length; i++) {
    errObj.code = config.errors.invalid_param.code;
    errObj.message = config.errors.invalid_param.message + " : " + srcObj[i];
    if (paramKeys.indexOf(srcObj[i]) < 0 || !params[srcObj[i]]) {
      errObj.code = config.errors.missing_param.code;
      errObj.message = config.errors.missing_param.message + " : " + srcObj[i];
      return callback(errObj);
    }

    if (srcObj[i] === "email") {
      if (validate.isEmail(params[srcObj[i]]) === false) {
        return callback(errObj);
      }
//    } else if (srcObj[i] === "schedule_time") {
//      if (validate.matches(params[srcObj[i]], /^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})$/) === false) {
//        return callback(errObj);
//      }
    } else if (srcObj[i] === "candidate_exp") {
      if (typeof(params[srcObj[i]]) !== "number") {
        return callback(errObj);
      }
    }else if(srcObj[i] === "tech_round"||srcObj[i] === "manager_round"||srcObj[i] === "hr_round" ){
      if(typeof (params[srcObj[i]]) !== "object"){
        return callback(errObj);
      }
    }
    else {
      if (typeof (params[srcObj[i]]) !== "string") {
        return callback(errObj);
      }
    }
  }
  return callback();
};
示例#23
0
  User.afterRemote('create', function({ req, res }, user, next) {
    debug('user created, sending email');
    if (!user.email || !isEmail(user.email)) { return next(); }
    const redirect = req.session && req.session.returnTo ?
      req.session.returnTo :
      '/';

    var mailOptions = {
      type: 'email',
      to: user.email,
      from: '*****@*****.**',
      subject: 'Welcome to Free Code Camp!',
      protocol: isDev ? null : 'https',
      host: isDev ? 'localhost' : 'freecodecamp.com',
      port: isDev ? null : 443,
      template: path.join(
        __dirname,
        '..',
        'views',
        'emails',
        'a-extend-user-welcome.ejs'
      ),
      redirect: '/email-signin'
    };

    debug('sending welcome email');
    return user.verify(mailOptions, function(err) {
      if (err) { return next(err); }
      req.flash('success', {
        msg: [ 'Congratulations ! We\'ve created your account. ',
               'Please check your email. We sent you a link that you can ',
               'click to verify your email address and then login.'
             ].join('')
      });
      return res.redirect(redirect);
    });
  });
示例#24
0
app.post('/api/register', function (req, res) {
    var re_capcha = req.body['g-recaptcha-response'];
    // console.log(req);
    if (_.isEmpty(re_capcha)) {
        res.json({
            err: true,
            msg: 'Re-capcha is not valid!'
        });
        return;
    }

    var mssv = req.body.msv;
    var email = req.body.email;

    if (!validator.isEmail(email) || mssv.length != 8) {
        res.status(404).json({
            err: true,
            msg: 'Email or Mssv is invalid!'
        });
        return;
    }

    if (!checkParam.checkParamValidate(mssv) || !checkParam.checkParamValidate(email)) {
        res.status(404).json({
            err: true,
            msg: "Something went wrong!"
        });
        return;
    }

    mssv = checkParam.validateParam(mssv);
    email = checkParam.validateParam(email);

    form.form.keysearch = mssv;

    postWithMssv(mssv, email, req, res);
});
示例#25
0
exports.deleteMaintenance = function(req, res) {
  if(!req.session.email || !req.session.siteid) {
    return res.json(401, {message: 'Please sign in.'});
  }
  var email = req.session.email;
  var siteid = req.session.siteid;
  var maintenanceID = req.body.id;
  if(!validator.isEmail(email)) {
    return res.json(400, {message: 'Invalid email.'});
  }
  if(!validator.isUUID(siteid, 4)) {
    return res.json(400, {message: 'Invalid site id.'});
  }
  sites.get(siteid, function (error, reply) {
    if(error) {
      console.log(error);
      return res.json(500, {message: 'Problem deleting new maintenance request.'});
    }
    var deleted = false;
    for(var maintenanceCounter = 0; maintenanceCounter < reply.maintenance.length; maintenanceCounter++) {
      if(reply.maintenance[maintenanceCounter].id === maintenanceID) {
        reply.maintenance.splice(maintenanceCounter, 1);
        deleted = true;
      }
    }
    if(!deleted) {
      return res.json(400, {message: 'Maintenance request does not exist.'});
    }
    sites.insert(reply, siteid, function (error) {
      if(error) {
        console.log(error);
        return res.json(500, {message: 'Problem deleting the maintenance request.'});
      }
      return res.json({message: 'Maintenance request deleted.'});
    });
  });
};
示例#26
0
const validateLoginInput = (data) => {
  let errors = {};

  data.email = !isEmpty(data.email) ? data.email: '';
  data.password = !isEmpty(data.password) ? data.password: '';

  if (!Validator.isEmail(data.email)) {
    errors.email = 'Email is invalid';
  }
  if (Validator.isEmpty(data.email)) {
    errors.email = 'Email field is required';
  }
  if (Validator.isEmpty(data.password)) {
    errors.password = '******';
  }




  return {
    errors,
    isValid: isEmpty(errors)
  }
};
示例#27
0
文件: user.js 项目: thelac/boxplot
router.post('/invite', utils.isLoggedIn, function(req, res, next){
  if (validator.isEmail(req.body.email)) {
    var data = {
      from: "Boxplot <*****@*****.**>",
      to: req.body.email,
      subject: "Join Boxplot!",
      text: "do it boxplot.io"
    };

    global.mg.sendText("*****@*****.**", req.body.email, "Join Boxplot!", "Go to boxplot.io to sign up!", function (err) {
      if (err) {
        res.send(500, "looks like something went wrong!")
      }
      else {
        res.send("invited")
      }
    });
  }

  else {
    res.send(500, "invalid email!")
  }

});
示例#28
0
    function(req, email, password, done) {

		if (!validator.isEmail(email)) {
			return done(null, false, req.flash('signupMessage', 'That email is not valid.'));
		}
		emailExistence.check(email, function(err,res){
			if (!res)
				return done(null, false, req.flash('signupMessage', 'That email does not exist.'));
			// find a user whose email is the same as the forms email
			// we are checking to see if the user trying to login already exists
			db.getUser(email,function(err,rows){
				if (err)
					return done(err);
				 if (rows.length) {
					return done(null, false, req.flash('signupMessage', 'That email is already registered.'));
				} else {

					// if there is no user with that email
					// create the user
					var salt = bcrypt.genSaltSync(10);
					var newUserMysql = new Object();
					newUserMysql.email    = email;
					newUserMysql.password = bcrypt.hashSync(password, salt);
					newUserMysql.salt = salt;
					db.createUser(newUserMysql,function(err,res){
						if(err){
							console.log(err);
							return done(null, false);
						}
						newUserMysql.id = res.insertId;
						return done(null, newUserMysql);
					});
				}	
			});
     	});		
    }));
示例#29
0
router.post('/', isLoggedIn, function(req, res) {

    // Input validation
    if (typeof req.body['first_name'] === 'undefined' || validator.isNull(req.body['first_name'])) return res.json( { status : false, message : "Interviewee name field is empty" });
    else if (typeof req.body['email'] === 'undefined' || validator.isNull(req.body['email'])) return res.json( { status : false, message : "Email field is empty" });
    else if (!validator.isEmail(req.body['email'])) return res.json( { status : false, message : "Invalid Email" });
    else if (typeof req.body['profile'] === 'undefined' || validator.isNull(req.body['profile'])) return res.json( { status : false, message : "Profile field is empty" });

    userId = req.user.id;
    connection.query('USE '+dbconfig.database);
    var date = new Date().toISOString().slice(0, 19).replace('T', ' ');
    console.log(userId);
    console.log(date);
    connection.query("INSERT INTO interview (id, userid, profile, interviewee, datetime) VALUES (NULL, ?, ?, ?, ?);",[req.user.id, req.body['profile'], req.body['first_name'], date],function(err,rows){
        console.log(err);
        if (err) {
            // TODO : Remove err, and add err message
            res.json( { status : true , message : err});
        }
        return res.json( { status : true , message : "Room created successfully"});
    });

    // console.log(req_user);
});
示例#30
0
	function(req, res){
		console.log('Check-email: ', req.body.email);
		var email = req.body.email;
		if(!validator.isEmail(email)){
			return res.json({code: consts.CODE.WRONG_PARAM});
		}

		app
			.get('models')
			.User 
			.findOne({email: email, accountType: consts.ACCOUNT_TYPE.NORMAL})
			.then(function(user){
				console.log(user);
				if (user){
					return res.json({code: consts.CODE.SUCCESS});
				} else {
					return res.json({code: consts.CODE.FAILD, status: consts.CODE.ACCOUNT_NOT_EXIST});
				}
			})
			.catch(function(err){
				console.error(err);
				return res.json({code: consts.CODE.ERROR});
			});
	});