reg.js 2.81 KB
/**
* 注册控制器
*/
'use strict';
const _ = require('lodash');
const passportHelper = require('../models/passport-helper');
const regService = require('../models/reg-service');
const userService = require('../models/user-service');
const config = require('../../../config/common');

let helpers = global.yoho.helpers;
let cache = global.yoho.cache;

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

    let refer = req.query.refer;

    refer && res.cookie('refer', encodeURI(refer), {
        domain: 'yohobuy.com'
    });

    regService.getRegData().then((result) => {
        res.render('reg/index', {
            title: '新用户注册',
            passport: {
                region: passportHelper.getCountry(),
                location: '+86',
                captchaUrl: helpers.urlFormat('/passport/images', {t: Date.now()}),
                itemUrl: helpers.urlFormat('/help/', {category_id: 9}),
                referUrl: refer,
                loginUrl: helpers.urlFormat('/signin.html', {refer: refer}),
                coverHref: result.url,
                coverImg: result.img,
                regBtnText: '立即注册'
            }
        });
    }).catch(next);
};

let checkMobile = (req, res, next) => {
    let data = {
        code: 400
    };
    let mobile = +req.body.mobile;
    let area = +req.body.area;

    if (!_.isNumber(mobile) || !_.isNumber(area)) {
        data.message = '手机号码格式不正确';
        return res.json(data);
    }

    // 判断手机号是否检查超过指定次数
    let key = 'checkmobilenum_' + passportHelper.makeAreaMobile(area, mobile);

    cache.get(key).then((checkNum) => {
        checkNum = +(checkNum || 0);

        cache.set(key, ++checkNum).catch(next);
        if (checkNum > 500) {
            data.message = '检查次数太多';
            return res.json(data);
        }

        // 判断用户是否存在
        return userService.findByMobileAsync(area, mobile).then((user) => {
            if (!_.isEmpty(user)) {
                data.message = '手机号码已经存在';
                return res.json(data);
            }

            data.code = 200;
            return res.json(data);
        });
    }).catch(next);
};

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

    regService.getRegData().then((result) => {
        res.render('reg/success', {
            title: '注册成功',
            passport: {
                goUrl: goUrl,
                goShoppong: goShoppingUrl,
                coverHref: result.url,
                coverImg: result.img
            }
        });
    }).catch(next);
};

module.exports = {
    index,
    success,
    checkMobile
};