sms.js 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
/* eslint no-unused-vars: ["error", { "args": "none" }] */
'use strict';
const _ = require('lodash');
const moment = require('moment');
const helpers = global.yoho.helpers;
const cookie = global.yoho.cookie;
const config = global.yoho.config;
const EventEmitter = require('events');
const utils = require(global.utils);
const RegService = require('../models/reg-service');
const PhoneService = require('../models/phone-service');
const AuthHelper = require('../models/auth-helper');

// constrant
const CODE_REQUIRED = '请输入校验码';
const PASSWORD_REQUIRED = '请输入密码';
const PASSWORD_LENGTH_ERROR = '密码6-20位,请重新输入';
const BAD_PASSWORD = '密码格式不正确';
const LOGIN_SUCCSS = '登录成功';
const VERIFY_ERROR = '校验失败';

exports.beforeIn = (req, res, next) => {
    res.set({
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        Pragma: 'no-cache',
        Expires: 0
    });

    let refer = utils.refererLimit(req.cookies.refer);

    if (!req.xhr && req.user.uid) {
        return res.redirect(refer);
    }

    next();
};

// 短信登录 第一步: 展现页面
const _step1 = (req, res, next) => {
    _.set(req.session, 'smsLogin.step', 1);

    if (req.session.captchaValidCount == null) { // eslint-disable-line
        req.session.captchaValidCount = 5;
    }

    let template = 'sms/login';

    // 登陆切换到短信登陆
    // let viewData = {
    //     width750: true,
    //     module: 'passport',
    //     page: 'sms-login',
    //     title: '手机短信登录',
    //     isPassportPage: true,
    //     headerText: '手机号码快捷登录',
    //     captchaUrl: helpers.urlFormat('/passport/sms_login/captcha.png', {t: Date.now()}),
    //     areaCode: '+86', // 默认的区号
    //     countrys: RegService.getAreaData() // 地区信息列表
    // };
    let viewData = {
        width750: true,
        module: 'passport',
        page: 'sms-login',
        backUrl: 'javascript:history.go(-1)', // eslint-disable-line
        showHeaderImg: true, // 控制显示头部图片
        title: '手机短信登录',
        isPassportPage: true,
        captchaUrl: helpers.urlFormat('/passport/sms_login/captcha.png', {t: Date.now()}),
        smsLoginUrl: '/passport/sms_login',
        registerUrl: '/passport/reg/index', // 注册的URL链接
        aliLoginUrl: '/passport/login/alipay', // 支付宝快捷登录的URL链接
        weiboLoginUrl: '/passport/login/sina', // 微博登录的URL链接
        qqLoginUrl: '/passport/login/qq', // 腾讯QQ登录的URL链接
        wechatLoginUrl: '/passport/login/wechat', // 微信登录的URL链接
        internationalUrl: '/passport/international', // 国际号登录的URL链接
        phoneRetriveUrl: '/passport/back/mobile', // 通过手机号找回密码的URL链接
        emailRetriveUrl: '/passport/back/email', // 通过邮箱找回密码的URL链接
        areaCode: '+86', // 默认的区号
        countrys: RegService.getAreaData(), // 地区信息列表
        reg: true
    };

    res.render(template, viewData);


};

// 短信登录 第二步: 输入 校验码
const _step2 = (req, res, next) => {
    const mobile = req.session.smsLogin.mobile;
    const area = req.session.smsLogin.area;
    const interval = req.session.smsLogin.interval;

    const template = 'sms/check';
    const viewData = {
        module: 'passport',
        page: 'sms-check',
        title: '手机短信登录',
        isPassportPage: true,
        headerText: '手机号码快捷登录',
        countdown: Math.ceil((interval - Date.now()) / 1000),
        mobile,
        area
    };

    res.render(template, viewData);
};

// 短信登录 第三步: 设置密码 (针对 改手机未注册用户)
const _step3 = (req, res, next) => {
    const template = 'sms/password';
    const viewData = {
        module: 'passport',
        page: 'sms-password',
        title: '设置密码',
        isPassportPage: true,
        headerText: '设置密码'
    };

    res.render(template, viewData);
};

// 短信 登录
exports.loginPage = (req, res, next) => {
    let step = Number(req.query.step) || 1;
    let smsLoginStep = _.get(req.session, 'smsLogin.step', 1);

    if (step === 2 && smsLoginStep !== 2) {
        return res.redirect(req.path);
    }

    if (step === 3 && smsLoginStep !== 3) {
        return res.redirect(req.path);
    }

    switch (step) {
        case 2:
            _step2(req, res, next);
            break;
        case 3:
            _step3(req, res, next);
            break;
        case 1:
        default:
            _step1(req, res, next);
    }
};


/**
 *  step1 的表单提交验证
 */
exports.indexCheck = (req, res, next) => {
    _.set(req.session, 'smsLogin.step', 1);

    let area = req.body.area = (req.body.area || '').trim();
    let mobile = req.body.mobile = (req.body.mobile || '').trim();
    let captcode = (req.body.captcode || '').trim();
    let captcodeValid = _.get(req.session, 'captcha');
    let testCode = req.body.yohobuy;

    let em = new EventEmitter();


    let errorCount = _.get(req.session, 'captchaValidCount', 4 - 1); // 初始1次 + 后续4次, 同一个验证码 共5次
    let errorData = {
        code: 400,
        message: ''
    };

    if (!errorCount) {
        _.set(req.session, 'captchaValidCount', 3);
    } else {
        --req.session.captchaValidCount;
    }

    // 校验 成功
    em.on('resolve', () => {
        // 1. 将信息放入 session
        _.set(req.session, 'smsLogin.area', area);
        _.set(req.session, 'smsLogin.mobile', mobile);
        _.set(req.session, 'smsLogin.step', 2);
        req.session.captcha = null;

        PhoneService.sendSMS(mobile, area, 1);

        res.json({
            code: 200,
            redirect: '/passport/sms_login?step=2'
        });
    });

    // 校验 失败
    em.on('reject', error => {
        _.set(req.session, 'smsLogin.step', 1);


        res.json(error);
    });

    if (req.session.captchaValidCount === 0) {
        req.session.captcha = null; // 验证码 用过就扔
        errorData.changeCaptcha = true;
    }


    // 验证
    if ([area, mobile].some(val => val === '')) {
        return em.emit('reject', Object.assign(errorData, { message: '请填写手机号'}));
    } else if (!captcode) {
        return em.emit('reject', Object.assign(errorData, {message: '请填写验证码'}));
    } else if (
        !(
            (captcodeValid && captcode === captcodeValid) || (testCode === config.testCode)
        )
    ) {
        return em.emit('reject', Object.assign(errorData, {message: '请将图片旋转到正确位置'}));
    }

    // congratulation~~
    em.emit('resolve');
};

exports.tokenBefore = (req, res, next) => {

    let step = _.get(req.session, 'smsLogin.step');
    let count = _.get(req.session, 'smsLogin.count');
    let interval = _.get(req.session, 'smsLogin.interval');


    if (!req.xhr || step !== 2) {
        return next(404);
    }

    let now = Date.now();

    // 重发次数用完了, 回冻结5min
    //      1. 过了冻结期, count 重设为 5次
    //      2. 没过冻结期, end
    // 没有用完, 判断是否请求太频繁
    let during = moment.duration(interval - now, 'ms').minutes();
    let message = `请${during}分钟后再试`;

    if (!count) {
        if (interval > now) {
            return res.json({
                code: 400,
                message: message,
                during: Math.ceil((interval - now) / 1000)
            });
        } else {
            _.set(req.session, 'smsLogin.count', 5);
        }
    } else if (interval > now) {
        return res.json({
            code: 429,
            message: message
        });
    }

    next();
};



// AJAX 获取验证码
exports.token = (req, res, next) => {
    let area = _.get(req.session, 'smsLogin.area');
    let mobile = _.get(req.session, 'smsLogin.mobile');

    PhoneService.sendSMS(mobile, area, 1).then(result => {
        if (result.code === 200) {

            _.set(req.session, 'smsLogin.step', 2);
            _.set(req.session, 'smsLogin.area', area);
            _.set(req.session, 'smsLogin.mobile', mobile);

            --req.session.smsLogin.count;

            if (!req.session.smsLogin.count) {
                _.set(req.session, 'smsLogin.interval', Date.now() + 5 * 60 * 1000);
            } else {
                _.set(req.session, 'smsLogin.interval', Date.now() + 60 * 1000);
            }

            result.redirect = '/passport/sms_login?step=2';
            res.json(result);
            return;
        }

        res.json(result);
    });
};

exports.checkBefore = (req, res, next) => {
    let code = req.query.code = (req.query.code || '').trim();
    let step = _.get(req.session, 'smsLogin.step');

    if (!req.xhr && step !== 2) {
        return next(404);
    }

    if (!code) {
        return res.json({
            code: 404,
            message: CODE_REQUIRED
        });
    }

    next();
};

// AJAX 校验验证码 in step2
exports.check = (req, res, next) => {
    const code = req.query.code;
    const mobile = _.get(req.session, 'smsLogin.mobile', '');
    const area = _.get(req.session, 'smsLogin.area', '');
    const shopping_key = cookie.getShoppingKey(req); // eslint-disable-line

    if (!mobile || !area) {
        res.json({
            code: 401,
            message: VERIFY_ERROR
        });
        return;
    }

    Promise.all([
        PhoneService.checkUserPhoneExist(mobile, area),
        PhoneService.verifySMS(mobile, area, code, 1)
    ])
        .then(result => {
            let r1 = result[0] || {};
            let r2 = result[1] || {};
            let redirect;

            // 验证码 校验异常
            if (r2.code !== 200) {
                res.json(r2);
                return;
            }

            // 检测 手机号 是否注册 异常
            if (r1.code !== 200) {
                res.json(r1);
                return;
            }

            // 校验失败
            if (r2.data.is_pass !== 'Y') {
                res.json({
                    code: 401,
                    message: VERIFY_ERROR
                });

                return;
            }

            // 手机号码 没注册
            if (r1.data.is_register !== 'Y') {
                redirect = '/passport/sms_login?step=3';
                _.set(req.session, 'smsLogin.step', 3);

                res.json({
                    code: 200,
                    redirect,
                    newer: true,
                    registerCode: r1.data.code
                });

                return;
            }

            // 手机号码已注册 --> 直接登录
            PhoneService.autoSignin({
                profile: mobile,
                code: r2.data.code,
                area,
                shopping_key
            })
                .then(info => {
                    if (info.code !== 200) {
                        return Promise.reject(info);
                    }

                    return AuthHelper.syncUserSession(info.data.uid, req, res);
                })
                .then(() => {
                    res.json({
                        code: 200,
                        message: LOGIN_SUCCSS,
                        redirect: utils.refererLimit(req.cookies.refer)
                    });

                    delete req.session.smsLogin;
                })
                .catch(error => {
                    res.json(error);
                });

        })
        .catch(next);
};

// AJAX 短信登录 设置密码 in step3
exports.password = (req, res, next) => {
    let step = _.get(req.session, 'smsLogin.step');

    if (step !== 3) {
        return next();
    }


    let data = {
        code: '400',
        message: BAD_PASSWORD
    };

    let mobile = _.get(req.session, 'smsLogin.mobile');
    let area = _.get(req.session, 'smsLogin.area');
    let password = (req.body.password || '').trim();
    let registerCode = req.body.registerCode || '';

    if (!password) {
        data.message = PASSWORD_REQUIRED;
        return res.json(data);
    }

    if (password.length < 6 || password.length > 20) {
        data.message = PASSWORD_LENGTH_ERROR;
        return res.json(data);
    }

    if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(password)) {
        return res.json(data);
    }

    // 购物车key
    let shoppingKey = cookie.getShoppingKey(req);


    RegService.regMobileAes(area, mobile, password, shoppingKey, registerCode).then(result => {
        if (!result.code || result.code !== 200) {
            return Promise.reject(result);
        }
        if (!result.data || !result.data.uid) {
            return Promise.reject(result);
        }

        return AuthHelper.syncUserSession(result.data.uid, req, res);
    }).then(() => {
        res.json({
            code: 200,
            message: LOGIN_SUCCSS,
            redirect: utils.refererLimit(req.cookies.refer)
        });
        delete req.session.smsLogin;
    }).catch(next);
};


/**
 *  生成 校验码
 */
/*
exports.genCaptcha = (req, res) => {
    let captcha = captchaService.generateCaptcha(90, 52, 4);

    _.set(req.session, 'smsLogin.captcha', captcha.text);

    res.type('png')
       .set('Cache-Control', 'no-cache')
       .status(200)
       .send(captcha.image);
};
*/