captcha.js 2.24 KB
/**
 * Created by TaoHuang on 2016/6/18.
 */

'use strict';
const _ = require('lodash');
const gee = require('./gee-captcha');
const img = require('./img-captcha');

const {CAPTCHA_SWITCH, CAPTCHA_TYPE} = require('../models/captcha-type');


const isGeetest = (req) => {
    return _.get(req.session, 'captcha.type', 'geetest') === CAPTCHA_TYPE.geetest;
};

function required(req, res, next) {
    img.trySwitch(req, res).then(() => {
        if (req.session.captcha.type === CAPTCHA_TYPE.image && req.session.captcha.value === CAPTCHA_SWITCH.off) {
            const captcha = {
                type: CAPTCHA_TYPE.geetest,
                value: CAPTCHA_SWITCH.on
            };

            req.session.captcha = captcha;
            res.locals.captcha = captcha;
        }
        next();
    }).catch(next);
}

const requiredAPI = (req, res, next) => {
    return (isGeetest(req) ? gee.requiredAPI : img.requiredAPI)(req, res, next);
};

const generate = (req, res) => {
    return (isGeetest(req) ? gee.generate : img.generate)(req, res);
};

// 端到端检查
const checkAPI = (req, res) => {
    return (isGeetest(req) ? gee.checkAPI : img.checkAPI)(req, res);
};

const passwordRequired = (req, res, next) => {
    // 默认账户密码登录需要验证码
    if (req.body.loginType === 'password') {
        return requiredAPI(req, res, next);
    }

    return next();
};

const imgGenerateRisk = img.generateRisk;

const geeCheck = gee.requiredAPI;

const geeGenerate = gee.generate;

const geeOnly = function(req, res, next) {
    const captcha = {
        type: CAPTCHA_TYPE.geetest,
        value: CAPTCHA_SWITCH.on
    };

    req.session.captcha = captcha;
    res.locals.captcha = captcha;

    next();
};

const requiredWithRisk = (req, res, next) => {
    if (!req.session.apiRiskValidate) {
        return geeOnly(req, res, next);
    }

    const captcha = {
        type: CAPTCHA_TYPE.image,
        value: CAPTCHA_SWITCH.on,
        apiRisk: true
    };

    req.session.captcha = captcha;
    res.locals.captcha = captcha;

    next();
};

module.exports = {
    requiredAPI,
    required,
    generate,
    checkAPI,
    passwordRequired,
    geeOnly,
    requiredWithRisk,
    CAPTCHA_SWITCH,
    CAPTCHA_TYPE,
    imgGenerateRisk,
    geeCheck,
    geeGenerate
};