sms.js 5.04 KB
/**
 * 短信controller
 * @author: leo <qi.li@yoho.cn>
 * @date: 2017/06/26
 */
'use strict';
const _ = require('lodash');
const EventEmitter = require('events');
const AuthHelper = require('../models/auth-helper');
const PhoneService = require('../models/phone-service');

const VERIFY_ERROR = '校验失败';
const LOGIN_SUCCESS = '登录成功';
const ANONYMOUS_USER = '匿名用户';
const CODE_REQUIRED = '请输入校验码';
const GET_USER_INFO_FAILED = '获取用户信息失败';

const sms = {
    /**
     * 发送短信验证码
     * @param req
     * @param res
     * @returns {*|boolean}
     */
    send(req, res) {
        const em = new EventEmitter();
        const area = (req.body.area || '').trim();
        const mobile = (req.body.mobile || '').trim();
        const inValid = [area, mobile].some(v => v === '');

        em.on('resolve', () => {
            _.set(req.session, 'smsLogin.area', area);
            _.set(req.session, 'smsLogin.mobile', mobile);

            PhoneService.sendSMS(mobile, area, 1)
                .then(result => {
                    if (result.code === 200) {
                        return res.json({
                            code: 200,
                            message: '验证码发送成功'
                        });
                    }

                    res.json({
                        code: 500,
                        message: '验证码发送失败'
                    });
                });
        });

        em.on('reject', error => {
            res.json(error);
        });


        if (!inValid) {
            return em.emit('resolve');
        }

        em.emit('reject', {
            code: 400,
            message: '请填写手机号'
        });
    },

    /**
     * 验证码校验
     * @param req
     * @param res
     */
    check(req, res) {
        console.log(req, res);
    },

    /**
     * 验证码登录
     * @param req
     * @param res
     * @param next
     */
    login(req, res, next) {
        const code = (req.body.code || '').trim();
        const area = _.get(req.session, 'smsLogin.area', '');
        const mobile = _.get(req.session, 'smsLogin.mobile', '');
        const toSignUp = (req.body.toSignUp || '').trim() || false;

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

        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 => {
                const res0 = result[0] || {};
                const res1 = result[1] || {};

                if (res0.code !== 200) {
                    res.json(res0);
                    return;
                }

                if (res1.code !== 200) {
                    res.json(res1);
                    return;
                }

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

                    return;
                }

                // 未注册
                if (res0.data.is_register !== 'Y') {
                    if (toSignUp) {
                        // TODO 对于想要注册的用户直接注册
                    } else {
                        res.json({
                            code: 200,
                            data: {
                                avatar: '',
                                name: `匿名用户${Math.random() * 100000}`,
                            },
                            message: ANONYMOUS_USER
                        });
                    }
                    return;
                }

                // 已注册
                PhoneService.autoSignin({
                    profile: mobile,
                    code: res1.data.code,
                    area
                })
                    .then(info => {
                        if (info.code !== 200) {
                            return res.json({
                                code: info.code,
                                data: GET_USER_INFO_FAILED
                            });
                        }

                        const uid = info.data.uid;
                        const sessionKey = info.data.session_key;

                        return AuthHelper.syncUserSession(uid, req, res, sessionKey);
                    })
                    .then(() => {
                        res.json({
                            code: 200,
                            data: req.session.user,
                            message: LOGIN_SUCCESS
                        });
                    })
                    .catch(error => {
                        res.json(error);
                    });

            })
            .catch(next);
    }
};

module.exports = sms;