back.js 9.62 KB
/**
 * 找回密码
 * Created by Tao.Huang on 2016/6/12.
 */

'use strict';

const helpers = global.yoho.helpers;
const BackService = require('../models/back-service');
const PassportHelper = require('../models/passport-helper');
const _ = require('lodash');

const index = (req, res, next) => {
    BackService.indexPageDataAsync()
        .then(result => {
            res.display('back/index', Object.assign({
                module: 'passport',
                page: 'back-index',
                title: '找回密码',
                defaultHeader: false
            }, result));
        })
        .catch(next);
};

const validateInputAPI = (req, res, next) => {
    let userInput = req.body.phoneNum || '';
    let areaCode = (req.body.area || '86').replace('+', '');

    BackService.validateEmailOrMobileAsync(userInput, areaCode)
        .then(result => {
            req.inputInfo = result;
            next();
        })
        .catch(err => {
            res.json({
                code: 400,
                message: err
            });
        });
};

const validateInputPage = (req, res, next) => {
    let userInput = req.body.phoneNum || '';
    let areaCode = (req.body.area || '86').replace('+', '');

    BackService.validateEmailOrMobileAsync(userInput, areaCode)
        .then(result => {
            req.inputInfo = result;
            next();
        })
        .catch(()=> {
            res.redirect(helpers.urlFormat('/passport/back/index'));
        });
};

const getUserInfoAPI = (req, res, next) => {
    let inputInfo = req.inputInfo;

    BackService.findUserAsync(inputInfo.type, inputInfo.phone, inputInfo.area)
        .then(result => {
            res.json(result);
        })
        .catch(next);
};

const sendCodePage = (req, res, next) => {
    let inputInfo = req.inputInfo;

    BackService.sendCodeToUserAsync(inputInfo.type, inputInfo.phone, inputInfo.area)
        .then(result => {
            if (!(result.code && result.code === 200)) {
                return res.redirect(helpers.urlFormat('/passport/back/index'));
            }

            return next();
        })
        .catch(next);
};

const saveInSession = (req, res) => {
    switch (req.inputInfo.type) {
        case 'email':
            req.session.email = req.inputInfo.phone;
            res.redirect(helpers.urlFormat('/passport/back/sendEmail'));
            break;
        case 'mobile':
            req.session.mobile = req.inputInfo.phone;
            req.session.area = req.inputInfo.area;
            req.session.verifyCode = req.session.captcha;
            res.redirect(helpers.urlFormat('/passport/back/verification'));
            break;
        default:
            res.redirect(helpers.urlFormat('/passport/back/index'));
            break;
    }
};

const sendBackMobileAPI = (req, res, next) => {
    let mobile = req.body.mobile || '';
    let area = req.body.area || '86';

    BackService.sendCodeToMobileAsync(area, mobile)
        .then(result => {
            res.json(result);
        })
        .catch(next);
};

const validateMobileAPI = (req, res, next) => {
    let mobile = req.body.mobile || '';
    const ERR = {code: 400, message: '验证失败'};

    if (!PassportHelper.validator.verifyMobile(mobile)) {
        return res.json(ERR);
    }

    next();
};

const validateEmailInSession = (req, res, next) => {
    let email = req.session.email || '';

    if (!email) {
        return res.redirect(helpers.urlFormat('/passport/back/index'));
    }

    let isp = email.split('@')[1].toLowerCase();
    const mapperEmailISP = {
        'yoho.cn': 'http://exmail.qq.com/login'
    };

    req.body.emailUrl = mapperEmailISP[isp] || `http://mail.${isp}`;
    next();
};

const sendEmailPage = (req, res) => {
    res.display('back/send-email', Object.assign({
        module: 'passport',
        page: 'back-send-email-ok',
        title: '邮件发送成功',
        defaultHeader: false
    }, {
        sendEmail: {
            email: req.body.emailUrl
        }
    }));
};

const validateCodeByEmailPage = (req, res, next) => {
    let code = req.query.code || '';

    if (!_.isEmpty(req.mobileAuth)) {
        return next();
    }

    BackService.checkEmailCodeAsync(code)
        .then(result => {
            if (!result) {
                return res.redirect(helpers.urlFormat('/passport/back/index'));
            }

            return next();
        })
        .catch(next);
};

const resetPasswordPage = (req, res) => {
    let code = req.query.code || '';

    res.display('back/reset-pwd', Object.assign({
        module: 'passport',
        page: 'back-reset-pwd',
        title: '重置密码',
        defaultHeader: false
    }, {
        resetPwd: Object.assign({
            code: code
        }, req.mobileAuth)
    }));
};

const verifyCodeByMobilePage = (req, res) => {

    res.display('back/verification', Object.assign({
        module: 'passport',
        page: 'back-verify-mobile-code',
        title: '手机验证',
        defaultHeader: false
    }, {
        verification: {
            mobile: req.body.mobile,
            area: req.body.area,
            verifyCode: req.body.verifyCode
        }
    }));
};

const validateSuccessStatusPage = (req, res, next) => {
    let successType = req.session.successType || '';

    if (!successType) {
        return res.redirect(helpers.urlFormat('/passport/back/index'));
    }

    delete req.session.successType;
    next();
};

const resetPwdSuccessPage = (req, res) => {
    res.display('back/reset-success', Object.assign({
        module: 'passport',
        page: 'back-reset-success',
        title: '重置密码成功',
        defaultHeader: false
    }));
};

const verifyCodeByMobileAPI = (req, res) => {
    let mobile = req.body.mobile || '';
    let area = req.body.area || '86';
    let mobileCode = req.body.code || '';
    const ERR = {
        code: 400,
        message: '验证码错误!',
        data: helpers.urlFormat('/passport/back/index')
    };

    const session = req.session;

    if (!mobileCode || mobile !== session.mobile || area !== session.area) {
        return res.json(ERR);
    }

    BackService.verifyCodyByMobileAsync(area, mobile, mobileCode)
        .then(result => {
            res.json(result);
        })
        .catch(()=> {
            res.json(ERR);
        });
};

const validateExistCodePage = (req, res, next) => {
    let code = req.query.code || req.body.code;

    if (!code) {
        return res.redirect(helpers.urlFormat('/passport/back/index'));
    }

    next();
};

const validateCodeByMobilePage = (req, res, next) => {
    let code = req.query.code || req.body.code;
    let mobile = req.query.mobile || req.body.mobile;
    let area = req.query.area || req.body.area;
    let token = req.query.token || req.body.token;
    let createdAt = req.query.createdAt || req.body.createdAt;

    if (!mobile) {
        req.mobileAuth = {};
        return next();
    }

    let data = {
        mobile: mobile,
        area: area,
        token: token,
        createdAt: createdAt
    };

    code = new Buffer(code, 'base64').toString();
    req.mobileAuth = BackService.authRequest(data, code);

    next();
};

const validatePwdPage = (req, res, next) => {
    let pwd = req.body.pwd || '';

    if (!PassportHelper.validator.verifyPassword(pwd)) {
        return res.redirect(helpers.urlFormat('/passport/back/index'));
    }

    next();
};

const updatePwdAPI = (req, res, next) => {
    let code = req.body.code || '';
    let mobileAuth = req.mobileAuth || {};
    let newPassword = req.body.pwd || '';

    BackService.updatePwdAsync(code, mobileAuth, newPassword)
        .then(result => {
            if (result.status) {
                req.session.successType = result.type;
                res.redirect(helpers.urlFormat('/passport/back/resetSuccess'));
            } else {
                res.redirect(helpers.urlFormat('/passport/back/index'));
            }
        })
        .catch(next);
};

const validateMobileInSession = (req, res, next) => {
    req.body.mobile = req.session.mobile || '';
    req.body.verifyCode = req.session.captcha || '';
    req.body.area = req.session.area || '';

    if (!(req.body.mobile && req.body.verifyCode)) {
        return res.redirect(helpers.urlFormat('/passport/back/index'));
    }

    next();
};

module.exports = {
    index,                         // 首页
    getUserInfoAPI,                // 通过邮箱或手机号获得用户信息
    sendCodePage,                  // 发送验证码到邮箱或者手机,然后跳转页面
    saveInSession,                 // 保存状态到session中

    sendEmailPage,                 // 发送邮件成功的页面

    verifyCodeByMobilePage,        // 验证手机验证码的页面
    verifyCodeByMobileAPI,         // 验证手机验证码
    sendBackMobileAPI,             // 重新发送验证码到手机

    resetPasswordPage,             // 重设密码页面
    updatePwdAPI,                  // 重设密码接口
    validateMobileAPI,             // 验证手机号是否合法
    resetPwdSuccessPage,           // 重设密码成功页面

    validateInputAPI,              // 验证用户输入的邮箱或者手机是否合法,返回是json
    validateInputPage,             // 验证用户输入的邮箱或者手机是否合法,跳转是页面

    validateEmailInSession,        // 验证邮箱是否在session中
    validateMobileInSession,       // 验证手机是否在session中

    validateCodeByEmailPage,       // 验证邮箱验证码
    validateCodeByMobilePage,      // 验证手机验证码

    validateSuccessStatusPage,     // 验证重设密码状态
    validateExistCodePage,         // 验证参数是否存在code

    validatePwdPage                // 验证密码是否合法
};