Authored by 陈峰

Merge branch 'gray' into 'master'

Gray



See merge request !20
... ... @@ -2,12 +2,12 @@
# Created by https://www.gitignore.io/api/node,webstorm,netbeans,sublimetext,vim
### Node ###
# Logs
!logs/README.md
# Logs
!logs/README.md
logs
*.log
npm-debug.log*
npm-debug.log*
# Runtime data
pids
*.pid
... ... @@ -141,3 +141,4 @@ public/bundle/*
.eslintcache
*.log.*
.vscode/
connection-parse/
\ No newline at end of file
... ...
... ... @@ -12,13 +12,16 @@ if (config.useOneapm) {
require('oneapm');
}
const _ = require('lodash');
const express = require('express');
const path = require('path');
const uuid = require('uuid');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
const session = require('client-sessions');
const CookieSession = require('client-sessions');
const MemcachedSession = require('yoho-express-session');
const memcached = require('connect-memcached');
const MemcachedStore = memcached(MemcachedSession);
const hbs = require('express-handlebars');
const multer = require('connect-multiparty');
const pkg = require('./package.json');
... ... @@ -54,21 +57,71 @@ app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(multer());
app.use(session({
requestKey: 'session',
cookieName: 'yohoblk-session',
app.use(MemcachedSession({ // eslint-disable-line
proxy: true,
resave: false,
saveUninitialized: true,
unset: 'destroy',
secret: '82dd7e724f2c6870472c89dfa43cf48d',
domain: config.cookieDomain
name: 'yohoblk_session',
cookie: {
domain: config.cookieDomain,
httpOnly: false
},
store: new MemcachedStore({
hosts: config.memcache.session,
prefix: 'yohoblk-session:',
reconnect: 5000,
timeout: 1000,
retries: 0
})
}));
app.use(CookieSession({ // eslint-disable-line
requestKey: 'session2',
cookieName: 'yohoblk_session_cookie',
secret: '82dd7e724f2c6870472c89dfa43cf48d',
cookie: {
domain: config.cookieDomain,
ephemeral: true
}
}));
app.use((req, res, next) => {
if (req.session) {
let sessionKeys = Object.keys(req.session || {});
let backSessionKeys = Object.keys(req.session2.sessionBack || {});
if (backSessionKeys.length > sessionKeys.length) {
let differences = _.difference(backSessionKeys, sessionKeys);
_.forEach(differences, d => {
req.session[d] = req.session2.sessionBack[d];
});
}
req.session2.sessionBack = req.session;
} else {
req.session = new MemcachedSession.Session(req);
req.session.cookie = new MemcachedSession.Cookie({
domain: 'yohoblk.com',
httpOnly: false
});
req.session = _.assign(req.session, req.session2.sessionBack);
}
if (typeof req.session.reset !== 'function') {
req.session.reset = function() {
req.session = null;
req.session2.reset();
};
}
next();
});
app.use((req, res, next) => {
req.user = {}; // 全局的用户数据
req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等
if (!req.session || !req.session.uuid) {
req.session = {
uuid: uuid.v4()
};
if (!req.session) {
req.session = {};
}
next();
});
... ...
... ... @@ -9,6 +9,7 @@
const editorialModel = require('../models/editorial');
const md5 = require('md5');
const config = global.yoho.config;
const helper = global.yoho.helpers;
/**
* 资讯首页数据
... ... @@ -83,7 +84,7 @@ const index = (req, res, next) => {
const list = (req, res, next) => {
let pageNum = req.query.page || 1;
let limit = req.query.limit || 20;
let tag = req.query.query;
let tag = helper.xssHtml(req.query.query);
let authorId = req.query.authorId;
let udid = md5(req.ip);
let channel = req.cookies._Channel || 'men';
... ... @@ -132,10 +133,10 @@ const list = (req, res, next) => {
},
{
pathTitle: '资讯',
name: req.query.query || result.authorName
name: tag || result.authorName
}
],
pathTitle: req.query.query || result.authorName,
pathTitle: tag || result.authorName,
msg: result.tabs,
paginationOpts: {
page: pageNum, // current page: //host/?page=2
... ...
... ... @@ -166,6 +166,7 @@ const bindMobile = (req, res, next) => {
settingModel.getUserInfo(uid).then(result => {
if (result.info.verify_mobile !== '') {
req.session.modify_phone = {mobile: result.info.verify_mobile};
return mcHandler.getMeThumb().then((thumb) => {
let info = result.info;
... ... @@ -205,6 +206,7 @@ const bindEmail = (req, res, next) => {
settingModel.getUserInfo(uid).then(result => {
if (result.info.verify_email !== '') {
req.session.modify_email = {email: result.info.verify_email};
let info = result.info;
info.ellipsisEmail = info.verify_email.replace(regEmail, '$1****');
... ... @@ -265,7 +267,7 @@ const modifyType = (req, res, next) => {
const edit = (req, res, next) => {
let type = req.params.type;
if (Number(cookieHelper.getVal(req, type + '_STEP')) !== 1) {
if (Number(cookieHelper.getVal(req, type + '_STEP')) !== 1 || !req.session.safeAccount) {
res.redirect(helpers.urlFormat('/me/setting/step1/' + type));
return;
}
... ... @@ -357,12 +359,22 @@ const validate1 = (req, res, next) => {
if (type === 'password') {
a = yield accountModel.verifyPwd(uid, body.password);
} else if (type === 'mobile') {
if (req.session.modify_phone.mobile !== body.mobile) {
return res.send({code: 400});
}
a = yield accountModel.checkVerifyMsg(body.code, body.mobile, body.area);
} else if (type === 'email') {
if (req.session.modify_email.email !== body.email) {
return res.send({code: 400});
}
a = yield accountModel.sendVerifyEmail(uid, body.email);
}
if (a) {
if (a.code === 200) {
req.session.safeAccount = true;
}
cookieHelper.setVal(res, req.body.type + '_STEP', 1);
res.send(a);
}
... ... @@ -378,36 +390,54 @@ const validate2 = (req, res, next) => {
let uid = req.user.uid;
let body = req.body;
if (!req.session.safeAccount) {
return res.send({
code: 400,
message: '修改失败,请重新验证身份'
});
}
if (type === 'password') {
let a = yield accountModel.changePwd(uid, body.password);
if (a.code === 200) {
req.session.safeAccount = false;
cookieHelper.setVal(res, body.type + '_STEP', 2);
res.send(a);
}
} else if (type === 'mobile') {
let a = yield accountModel.checkVerifyMsg(body.code, body.mobile, body.area);
let b = yield accountModel.modifyVerifyMobile(uid, body.area, body.mobile);
if (a.code === 200 && b.code === 200) {
cookieHelper.setVal(res, body.type + '_STEP', 2);
res.send({
code: 200,
data: {}
});
} else {
let msg = [];
if (a.code !== 200) {
msg.push('<p>图片验证:' + a.message + '</p>');
}
if (b.code !== 200) {
msg.push('<p>修改号码:' + a.message + '</p>');
let b = yield accountModel.checkVerifyMobile(uid, body.mobile, body.area);
if (b.code === 200) {
let a = yield accountModel.checkVerifyMsg(body.code, body.mobile, body.area);
if (a.code === 200) {
let c = yield accountModel.modifyVerifyMobile(uid, body.area, body.mobile);
cookieHelper.setVal(res, body.type + '_STEP', 2);
if (c.code === 200) {
req.session.safeAccount = false;
res.send({
code: 200,
data: {}
});
} else {
res.send({
code: 500,
message: c.message
});
}
} else {
res.send({
code: 500,
message: '<p>短信验证:' + a.message + '</p>'
});
}
} else {
res.send({
code: 500,
message: msg.join('')
message: '<p>修改号码:' + b.message + '</p>'
});
}
}
... ...
... ... @@ -82,6 +82,15 @@ const getUserInfoAPI = (req, res, next) => {
const sendCodePage = (req, res, next) => {
let inputInfo = req.inputInfo;
if (req.session.mobile && req.session.mobile !== inputInfo.phone) {
req.session.mobile = '';
req.session.captcha = '';
return res.json({
code: 400,
message: '验证码失效',
data: ''
});
}
BackService.sendCodeToUserAsync(inputInfo.type, inputInfo.phone, inputInfo.area)
.then(result => {
if (!(result.code && result.code === 200)) {
... ... @@ -121,8 +130,21 @@ const sendBackMobileAPI = (req, res, next) => {
let mobile = req.body.mobile || '';
let area = req.body.area || '86';
// 检查上次的发送短信号码
if (req.session.mobile && req.session.mobile !== mobile) {
req.session.mobile = '';
req.session.captcha = '';
return res.json({
code: 400,
message: '验证码失效',
data: ''
});
}
BackService.sendCodeToMobileAsync(area, mobile)
.then(result => {
// 记录发送短信的号码
req.session.mobile = mobile;
res.json(result);
})
.catch(next);
... ...
... ... @@ -247,9 +247,22 @@ const bindCheck = (req, res, next) => {
const sendBindMsg = (req, res, next) => {
let mobile = req.body.mobile;
let area = req.body.area;
let verifyCode = req.body.verifyCode;
if (req.session.autouserinfoMobile && req.session.autouserinfoMobile !== mobile || verifyCode !== req.session.captcha) {//eslint-disable-line
req.session.autouserinfoMobile = '';
req.session.captcha = '';
return res.json({
code: 400,
message: '验证码失效'
});
}
BindService.sendBindMsgAsync(area, mobile).then(result => {
if (result && result.code) {
req.session.autouserinfoMobile = mobile;
req.session.thirdBind = {
mobile: mobile
};
res.json(result);
} else {
res.json({ code: 400, message: '', data: '' });
... ... @@ -284,25 +297,29 @@ const bindMobile = (req, res, next) => {
let sourceType = _.trim(req.body.sourceType);
let password = _.trim(req.body.password) || '';
BindService.bindMobileAsync(openId, sourceType, mobile, area, password).then(result => {
if (result && result.code) {
if (result.code === 200 && result.data && result.data.uid) {
let refer = helpers.urlFormat('/passport/thirdlogin/bindsuccess', {
sourceType: sourceType + '_bind'
});
return LoginService.syncUserSession(result.data.uid, req, res).then(() => {
return { code: 200, message: result.message, data: { refer: refer } };
});
if (req.session.thirdBind && req.session.thirdBind.mobile === mobile) {
BindService.bindMobileAsync(openId, sourceType, mobile, area, password).then(result => {
if (result && result.code) {
if (result.code === 200 && result.data && result.data.uid) {
let refer = helpers.urlFormat('/passport/thirdlogin/bindsuccess', {
sourceType: sourceType + '_bind'
});
return LoginService.syncUserSession(result.data.uid, req, res).then(() => {
return { code: 200, message: result.message, data: { refer: refer } };
});
} else {
return { code: result.code, message: result.message, data: { refer: '' } };
}
} else {
return { code: result.code, message: result.message, data: { refer: '' } };
return { code: 400, message: '', data: '' };
}
} else {
return { code: 400, message: '', data: '' };
}
}).then(result => {
res.json(result);
}).catch(next);
}).then(result => {
res.json(result);
}).catch(next);
} else {
res.json({ code: 400, message: '', data: '' });
}
};
/**
... ... @@ -314,25 +331,30 @@ const relateMobile = (req, res, next) => {
let areaCode = req.body.areaCode || '86';
let sourceType = req.body.sourceType;
BindService.relateMobileAsync(openId, sourceType, mobile, areaCode).then(result => {
if (result && result.code) {
if (result.code === 200 && result.data && result.data.uid) {
let refer = helpers.urlFormat('/passport/thirdlogin/relatesuccess', {
sourceType: sourceType + '_bind'
});
return LoginService.syncUserSession(result.data.uid, req, res).then(() => {
return { code: 200, message: result.message, data: { refer: refer } };
});
if (req.session.thirdBind && req.session.thirdBind.mobile === mobile) {
BindService.relateMobileAsync(openId, sourceType, mobile, areaCode).then(result => {
if (result && result.code) {
if (result.code === 200 && result.data && result.data.uid) {
let refer = helpers.urlFormat('/passport/thirdlogin/relatesuccess', {
sourceType: sourceType + '_bind'
});
return LoginService.syncUserSession(result.data.uid, req, res).then(() => {
req.session.thirdBind = '';
return { code: 200, message: result.message, data: { refer: refer } };
});
} else {
return { code: result.code, message: result.message, data: { refer: '' } };
}
} else {
return { code: result.code, message: result.message, data: { refer: '' } };
return { code: 400, message: '', data: '' };
}
} else {
return { code: 400, message: '', data: '' };
}
}).then(result => {
res.json(result);
}).catch(next);
}).then(result => {
res.json(result);
}).catch(next);
} else {
res.json({ code: 400, message: '', data: '' });
}
};
module.exports = {
... ...
... ... @@ -57,6 +57,7 @@ const generate = (req, res) => {
let length = +(req.query.l || 4);
let captcha = captchaService.generateCaptcha(width, height, length);
req.session.sendMobile = '';
req.session.captcha = captcha.text;
req.session.captchaCount = 0;
... ...
... ... @@ -242,7 +242,21 @@ const local = {
});
}
if (req.session.sendMobile && req.session.sendMobile !== mobile) { // ajax中判断
req.session.sendMobile = '';
req.session.captcha = '';
return res.json({
code: 400,
message: '验证码已失效'
});
}
LoginService.sendPasswordBySMS(area, mobile).then((result) => {
if (result && result.code === 200) {
req.session.captcha = '';
req.session.sendMobile = mobile;
}
return res.json(result);
}).catch(next);
},
... ...
... ... @@ -154,10 +154,13 @@ let sendBindMsg = (req, res, next) => {
let area = req.body.area;
// 检查是否检查过
let checkNum = yield cache.get(`regCheckMobileNum_${mobile}`);
// let checkNum = yield cache.get(`regCheckMobileNum_${mobile}`);
if (!checkNum) {
data.message = '发送失败';
// 检查上次的发送短信号码
if (req.session.sendMobile_reg && req.session.sendMobile_reg !== mobile) {
req.session.sendMobile_reg = '';
req.session.captcha = '';
data.message = '验证码失效';
return res.json(data);
}
... ... @@ -176,6 +179,8 @@ let sendBindMsg = (req, res, next) => {
return cache.set(sendCodeKey, sendCodeTimes + 1, 3600).then(() => {
if (result.code) {
// 记录发送短信的号码
req.session.sendMobile_reg = mobile;
return res.json(result);
} else {
data.message = '发送失败';
... ...
... ... @@ -26,6 +26,12 @@ const cache = global.yoho.cache;
let siteUrl = config.siteUrl.indexOf('//') === 0 ? 'http:' + config.siteUrl : config.siteUrl;
function getLoginStat(ip) {
let errorLoginKey = 'loginErrorIp:' + ip;
return cache.get(errorLoginKey);
}
// 本地登录
passport.use('local', new LocalStrategy({
usernameField: 'account',
... ... @@ -34,81 +40,67 @@ passport.use('local', new LocalStrategy({
}, (req, username, password, done) => {
let area = req.body.areaCode || '86';
let type = req.body.loginType;
let clientIp = req.yoho.clientIp;
let errorLoginKey = 'loginErrorIp:' + clientIp;
return getLoginStat(clientIp).then((times) => {
let errLoginTimes = _.parseInt(times) || 0;
let verifyCode = req.body.captcha;
if (errLoginTimes > 0 && type !== 'SMSLogin') {
if (!verifyCode || verifyCode !== req.session.captcha) {
return done({message: '验证码不正确或验证码过期', needCaptcha: true}, null);
}
}
if (isNaN(_.parseInt(area)) || _.isEmpty(username) || _.isEmpty(password)) {
logger.info(`【Passport Loginbad params, area:${area} account:${username} password:${password}`);
return done({message: '登录参数错误'}, null);
}
if (isNaN(_.parseInt(area)) || _.isEmpty(username) || _.isEmpty(password)) {
logger.info(`【Passport Loginbad params, area:${area} account:${username} password:${password}`);
return done({message: '登录参数错误'}, null);
}
let verifyEmail = helpers.verifyEmail(username);
let verifyMobile = area === '86' ? helpers.verifyAreaMobile(area + '-' + username) : true;
if (!verifyEmail && !verifyMobile) {
logger.info(`【Passport Loginbad account, email:${verifyEmail} mobile:${verifyMobile}`);
return done({message: '登录账号格式错误'}, null);
}
let expire = req.cookies['LE' + md5('_LOGIN_EXPIRE')] || '';
if (expire && expire < (new Date()).getTime() / 1000) {
return done({message: '页面停留时间过长,请刷新页面'}, null);
}
let verifyCode = req.body.captcha;
if (verifyCode && verifyCode !== req.session.captcha) {
return done({message: '验证码不正确或验证码过期', needCaptcha: true}, null);
}
let shoppingKey = cookie.getShoppingKey(req);
let account = req.body.account;
let errorLoginKey = 'account_errorlogin_' + account;
let accountKey = 'account_signin_' + account;
let cacheGet = [cache.get(errorLoginKey), cache.get(accountKey)];
Promise.all(cacheGet).then(times => {
let errLoginTimes = _.parseInt(times[0]) || 0;
let accountTimes = _.parseInt(times[1]) || 0;
if (accountTimes >= 10) {
done({ message: '您的账号已被暂时锁定,请30分钟后再试' }, null);
} else {
return LoginService.signin(type, area, username, password, shoppingKey, req).then((result) => {
if (result.code && result.code === 200 && result.data.uid) {
cache.del(errorLoginKey);
done(null, result.data);
} else {
errLoginTimes = errLoginTimes + 1;
accountTimes = accountTimes + 1;
cache.set(errorLoginKey, errLoginTimes);
cache.set(accountKey, accountTimes, 1800);
// 再次校验
if (accountTimes >= 10) {
done({message: '您的账号已被暂时锁定,请稍后再试'}, null);
} else if (errLoginTimes >= 3) {
done({
message: '请输入正确的账号或密码',
needCaptcha: true
});
} else {
done({
message: '请输入正确的账号或密码',
needCaptcha: false
});
}
}
});
let verifyEmail = helpers.verifyEmail(username);
let verifyMobile = area === '86' ? helpers.verifyAreaMobile(area + '-' + username) : true;
if (!verifyEmail && !verifyMobile) {
logger.info(`【Passport Loginbad account, email:${verifyEmail} mobile:${verifyMobile}`);
return done({message: '登录账号格式错误'}, null);
}
let expire = req.cookies['LE' + md5('_LOGIN_EXPIRE')] || '';
if (expire && expire < (new Date()).getTime() / 1000) {
return done({message: '页面停留时间过长,请刷新页面'}, null);
}
if (type !== 'SMSLogin' && verifyCode && verifyCode !== req.session.captcha) {
return done({message: '验证码不正确或验证码过期', needCaptcha: true}, null);
}
let shoppingKey = cookie.getShoppingKey(req);
return LoginService.signin(type, area, username, password, shoppingKey, req).then((result) => {
if (result.code && result.code === 200 && result.data.uid) {
cache.del(errorLoginKey).catch(() => {});
done(null, result.data);
} else {
cache.set(errorLoginKey, errLoginTimes + 1, 3600).catch(() => {});
done({
message: '请输入正确的账号或密码',
needCaptcha: true
});
}
}).catch(e => {
logger.error('call the signin service fail,', e);
done('登录失败,请稍后重试', null);
});
}).catch(e => {
logger.error('call the signin service fail,', e);
done('登录失败,请稍后重试', null);
return done('登录失败,请稍后重试', null);
});
}));
/**
... ...
... ... @@ -20,7 +20,8 @@ const router = express.Router(); // eslint-disable-line
// 本地登录
router.get('/login', login.common.beforeLogin, login.local.loginPage);
router.post('/login/auth', login.local.login);
router.post('/login/user', back.validateInputAPI, back.getUserInfoAPI);
// router.post('/login/user', back.validateInputAPI, back.getUserInfoAPI);
router.get('/logout', login.local.logout);
// 手机短信验证码
... ... @@ -72,7 +73,8 @@ router.post('/autouserinfo/relateMobile', bind.relateMobile);
* 注册页面路由
*/
router.get('/reg', reg.index);
router.post('/reg/checkmobile', reg.checkMobile);
// router.post('/reg/checkmobile', reg.checkMobile);
router.post('/reg/piccaptcha', reg.checkCode, reg.picCaptcha);
router.post('/reg/msgcaptcha', reg.msgCaptcha);
router.post('/reg/sendBindMsg', reg.checkCode, reg.sendBindMsg);
... ... @@ -86,9 +88,9 @@ router.get('/reg/success', reg.success);
router.get('/back/index', back.indexPage);
// 实时验证输入是否正确
router.post('/back/authcode',
back.validateInputAPI,
back.getUserInfoAPI);
// router.post('/back/authcode',
// back.validateInputAPI,
// back.getUserInfoAPI);
// 提交按钮邮件API
router.post('/back/email',
... ... @@ -157,4 +159,5 @@ router.get('/back/resetSuccess',
router.get('/images', captcha.generate);
router.post('/images/check', captcha.requiredPost);
module.exports = router;
... ...
... ... @@ -11,11 +11,12 @@
const _ = require('lodash');
const Search = require('../models/search');
const DataHelper = require('../models/helpers');
const helper = global.yoho.helpers;
const Query = {
index: (req, res, next) => {
let q = req.query;
let query = q.query || '';
let query = helper.xssHtml(q.query) || '';
let channel = req.query._Channel || req.cookies._Channel || 'men';
q.page = parseInt(q.page || 1, 10);
... ...
... ... @@ -34,7 +34,7 @@ const safeRedirect = (uri) => {
}
return _.some(domains, matchFunc) ? uri : '/';
return _.some(domains, matchFunc) ? uri.replace(/\@.*$/, '') : '/';
};
/**
... ...
{
"name": "yoho-blk",
"version": "0.2.4",
"version": "0.2.5",
"private": true,
"description": "A New Yohoblk Project With Express",
"repository": {
... ... @@ -65,7 +65,9 @@
"winston-daily-rotate-file": "^1.1.4",
"xml2js": "^0.4.17",
"xss": "^0.2.13",
"yoho-node-lib": "0.2.17"
"connect-memcached": "^0.2.0",
"yoho-express-session": "^2.0.0",
"yoho-node-lib": "0.2.17"
},
"devDependencies": {
"autoprefixer": "^6.3.6",
... ...
... ... @@ -5,7 +5,8 @@
*/
var dialog = require('../../plugins/dialog');
var _alert = dialog.Alert;
var regValidate = require('../../passport/common/mail-phone-regx');
// var regValidate = require('../../passport/common/mail-phone-regx');
var types = location.pathname.split('/');
var type = types[types.length - 1]; // 界面操作类型
var $imgCaptchaInput = $('#captcha');
... ... @@ -28,21 +29,21 @@ var disableSMSBtn = function() {
};
// 校验手机号码格式
var validatePhoneNumLocal = function(phoneNum) {
var length = phoneNum.length;
phoneNum = parseInt(phoneNum, 10);
if (length === 0) {
new _alert('请输入手机号码!').show();
return false;
} else if (length !== 11 || !/^[0-9]+$/.test(phoneNum) || !regValidate.phoneRegx['+86'].test(phoneNum)) {
new _alert('手机号码格式不正确,请重新输入!').show();
return false;
} else {
return true;
}
};
// var validatePhoneNumLocal = function(phoneNum) {
// var length = phoneNum.length;
// phoneNum = parseInt(phoneNum, 10);
// if (length === 0) {
// new _alert('请输入手机号码!').show();
// return false;
// } else if (length !== 11 || !/^[0-9]+$/.test(phoneNum) || !regValidate.phoneRegx['+86'].test(phoneNum)) {
// new _alert('手机号码格式不正确,请重新输入!').show();
// return false;
// } else {
// return true;
// }
// };
require('yoho-jquery-placeholder');
... ... @@ -57,42 +58,42 @@ $('#region').on('change', function() {
});
// 校验手机号码
$('#real-mobile').blur(function() {
var mobile = $(this).val();
var self = $('#real-mobile').parent();
if (validatePhoneNumLocal(mobile)) {
$.ajax({
type: 'POST',
url: '/me/account/checkVerifyMobile',
dataType: 'json',
data: {
mobile: mobile,
area: area
},
success: function(data) {
if (data.code === 200) {
$sms.removeClass('disable');
self.find('.tips-success').addClass('ok').show();
self.find('.tips-error').removeClass('notok').hide();
} else {
new _alert(data.message).show();
self.find('.tips-success').removeClass('ok').hide();
self.find('.tips-error').addClass('notok').show();
}
}
});
}
});
// $('#real-mobile').blur(function() {
// var mobile = $(this).val();
// var self = $('#real-mobile').parent();
// if (validatePhoneNumLocal(mobile)) {
// $.ajax({
// type: 'POST',
// url: '/me/account/checkVerifyMobile',
// dataType: 'json',
// data: {
// mobile: mobile,
// area: area
// },
// success: function(data) {
// if (data.code === 200) {
// $sms.removeClass('disable');
// self.find('.tips-success').addClass('ok').show();
// self.find('.tips-error').removeClass('notok').hide();
// } else {
// new _alert(data.message).show();
// self.find('.tips-success').removeClass('ok').hide();
// self.find('.tips-error').addClass('notok').show();
// }
// }
// });
// }
// });
// 发送手机验证码
$sms.click(function() {
var mobile = $('#real-mobile').val();
if ($(this).hasClass('disable')) {
return;
}
// if ($(this).hasClass('disable')) {
// return;
// }
$sms.addClass('disable');
$.ajax({
type: 'POST',
... ...
... ... @@ -8,7 +8,7 @@ var $ = require('yoho-jquery'),
regx = require('../common/mail-phone-regx'),
EventProxy = require('yoho-eventproxy');
var emailAc = require('../common/ac-email'); // 邮箱自动完成
// var emailAc = require('../common/ac-email'); // 邮箱自动完成
var $regionCodeText = $('#country-code'),
$phoneNumInput = $('.phone-num'),
... ... @@ -125,7 +125,7 @@ function validatePhoneNumLocal() {
/**
* 整合本地和异步验证
*/
function validatePhoneNum() {
function validatePhoneNum() {//eslint-disable-line
function validate() {
var defer = $.Deferred(); //eslint-disable-line
... ... @@ -227,9 +227,9 @@ function validateImgCaptcha() {
/**
* 邮箱自动补全
*/
emailAc($phoneNumInput, function() {
validatePhoneNum();
});
// emailAc($phoneNumInput, function() {
// validatePhoneNum();
// });
$imgCaptchaInput.attr('maxlength', 4);
... ... @@ -237,6 +237,7 @@ $imgCaptchaInput.attr('maxlength', 4);
$('input').placeholder();
exports.init = function() {
$nextBtn.removeClass('disable');
// 监听事件 phone-num 和 captcha-img
ep.tail('phone-num', 'captcha-img', function(phoneAuth, imgAuth) {
... ... @@ -271,13 +272,13 @@ exports.init = function() {
$imgCaptchaInput.addClass('focus');
});
$phoneNumInput.on('focus', function() {
hideTip($phoneNumInput);
$('.phone').addClass('focus');
}).on('blur', function() {
$phoneNumInput.removeClass('focus');
$('.phone').removeClass('focus');
});
// $phoneNumInput.on('focus', function() {
// hideTip($phoneNumInput);
// $('.phone').addClass('focus');
// }).on('blur', function() {
// $phoneNumInput.removeClass('focus');
// $('.phone').removeClass('focus');
// });
$nextBtn.on('click', function() {
var urlPhone = '/passport/back/mobile',
... ...
... ... @@ -60,6 +60,15 @@ function disableSMSBtn() {
}
}
// 刷新图形验证码
function refreshImgCaptcha() {
var time = new Date(),
$captchaImg = $('.img-captcha'),
captchaImgSrc = $captchaImg.attr('src').split('?')[0];
$captchaImg.attr('src', captchaImgSrc + '?t=' + time.getTime());
}
// 发送短信验证码
function sendSMSCaptcha() {
return $.ajax({
... ... @@ -67,20 +76,18 @@ function sendSMSCaptcha() {
url: '/passport/autouserinfo/sendBindMsg',
data: {
mobile: $phoneNumInput.val(),
area: $regionCodeText.text().replace('+', '')
area: $regionCodeText.text().replace('+', ''),
verifyCode: $imgCaptchaInput.val()
}
}).then(function(ret) {
if (ret && ret.code === 400) {
errTip($imgCaptchaInput, ret.message);
refreshImgCaptcha();
ep.emit('img-captcha', false);
}
});
}
// 刷新图形验证码
function refreshImgCaptcha() {
var time = new Date(),
$captchaImg = $('.img-captcha'),
captchaImgSrc = $captchaImg.attr('src').split('?')[0];
$captchaImg.attr('src', captchaImgSrc + '?t=' + time.getTime());
}
// 异步验证图形码
function validateImgCaptchaAsync() {
return $.ajax({
... ... @@ -268,10 +275,17 @@ $smsCaptchaCtrl.on('click', function() {
return;
}
$smsCaptchaCtrl.addClass('disable');
disableSMSBtn();
sendSMSCaptcha();
validateImgCaptchaAsync().then(function(result) {
if (result.code === 200) {
$smsCaptchaCtrl.addClass('disable');
disableSMSBtn();
sendSMSCaptcha();
} else {
ep.emit('img-captcha', false);
errTip($imgCaptchaInput, '图形验证码错误');
refreshImgCaptcha();
}
});
});
// 统一设置用户信息
... ...
... ... @@ -25,7 +25,7 @@ var $phoneNumInput = $('#account'),
var $loginTip = $loginBtn.siblings('.login-fail-tip'),
ep = new EventProxy();
var mailPhoneRegx = require('../common/mail-phone-regx');
// var mailPhoneRegx = require('../common/mail-phone-regx');
var mailAc = require('../common/ac-email'); // 邮箱自动完成
var $remember = $('.remember-me');
var captchaUrl = '/passport/images?t='; // /passport/images?t=1454464125
... ... @@ -53,7 +53,8 @@ var secondCount = 60;
// 短信验证码只能验证一次
var isSmsCheckedSuccessFlag = false;
var currLoginType = 'PasswordLogin';
var userIsRight = false;
// var userIsRight = false;
var smsIsRight = false;
require('yoho-jquery-placeholder');
... ... @@ -86,94 +87,94 @@ function getMoblie() {
}
// 验证账户名
function validateAccountLocal() {
var phoneNum = getMoblie(),
regionCode = $regionCodeText.text();
if (phoneNum !== '') {
if (/^[0-9]+$/.test(phoneNum)) {
// 这里只做中国区验证
if (regionCode === '+86') {
if (phoneNum.length === 11 && mailPhoneRegx.phoneRegx['+86'].test(phoneNum)) {
return true;
} else {
errTip($phoneNumInput, '手机号码不正确,请重新输入');
return false;
}
}
return true;
} else {
// 邮箱验证
if (mailPhoneRegx.emailRegx.test(phoneNum)) {
return true;
} else {
errTip($phoneNumInput, '邮箱格式不正确,请重新输入');
return false;
}
}
} else {
errTip($phoneNumInput, '请输入账号');
return false;
}
}
// function validateAccountLocal() {
// var phoneNum = getMoblie(),
// regionCode = $regionCodeText.text();
// if (phoneNum !== '') {
// if (/^[0-9]+$/.test(phoneNum)) {
// // 这里只做中国区验证
// if (regionCode === '+86') {
// if (phoneNum.length === 11 && mailPhoneRegx.phoneRegx['+86'].test(phoneNum)) {
// return true;
// } else {
// errTip($phoneNumInput, '手机号码不正确,请重新输入');
// return false;
// }
// }
// return true;
// } else {
// // 邮箱验证
// if (mailPhoneRegx.emailRegx.test(phoneNum)) {
// return true;
// } else {
// errTip($phoneNumInput, '邮箱格式不正确,请重新输入');
// return false;
// }
// }
// } else {
// errTip($phoneNumInput, '请输入账号');
// return false;
// }
// }
// 异步验证帐号是否存在
function validateAccountAsync(url) {
return $.ajax({
type: 'POST',
url: url,
data: {
phoneNum: getMoblie(),
area: getArea()
}
}).then(function(data) {
if (data.code && data.code === 200) {
return true;
} else {
errTip($phoneNumInput, data.message);
return false;
}
});
}
// function validateAccountAsync(url) {
// return $.ajax({
// type: 'POST',
// url: url,
// data: {
// phoneNum: getMoblie(),
// area: getArea()
// }
// }).then(function(data) {
// if (data.code && data.code === 200) {
// return true;
// } else {
// errTip($phoneNumInput, data.message);
// return false;
// }
// });
// }
// 整合本地和异步验证信息
function validateAccount() {
if (userIsRight) {
// if (userIsRight) {
return $.Deferred().resolve(true).promise(); // eslint-disable-line
}
return (function() {
var defer = $.Deferred(); // eslint-disable-line
var url = '/passport/login/user';
if (currLoginType === 'SMSLogin') {
url = '/passport/login/sms/checkuser';
}
if (validateAccountLocal()) {
validateAccountAsync(url).then(function(result) {
if (result) {
defer.resolve(result);
} else {
defer.reject(result);
}
});
} else {
defer.reject(false);
}
return defer.promise();
}()).then(function() {
hideTip($phoneNumInput);
ep.emit('phone', true);
userIsRight = true;
}).fail(function() {
ep.emit('phone', false);
});
// }
// return (function() {
// var defer = $.Deferred(); // eslint-disable-line
// var url = '/passport/login/user';
// if (currLoginType === 'SMSLogin') {
// url = '/passport/login/sms/checkuser';
// }
// if (validateAccountLocal()) {
// validateAccountAsync(url).then(function(result) {
// if (result) {
// defer.resolve(result);
// } else {
// defer.reject(result);
// }
// });
// } else {
// defer.reject(false);
// }
// return defer.promise();
// }()).then(function() {
// hideTip($phoneNumInput);
// ep.emit('phone', true);
// userIsRight = true;
// }).fail(function() {
// ep.emit('phone', false);
// });
}
// 验证密码
... ... @@ -282,65 +283,65 @@ function showAccountErrTimes() {
}
// 登录次数限制接口
function throttle() {
return $.ajax({
url: '/passport/login/account',
type: 'GET',
data: {
account: getMoblie()
}
});
}
// function throttle() {
// return $.ajax({
// url: '/passport/login/account',
// type: 'GET',
// data: {
// account: getMoblie()
// }
// });
// }
// 验证帐号系统
function validate() {
if (userIsRight) {
return true;
}
return validateAccount().then(function(result) {
if (result) {
return throttle();
} else {
return false;
}
}).then(function(res) {
var defer = $.Deferred(); // eslint-disable-line
if (!res) {
defer.reject(false);
}
if (res.data && res.data.needCaptcha) {
showAccountErrTimes();
defer.reject(false);
}
defer.resolve(true);
return defer.promise();
});
}
// function validate() {
// if (userIsRight) {
// return true;
// }
// return validateAccount().then(function(result) {
// if (result) {
// return throttle();
// } else {
// return false;
// }
// }).then(function(res) {
// var defer = $.Deferred(); // eslint-disable-line
// if (!res) {
// defer.reject(false);
// }
// if (res.data && res.data.needCaptcha) {
// showAccountErrTimes();
// defer.reject(false);
// }
// defer.resolve(true);
// return defer.promise();
// });
// }
// 邮箱自动补全
mailAc($phoneNumInput, function() {
});
// 手机号码输入框失去焦点事件
function phoneBlur() {
$phone.removeClass('focus');
validate();
}
// function phoneBlur() {
// $phone.removeClass('focus');
// validate();
// }
$phoneNumInput.on('focus', function() {
hideTip($phoneNumInput);
$phone.addClass('focus');
$(this).off('blur').on('blur', phoneBlur);
});
// $phoneNumInput.on('focus', function() {
// hideTip($phoneNumInput);
// $phone.addClass('focus');
// $(this).off('blur').on('blur', phoneBlur);
// });
$phoneNumInput.on('input', function() {
userIsRight = false;
});
// $phoneNumInput.on('input', function() {
// userIsRight = false;
// });
$('[placeholder]').placeholder();
... ... @@ -508,7 +509,7 @@ function sendCaptchaSmsAsync() {
verifyCode: $.trim($imgCaptchaInput.val())
}
}).then(function(data) {
if (data.captchaCount === false) {
if (data.captchaCount === false || data.code === 400) {
errTip($imgCaptchaInput, data.message);
ep.emit('captcha', false);
refreshCaptcha();
... ... @@ -734,7 +735,8 @@ function loginAsync() {
// 全部的本地验证-- 短信验证登录
function smsLoginAsync() {
return validateAccount()
.then(validateCaptchaImg)
// .then(validateCaptchaImg)
.then(validateCaptchaSms)
.then(function() {
return login();
... ...
... ... @@ -162,8 +162,10 @@ function validateImgCaptcha() {
}()).then(function() {
hideTip($imgCaptchaInput);
ep.emit('captcha-img', true);
return true;
}).fail(function() {
ep.emit('captcha-img', false);
return false;
});
}
... ... @@ -196,14 +198,11 @@ function validateSMSCaptchaAsync() {
return false;
}
switch (data.code) {
case 200:
return true;
case 400:
errTip($smsCaptchaInput, '短信验证码错误');
return false;
default:
return false;
if (data.code === 200) {
return true;
} else {
errTip($smsCaptchaInput, data.message);
return false;
}
});
}
... ... @@ -261,7 +260,9 @@ function validatePhoneNumLocal() {
}
function validatePhoneNum() {
return (function() {
return $.Deferred().resolve(true);// eslint-disable-line
return (function() {// eslint-disable-line
var defer = $.Deferred(); // eslint-disable-line
if (validatePhoneNumLocal()) {
... ... @@ -464,18 +465,20 @@ function disableSMSBtn() {
}
exports.init = function() {
$smsCaptchaCtrl.removeClass('disable');
// 验证手机输入
$phoneNumInput.on('blur', function() {
validatePhoneNum();
$('#phone').removeClass('focus');
}).on('focus', function() {
hideTip($phoneNumInput);
$('#phone').addClass('focus');
});
// $phoneNumInput.on('blur', function() {
// validatePhoneNum();
// $('#phone').removeClass('focus');
// }).on('focus', function() {
// hideTip($phoneNumInput);
// $('#phone').addClass('focus');
// });
// 验证图形输入
$imgCaptchaInput.on('blur', function() {
validateImgCaptcha();
// validateImgCaptcha();
$imgCaptchaInput.removeClass('focus');
}).on('focus', function() {
hideTip($imgCaptchaInput);
... ... @@ -566,14 +569,30 @@ exports.init = function() {
// 点击发送验证码
$smsCaptchaCtrl.on('click', function() {
if ($smsCaptchaCtrl.hasClass('disable') || $smsCaptchaCtrl.hasClass('second-progress')) {
return;
}
$smsCaptchaCtrl.addClass('disable');
disableSMSBtn();
sendSMSCaptcha();
// if ($smsCaptchaCtrl.hasClass('disable') || $smsCaptchaCtrl.hasClass('second-progress')) {
// return;
// }
validateImgCaptcha().then(allow=>{
if (allow) {
$smsCaptchaCtrl.addClass('disable');
disableSMSBtn();
sendSMSCaptcha().then((data)=>{
if (data.code !== 200) {
if (data.code === 404) {
errTip($phoneNumInput, data.message);
} else {
errTip($imgCaptchaInput, data.message);
}
refreshImgCaptcha();
} else {
hideTip($smsCaptchaInput);
}
});
}
});
});
// 点击注册提交
... ...