exports.register = (req, res, next) => { let new_user = { phone: req.body.phone, nick_name: req.body.nick_name, passwd: utils.md5(req.body.passwd), } if (!validator.isMobilePhone(new_user.phone, 'zh-CN')) { return res.send({code: 102, msg: response_code['102']}); } let not_complete = _.keys(new_user).some((item) => { return !new_user[item]; }); if (not_complete) { return res.send({code: 113, msg: response_code['113']}); } User.add_user(new_user) .then((data) => { console.log(data); let result = { user_id: data._id, phone: data.phone, nick_name: data.nick_name } res.send({code: 1, msg: response_code['1'], data: result}); }) .catch((e) => { res.send({code: 101, msg: response_code['101']}); }); }
const createUser = async function(userInfo){ let unique_key, auth_info, err; auth_info={} auth_info.status='create'; unique_key = getUniqueKeyFromBody(userInfo); if(!unique_key) TE('An email or phone number was not entered.'); if(validator.isEmail(unique_key)){ auth_info.method = 'email'; userInfo.email = unique_key; [err, user] = await to(User.create(userInfo)); if(err) TE('user already exists with that email'); return user; }else if(validator.isMobilePhone(unique_key, 'any')){//checks if only phone number was sent auth_info.method = 'phone'; userInfo.phone = unique_key; [err, user] = await to(User.create(userInfo)); if(err) TE('user already exists with that phone number'); return user; }else{ TE('A valid email or phone number was not entered.'); } }
isValid() { let validFirstName = this.isInputValid('firstName', 'first name'); let validLastName = this.isInputValid('lastName', 'last name'); let validPhone = this.isInputValid('phone', 'phone number') && validator.isMobilePhone(this.state.phone.replace(/[-() X]/gi, '').trim(), 'en-US'); let validPassword = this.isPasswordValid(); return validFirstName && validLastName && validPassword && validPhone; }
exports.save = function(req, res, verb) { var status = req.body.status; var first_name = req.body.first_name; var last_name = req.body.last_name; var title = req.body.title; var gender = req.body.gender; var job_title = req.body.job_title; var email = req.body.email; var ssn = req.body.ssn; var phone_number = req.body.phone_number; var street = req.body.street; var city = req.body.city; var state = req.body.state; var country = req.body.country; var zip = req.body.zip; var department = req.body.department; var office = req.body.office; var validateFields = { 'status': status == null ? false : validator.isAlphanumeric(status), 'first_name': first_name == null ? false : validator.isAlpha(first_name), 'last_name': last_name == null ? false : validator.isAlpha(last_name), 'title': title == null ? false : validator.isAlpha(title), 'gender': gender == null ? false : validator.isAlpha(gender), 'job_title': job_title == null ? false : validator.isAlphanumeric(validator.blacklist(job_title, ['-', ' ', '.', ','])), 'email': email == null ? false : validator.isEmail(email), 'ssn': ssn == null ? false : validator.isNumeric(validator.blacklist(ssn, '-')), 'phone_number': phone_number == null ? false : validator.isMobilePhone(phone_number, 'en-US'), 'street': street == null ? false : validator.isAlphanumeric(validator.blacklist(street, ['-', ' ', '.', ','])), 'city': city == null ? false : validator.isAlpha(validator.blacklist(city, ['-', ' ', '.', ','])), 'state': state == null ? false : validator.isAlpha(state), 'country': country == null ? false : validator.isAlpha(country), 'zip': zip == null ? false : validator.isNumeric(zip), 'department': department == null ? false : validator.isNumeric(department), 'office': office == null ? false : validator.isNumeric(office) } var valid = true; for(var key in validateFields) { if(!validateFields[key]) { valid = false; } } if(valid) { if(verb == "POST") { var query = 'insert into employees (status, first_name, last_name, title, gender, job_title, email, ssn, phone_number, street, city, state, country, zip, department, office) values ("'+status+'", "'+first_name+'", "'+last_name+'", "'+title+'", "'+gender+'", "'+job_title+'", "'+email+'", "'+ssn+'", "'+phone_number+'", "'+street+'", "'+city+'", "'+state+'", "'+country+'", "'+zip+'", "'+department+'", "'+office+'")'; } else { var query = 'update employees set status="'+status+'", first_name="'+first_name+'", last_name="'+last_name+'", title="'+title+'", gender="'+gender+'", job_title="'+job_title+'", email="'+email+'", ssn="'+ssn+'", phone_number="'+phone_number+'", street="'+street+'", city="'+city+'", state="'+state+'", country="'+country+'", zip="'+zip+'", department="'+department+'", office="'+office+'" where id = '+req.body.id; } connection.query(query, function(err, result) { res.status(201).send(req.body); }); } else { res.status(400).send(JSON.stringify(validateFields)); } }
LogMissedAppointment() { let validFirstName = this.isInputValid('firstName', 'first name'); let validLastName = this.isInputValid('lastName', 'last name'); let validPhone = this.isInputValid('phone', 'phone number') && validator.isMobilePhone(this.state.phone.replace(/[-() X]/gi, '').trim(), 'en-US'); if (validFirstName && validLastName && validPhone) { this.setState({ loading: true }); let customerInfo = { zipcode: this.props.zipcode }; if(isDefined(this.props.email)){ customerInfo.email = this.props.email; } if(isDefined(this.props.expertise)){ customerInfo.expertise = this.props.expertise.toLowerCase(); } if (!isEmpty(this.props.customerId)) { customerInfo.customerId = this.props.customerId; } else { //let dtMoment = moment(this.state.selectedDate.dateObject).format(); customerInfo.customerId = null; customerInfo.first_name = this.state.firstName; customerInfo.last_name = this.state.lastName; customerInfo.phone_number = this.state.phone; //customerInfo.requested_time = dtMoment; } MissedAppointmentsService.addMissedAppointment({ zipcode: customerInfo.zipcode, email: customerInfo.email, customerId: customerInfo.customerId, expertise_filter: customerInfo.expertise_filter, first_name: customerInfo.first_name, last_name: customerInfo.last_name, phone_number: customerInfo.phone_number, requested_time: customerInfo.requested_time }).then(success => { this.setState({ error: {message: ''}, loading: false }); if (!this.state.isCustomer) { this.goToThankYou(); } }, error => { this.setState({ error: {message: 'Error adding to missed appointment.'}, loading: false }); }); } }
exports.login = (req, res, next) => { let result = {}; let opts = { maxAge: 1000 * 60 * 60 * 24 * 30, signed: true, httpOnly: true }; if (!req.body.passwd) { return res.send({code: 112, msg: response_code['112']}); } let phone = validator.trim(req.body.phone); let passwd = validator.trim(req.body.passwd); passwd = utils.md5(passwd); if (!validator.isMobilePhone(phone, 'zh-CN')) { return res.send({code: 102, msg: response_code['102']}); } User.get_user({phone: phone}, (err, data) => { if (!data) { return res.send({code: 103, msg: response_code['103']}); } else { if (data.passwd !== passwd) { return res.send({code: 104, msg: response_code['104']}); } // 将管理员 id 存进 session 和 cookie req.session.user = {user_id: data._id}; res.cookie(config.auth_cookie_name, data._id, opts); result = { user_id: data._id, avrtar: data.avatar, phone: data.phone, nick_name: data.nick_name, school: data.school, sex: data.sex, purpose: data.purpose }; return res.send({code: 1, msg: response_code['1'], data: result}); } }); };
function (account, password, done) { var search={}; if(validator.isEmail(account)){ search.email=account; }else if(validator.isMobilePhone(account,'zh-CN')){ search.mobile=account; }else{ search.name=account } User.findOne(search, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false,{ message: 'Incorrectusername' }); } if (!user.verifyPassword(password)) { return done(null, false,{ message: 'Incorrectpassword' }); } return done(null, user,{ message: 'success' }); }); }
_onPurchaseSuccess(order, cb) { console.log('in-app purchase successful', JSON.stringify(order)) var self = this var price = self._orderTotal() var params = Object.assign({ category: self.props.category.slug, price: Math.floor(price * 100), desc: 'blast of ' + self.state.size + ' mms messages', platform: Platform.OS, transactionId: order.transactionId, receipt: order.receipt, user: Device.identifierForVendor, }, self.state) params.toNumber = self._sanitizeNumber(params.toNumber) if (!validator.isMobilePhone(params.toNumber, 'en-US') && params.toNumber.charAt(0) !== '+' && params.toNumber.length > 10) { params.toNumber = '+' + params.toNumber } if (order.toName) params.toName = order.toName return OrderService.create(params) .then(() => { Alert.alert('Success', 'Your order\'s been placed successfully! The recipient should start receiving messages shortly. You can check the status of your order at any time from the top menu.') self.setState({ toNumber: "", toName: "" }) cb([]) }) .catch((err) => { console.log('error initializing order', err) Alert.alert('Error', `Error initializing order. Please double-check the recipient number ${params.toNumber} or contact support@seshapp.com with transaction ID ${order.transactionId}.`) cb([]) }) }
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; }
return exists(value) && validator.isEmail(value); }, alpha(value/*, options */) { return exists(value) && validator.isAlpha(value); }, base64(value/*, options */) { return exists(value) && validator.isBase64(value); }, hex(value/*, options */) { return exists(value) && validator.isHexadecimal(value); }, alpha_numeric(value/*, options */) { return exists(value) && validator.isAlphanumeric(value); }, phone(value/*, options */) { return exists(value) && validator.isMobilePhone(value, 'en-GB'); }, 'function': function(value/*, options */) { return exists(value) && isFunction(value) && _.isFunction(value); }, date(value/*, options */) { return exists(value) && ( _.isDate(value) || validateMoment(value, [ "YYYY-MM-DD", "DD-MM-YYYY" ]) ); }, time(value/*, options */) { return exists(value) && validateMoment(value, [ "HH:mm", "HH:mm:ss", "HH:mm:ssZ", "HH:mm:ssZZ",
_isMobilePhoneValid(number) { number = this._sanitizeNumber(number) return number && (validator.isMobilePhone(number, 'en-US') || (number.length >= 10 && number.length <= 13)) }
Validator.prototype.isMobilePhone = function(tip,locale) { if (this.goOn && (!isString(this.value) ||!v.isMobilePhone(this.value,locale))) { this.addError(tip || this.key + " is not a mobile phone format."); } return this; };
userMobile : function (mobile, next){ if (!validator.isMobilePhone(mobile, 'zh-CN')) return throw409(code.user.mobileWrong.code, code.user.mobileWrong.message, code.user.mobileWrong.field, next); },
exports.resetMobilePassword = function (req, res) { var phone = req.params.phone var sms = req.body.sms; var password = req.body.password; if(!password) password = "******"; logger.debug('check if phone and sms are all set'); if (phone === '' || sms==='') { resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: '信息不完整。', phone: phone}); return; } logger.debug('check if sms is valid, smsText: ' + sms); logger.debug(global.smsMap); if (global.smsMap[phone]!=sms) { resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: '手机验证码不正确。', sms: sms}); return; } logger.debug('check if password length >= 8'); if (password.length < 8) { resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: '密码长度必须大于或等于8位', phone: phone}); return; } logger.debug('check if phone is exist, phone: ' + phone); //TODO userProxy.findUserByPhone(phone).then(function (user) { if (!user) { resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: '不能重置密码,因为用户账号不存在,请先注册', action:'/signup',phone: phone}); } else { logger.debug('all check passed'); logger.debug('try to reset user password'); //TODO //var newPwd = "p0o9i8u7"; user.password = crypto.md5(password); return userProxy.saveUser(user).then(function () { resUtil.render(req, res, 'signup', { success: '密码已经重置,请返回主页登陆', action: '/signin' }); }); // return userProxy.changePassword(email, password).then(function (email) { // logger.debug('try to send a mail to change password, mail: ' + email); // //return email; // return mailer.sendActiveMail(user.email); // }).then(function (email) { // resUtil.render(req, res, 'signup', { // success: '您的密码已经重置!我们已给您的注册邮箱 ' + email + ' 发送了一封邮件,登陆后尽快修改密码。' // }); // }); } }).fail(function (err) { logger.error(err); resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: '出错啦,请稍后再试'}); }); if (!validator.isMobilePhone(phone,'zh-CN')) { resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: '不正确的手机号码', phone: phone}); return; } logger.info(phone); }
exports.resetPassword = function (req, res) { var registry = req.body.registry; var captcha = req.body.captcha; if(registry === 'phone'){ var phone = req.body.phone; if (phone === '' || captcha === '') { resUtil.render(req, res, 'forgot_password', {error: '信息不完整。', phone: phone}); return; } logger.debug('check if phone is valid, phone: ' + phone); if (!validator.isMobilePhone(phone,'zh-CN')) { resUtil.render(req, res, 'forgot_password', {error: '不正确的手机号。', phone: phone}); return; } logger.debug(req.session.capText); logger.debug('check if captcha is valid, captcha: ' + captcha + ' with generated Code '+req.session.capText); if (req.session.capText.toLowerCase()!=captcha.toLowerCase()) { resUtil.render(req, res, 'forgot_password', {error: '图形验证码不正确。', captcha: captcha}); return; } req.body.type="resetPwd"; signUp.sms(req,res,function(data){ if(data.success){ resUtil.render(req, res, 'confirm_mobile_pass_reset',{ phone: req.body.phone }); }else{ resUtil.render(req, res, 'confirm_mobile_pass_reset', {error: data.msg, phone: phone}); } }); } else{ var email = req.body.email; var password = req.body.password; if(!password) password = "******"; logger.debug('check if email address is exist, email: ' + email); if (email === '') { resUtil.render(req, res, 'forgot_password', {error: '邮箱未填写', email: email}); return; } logger.debug('check if captcha is exist'); if (captcha === '') { resUtil.render(req, res, 'forgot_password', {error: '请输入图形验证码', email: email}); return; } logger.debug(req.session.capText); logger.debug('check if captcha is valid, captcha: ' + captcha + ' with generated Code '+req.session.capText); if (req.session.capText.toLowerCase()!=captcha.toLowerCase()) { resUtil.render(req, res, 'forgot_password', {error: '图形验证码不正确。', captcha: captcha}); return; } //TODO userProxy.findUserByEmail(email).then(function (user) { if (!user) { resUtil.render(req, res, 'forgot_password', {error: '不能重置密码,因为用户账号不存在或还未激活', email: email}); } else { logger.debug('all check passed'); logger.debug('try to reset user password'); //TODO var newPwd = "p0o9i8u7"; user.password = crypto.md5(newPwd); return userProxy.saveUser(user).then(function () { logger.debug('try to send a mail to change password, mail: ' + email); return mailer.sendResetPwdMail(email, newPwd); }).then(function (email) { resUtil.render(req, res, 'signup', { success: '密码重置邮件已发送至你的邮箱:' + email + ' 请尽快登录你的邮箱接收邮件,链接激活后可重置密码。' }); }); } }).fail(function (err) { logger.error(err); resUtil.render(req, res, 'forgot_password', {error: '出错啦,请稍后再试'}); }); if (!validator.isEmail(email)) { resUtil.render(req, res, 'forgot_password', {error: '不正确的电子邮箱。', email: email}); return; } logger.info(email); } }
validate: (val) => validator.isMobilePhone(val, locale)
new JSONAPIDeserializer({keyForAttribute: 'camelCase'}).deserialize(req.body, function(err, user) { if (err) { return next(err); } // id if (!user.id || user.id != req.uid) { return res.json(error('数据异常', 'id信息不存在或不正确!')); } // name if (user.name) { if (validator.isLength(user.name, {min:6, max: 18})) { tmpUser['name'] = user.name; funcs.push(User.getUserByNameExceptSelfAsync(user.id, user.name).then((data)=>{ if (data) { return error('数据异常', '新更改的用户登录名已被注册,请更换!'); } })); } else { return res.json(error('数据异常', '用户登录名至少6个字符,最多18个字符!')); } } // nickName if (user.nickName) { if (validator.isLength(user.nickName, {min:1, max: 18})) { tmpUser['nickName'] = user.nickName; } else { return res.json(error('数据异常', '用户昵称至少1个字符,最多18个字符!')); } } // email if (user.email) { if (validator.isEmail(user.email)) { tmpUser['email'] = user.email; funcs.push(User.getUserByEmailExceptSelfAsync(user.id, user.email).then((data)=>{ if (data) { return error('数据异常', '新更改的Email已被注册,请更换!'); } })); } else { return res.json(error('数据异常', 'Email格式不正确!')); } } // mphone if (user.mphone) { if (validator.isMobilePhone(user.mphone, 'zh-CN')) { tmpUser['mphone'] = user.mphone; funcs.push(User.getUserByMphoneExceptSelfAsync(user.id, user.mphone).then((data)=>{ if (data) { return error('数据异常', '新更改的手机号码已被注册,请更换!'); } })); } else { return res.json(error('数据异常', '手机号码格式不正确!')); } } // password if (user.oldPass) { if (validator.isLength(user.oldPass, {min:6, max: 18})) { tmpUser['oldPass'] = user.oldPass; funcs.push(User.getUserByIdPassAsync(user.id, hashcrypt.sha1(user.oldPass + CONFIG.serverSalt)).then((data)=>{ if (!data) { return error('数据异常', '原用密码不正确!'); } })); } else { return res.json(error('数据异常', '原用密码至少6个字符,最多18个字符!')); } } if (user.newPass) { if (validator.isLength(user.newPass, {min:6, max: 18})) { tmpUser['newPass'] = user.newPass; tmpUser['password'] = hashcrypt.sha1(user.newPass + CONFIG.serverSalt); } else { return res.json(error('数据异常', '新设密码至少6个字符,最多18个字符!')); } } // state // familyId // screenId if (funcs.length > 0) { Promise.all(funcs) .then((datas) => { // datas = [null, obj] var errs = []; datas.forEach(function(data) { if (data) { errs.push(data); } }); if (errs.length > 0) { res.json(errs[0]); } else { User.updateOneAsync(user.id, tmpUser) .then((data) => { // user name & pass save in client. var user = data[0]; user['key'] = hashcrypt.encrypt(user._id + '\t' + user.name + '\t' + user.password, CONFIG.clientSecret); res.json(UserSerializer.serialize(user)); }) .catch((err) => { return next(err); }); } }) .catch((err) => { return next(err); }); } else { User.updateOneAsync(user.id, tmpUser) .then((data) => { // user name & pass save in client. var user = data[0]; user['key'] = hashcrypt.encrypt(user._id + '\t' + user.name + '\t' + user.password, CONFIG.clientSecret); res.json(UserSerializer.serialize(user)); }) .catch((err) => { return next(err); }); } });
}, // 校验用户名 checkUserName(str) { return /^[a-zA-Z][a-zA-Z0-9_]{4,11}$/.test(str); }, // 校验中文GBK checkName(str, min = 2, max = 6) { return str && validator.isLength(str, min, max) && /[\u4e00-\u9fa5]/.test(str); }, // 校验密码 checkPwd(str, min = 6, max = 32) { return str && validator.isLength(str, 5, max) && /(?!^\\d+$)(?!^[a-zA-Z]+$)(?!^[_#@]+$).{6,}/.test(str); }, // 校验邮箱 checkEmail(str) { return str && validator.isEmail(str); }, // 校验手机号 checkPhoneNum(str) { return str && validator.isMobilePhone(str.toString(), 'zh-CN'); }, // 校验QQ号 checkQqNum(str) { return RegExp(/^[1-9][0-9]{4,9}$/).test(str); }, checkUrl(str) { return str && validator.isURL(str); } }
function (err, users, fields) { if (err){ console.log(err); return res.status(500).json({ status: 'error', error: 'Error while reading database' }) } if (users.length < 1){ return res.status(400).json({ status: 'error', error: 'Invalid userId' }); } var user = users[0]; // console.log(user); if (!bcrypt.compareSync(oldPassword, user.password)){ return res.status(200).json({ status: 'error', error: 'Wrong password' }) } var sqlQuery = 'UPDATE users SET status = ?, '; var queryBuilderData = [true]; if (rb.fullname){ sqlQuery += 'fullname = ?, '; queryBuilderData.push(rb.fullname); } if (rb.phone){ if (!validator.isMobilePhone(rb.phone, 'vi-VN')){ return res.status(200).json({ status: 'error', error: 'Invalid phone number' }) } sqlQuery += 'phone = ?, '; queryBuilderData.push(rb.phone); } if (rb.address){ sqlQuery += 'address = ?, '; queryBuilderData.push(rb.address); } if ('gender' in rb){ sqlQuery += 'gender = ?, '; queryBuilderData.push(rb.gender); } if ('birthday' in rb){ sqlQuery += 'birthday = ?, '; queryBuilderData.push(rb.birthday); } if (newPassword && newPassword.length > 0){ console.log('checking new password'); // check new password if (!validator.isLength(newPassword + '', {min: 6, max: 30})){ res.status(400).json({ status: 'error', error: 'Password length must greater than 5 and less than 31' }) return; } if (newPassword.localeCompare(repeatPassword) !== 0){ res.status(400).json({ status: 'error', error: 'Password not match' }) return; } console.log('done new password'); newPassword = bcrypt.hashSync(newPassword, bcrypt.genSaltSync(8), null); sqlQuery += 'password = ?, '; queryBuilderData.push(newPassword); } var token = makeToken(user.email); sqlQuery += 'token = ? WHERE id = ?'; queryBuilderData.push(token, userId); connection.query( sqlQuery, queryBuilderData, function (error, result) { if (error){ console.log(error); return res.status(200).json({ status: 'error', error: 'Error while writing on database' }); } return res.status(200).json({ status: 'success', user: { id: userId, email: user.email, fullname: rb.fullname ? rb.fullname : user.fullname, status: true, token: token, address: rb.address ? rb.address : user.address, phone: rb.phone ? rb.phone : user.phone } }) } ) }
Validator.mobile = (value, locale = 'zh-CN') => { return !value || validator.isMobilePhone(value, locale); };