reg.js 8.08 KB
/**
 * 注册控制器
 */
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const passportHelper = require('../models/passport-helper');
const RegService = require('../models/reg-service');
const LoginService = require('../models/login-service');
const request = require('request-promise');


const config = require('../../../config/common');
const simpleHeaderModel = require('../../../doraemon/models/simple-header');
let helpers = global.yoho.helpers;
let cookie = global.yoho.cookie;
let logger = global.yoho.logger;

class BaiduSDK {
    /*
     * @ description: 广告主回传转化数据接口, 上报百度
     * @ author: huzhiming
     * @ date: 2019-11-19 17:21:29
     * @ version: v1.0.0
     * 详情见文档:[http://ocpc.baidu.com/developer/d/guide/?iurl=api%2Fapi-doc%2Fapi-interface%2F]
    */
    static reportOcpcApi({
        token = '7GULUkX90QLZU6cHO9OEqUsRKttGNqpN@O62eFfb91OUVhmkakV1bQHIxF8xURBvP',
        conversionTypes = [{ logidUrl: '', newType: null }]
    }) {
        logger.info('--------------百度ocpc--------------');
        request({
            method: 'POST',
            uri: 'http://ocpc.baidu.com/ocpcapi/api/uploadConvertData',
            body: {
                token,
                conversionTypes
            },
            json: true
        }).then((result) => {
            logger.info(`[账号注册成功后上报 百度ocpc返回信息:${JSON.stringify(result)}`);
        }).catch((error) => {
            logger.info(`[账号注册成功后上报 百度ocpc失败 错误信息:${error}`);
        });
    }
}


/**
 * 检查图形验证码
 */
let checkCode = (req, res, next) => {
    let verifyCode = _.trim(req.body.verifyCode);

    if (verifyCode !== req.session.captcha) {
        return res.json({
            code: 400,
            message: '验证码错误'
        });
    }
    next();
};

/**
 * 检查手机格式
 */
let checkMobileMiddleware = (req, res, next) => {
    let mobile = req.body.mobile;
    let area = req.body.area;

    if (!(_.toNumber(mobile) && _.toNumber(area))) {
        return res.json({
            code: 400,
            message: '手机号码格式不正确'
        });
    }
    next();
};

/**
 * 检查密码格式
 */
let checkPassword = (req, res, next) => {
    /* 判断密码是否符合规则 */
    let password = req.body.password;

    if (!helpers.verifyPassword(password)) {
        return res.json({
            code: 400,
            message: '密码不正确'
        });
    }
    next();
};

/**
 * 注册首页
 */
let index = (req, res, next) => {
    // 设置注册有效时间30分钟, 防机器刷
    req.session.REG_EXPIRE_ = Date.now() + 1800000;

    let refer = req.query.refer;
    let mobile = req.query.mobile;
    let area = req.query.area;

    refer && res.cookie('refer', encodeURI(refer), {
        domain: config.cookieDomain
    });

    req.ctx(RegService).getRegData().then((result) => {
        res.render('reg/index', {
            simpleHeader: simpleHeaderModel.setSimpleHeaderData(),
            title: '新用户注册',
            passport: {
                region: req.ctx(passportHelper).getCountry(),
                location: area || '+86',
                defaultMobile: mobile,
                captchaUrl: helpers.urlFormat('/passport/imagesNode', {t: Date.now()}),
                itemUrl: helpers.urlFormat('/help/detail', {id: 254}),
                privacyUrl: helpers.urlFormat('/help/detail', {id: 256}),
                referUrl: refer,
                loginUrl: helpers.urlFormat('/signin.html', {refer: refer}),
                coverHref: result.url,
                coverImg: result.img,
                regBtnText: '立即注册'
            },
            module: 'passport',
            page: 'reg'
        });
    }).catch(next);
};

/**
 * checkMobile的伪装,始终成功。
 */
let fakeCheckMobile = (req, res) => {
    return res.json({
        code: 200
    });
};

/**
 * 发送验证码
 */
let sendBindMsg = (req, res, next) => {
    let mobile = req.body.mobile;
    let area = req.body.area;
    let sessionId = req.session.id;
    let captcha = req.body.verifyCode;

    /* 向手机发送注册验证码 */
    req.ctx(RegService).sendCodeToMobile(area, mobile, sessionId, captcha).then((result) => {
        if (result.code === 200) {
            req.session.type = 'register-step1';
        }

        return res.json(result);
    }).catch(next);
};

/**
 * 短信验证码校验
 */
let msgCaptcha = (req, res, next) => {
    let data = {
        code: 400,
        message: '',
        data: ''
    };
    let area = req.body.area;
    let mobile = req.body.mobile;
    let code = req.body.code; // 短信验证码

    req.ctx(RegService).validMobileCode(area, mobile, code).then((result) => {
        if (result.code) {
            return res.json(result);
        } else {
            data.message = '短信验证码错误';
            return res.json(data);
        }
    }).catch(next);
};

/**
 * 注册接口
 */
let mobileRegister = (req, res, next) => {
    Promise.coroutine(function* () {
        let data = {
            code: 400,
            message: '',
            data: ''
        };

        if (req.session.type !== 'register-step1') {
            return res.json(data);
        }

        let area = req.body.area;
        let mobile = req.body.mobile;
        let code = req.body.code; // 短信验证码
        let password = req.body.password;
        let inviteCode = req.body.inviteCode;
        let result = yield req.ctx(RegService).validMobileCode(area, mobile, code); // 验证注册的标识码是否有效

        if (!result.code || result.code !== 200) {
            data.message = '短信验证码错误';
            return res.json(data);
        }

        /* 手机注册: 调用注册接口*/
        let regResult = yield req.ctx(RegService).regMobileAes(
            area, mobile, password, code, cookie.getShoppingKey(req), inviteCode, {udid: req.yoho.udid}
        );

        if (!regResult.code || regResult.code !== 200) {
            data.message = regResult.message || '注册失败';
            return res.json(data);
        }

        /*
            * @ description: feat(oCPC搜索推广): 推广链接转化数据发送给百度服务器,埋点:OCPC推广链接打开并完成注册进行数据上报
            * @ author: huzhiming
            * @ date: 2019-11-19 19:09:39
            * @ version: v1.0.0
            * bd_vid_path存值见:public/js/common.js 文件
        */
        const logidUrl = req.cookies.bd_vid_path;

        logger.info('-------logidUrl--------', `${logidUrl}:${mobile}`);
        if (logidUrl) {
            BaiduSDK.reportOcpcApi({
                conversionTypes: {
                    logidUrl,
                    newType: 3
                }
            });
        }

        // 清除 session type
        req.session.type = '';

        return req.ctx(LoginService).syncUserSession(regResult.data, req, res).then(() => {
            return res.json({
                code: 200,
                message: '注册成功',
                data: {
                    href: helpers.urlFormat('/passport/reg/success', {
                        next: cookie.getRefer(req, '/?go=1'),
                        goShoppingUrl: config.siteUrl
                    })
                }
            });
        });
    })().catch(next);
};

let success = (req, res, next) => {
    let goUrl = req.query.next || config.siteUrl;
    let goShoppingUrl = req.query.goShoppingUrl || config.siteUrl;

    req.ctx(RegService).getRegData().then((result) => {
        res.render('reg/success', {
            title: '注册成功',
            module: 'passport',
            page: 'reg-success',
            simpleHeader: simpleHeaderModel.setSimpleHeaderData(),
            passport: {
                goUrl: goUrl,
                goShoppong: goShoppingUrl,
                coverHref: result.url,
                coverImg: result.img
            }
        });
    }).catch(next);
};

module.exports = {
    checkCode,
    checkMobileMiddleware,
    checkPassword,
    index,
    success,
    sendBindMsg,
    msgCaptcha,
    mobileRegister,
    fakeCheckMobile
};