back-service.js 5.62 KB
/**
 * Created by TaoHuang on 2016/6/14.
 */

'use strict';

const helpers = require(`${library}/helpers`);
const api = require('./back-api');
const Promise = require('bluebird');
const co = Promise.coroutine;
const _ = require('lodash');
const moment = require('moment');

const userService = require('./user-service');
const passportHelper = require('./passport-helper');
const authHelper = require('./auth-helper');

const BACK_LEFT_BANNER_CODE = '3bbaf502c447a2ddad60879042e286d8'; //找回密码左边的banner

module.exports.validateEmailOrMobileAsync = (userInput, areaCode) => {
    return new Promise(function (resolve, rejected) {
        let result = {type: 'email', area: '', phone: ''};

        if (helpers.verifyEmail(userInput)) {
            result.type = 'email';
            result.area = '';
            result.phone = userInput;

            resolve(result);
        } else if (helpers.verifyAreaMobile(helpers.makeAreaMobile(areaCode, userInput))) {
            result.type = 'mobile';
            result.area = areaCode;
            result.phone = userInput;

            resolve(result);
        } else {
            rejected('输入信息出错!');
        }
    });

};

module.exports.findUserAsync = (type, phone, area) => {
    return co(function * () {
        const MESSAGE = {
            mobile: '您输入的手机号码尚未注册!',
            email: '您输入的邮件账户尚未注册!',
            ok: '验证成功'
        };

        const findBy = {
            email: userService.findByEmailAsync,
            mobile: userService.findByMobileAsync
        };

        const OK = {code: 200, message: MESSAGE.ok};

        return OK;

        const user = yield findBy[type](phone, area);

        if (_.isEmpty(user)) {
            return {
                code: 402,
                message: MESSAGE[type]
            };
        }

        return OK;
    })();
};

function sendCodeToEmailAsync(input) {
    return api.sendCodeToEmailAsync(input).then(result => {
        if (!result.code || result.code !== 200) {
            return Promise.reject('request error!');
        }

        return result.data;
    }).catch(() => {
        return {};
    });
}

function sendCodeToMobileAsync(areaCode, userInput) {
    return api.sendCodeToMobileAsync(areaCode, userInput).then(result => {
        if (!result.code || result.code !== 200) {
            return Promise.reject('request error');
        }

        return result.data;
    }).catch(() => {
        return {};
    });
}

module.exports.sendCodeToUserAsync = (type, mobile, areaCode) => {
    let sendTo = {
        email: sendCodeToEmailAsync,
        mobile: sendCodeToMobileAsync
    };

    return sendTo[type](mobile, areaCode);
};

/**
 * 发送找回手机号短信
 */
module.exports.sendCodeToMobileAsync = (areaCode, mobile) => {
    return api.sendCodeToMobileAsync(mobile, areaCode);
};

/**
 * 获得首页的数据
 */
module.exports.indexPageDataAsync = () => {
    return co(function *() {
        let banner = yield passportHelper.getLeftBannerAsync(BACK_LEFT_BANNER_CODE);
        let countryList = passportHelper.getCountry();

        return {
            back: {
                coverHref: banner.url,
                coverImg: banner.img,
                countryCode: 86,
                countryName: "中国",
                captchaUrl: helpers.urlFormat('/passport/images', {t: moment().valueOf()}),
                countryList: countryList
            }
        }
    })();
};

module.exports.verifyCodyByMobileAsync = (area, mobile, mobileCode) => {
    const ERR = {
        code: 400,
        message: '验证码错误!',
        data: helpers.urlFormat('/passport/back/index.html')
    };

    api.validateMobileCodeAsync(mobile, mobileCode, area)
        .then(result => {
            if (!result.code || result.code !== 200) {
                return ERR;
            }

            let token = authHelper.encode({
                mobile: mobile,
                area: area,
                token: result.data.token,
                create_time: moment().unix()
            });

            return {
                code: 200,
                message: '验证成功',
                data: helpers.urlFormat('/passport/back/backcode', {
                    code: new Buffer(token).toString('base64')
                })
            };
        })

};

module.exports.authRequest = (token) => {
    let json = authHelper.decode(token);
    let existTime = moment.duration(24, 'hours').seconds();
    let isExpired = (moment().unix() - json.create_time) > existTime;
    if (isExpired) {
        return {}
    } else {
        return json;
    }
};

module.exports.updatePwdAsync = (emailToken, mobileToken, newPassword) => {
    return co(function * () {
        let result = {type: 'mobile', status: false};

        const ERR = {type: '', status: false};

        if (!_.isEmpty(mobileToken)) {
            if (!mobileToken.mobile || mobileToken.uid) {
                return ERR;
            }

            let mobile = mobileToken.mobile;

            let area = mobileToken.area;

            let token = mobileToken.token;

            let data = yield api.modifyPasswordByMobileAsync(mobile, token, newPassword, area);

            if (!data.code || data.code !== 200) {
                return ERR;
            }

            result.type = 'mobile';
            result.status = true;

        } else {
            let data = yield api.modifyPasswordByEmailCodeAsync(emailToken, newPassword);

            if (!data.code || data.code !== 200) {
                return ERR;
            }

            result.type = 'email';
            result.status = true;
        }

        return result;

    })();
}