captcha.js 1.43 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.app.locals.pc, 'geetest.validation', false);
};

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

        req.session.capthca = captcha;
        req.app.locals.captcha = captcha;
        return next();
    } else {
        return img.trySwitch(req, res, 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 geeOnly = (req, res, next) => {
    const captcha = {
        type: CAPTCHA_TYPE.geetest,
        value: CAPTCHA_SWITCH.on
    };

    req.session.capthca = captcha;
    req.app.locals.captcha = captcha;
    return next();
};

const geeCheck = gee.requiredAPI;

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