geetest.js 1.72 KB
'use strict';
const _ = require('lodash');
const Geetest = require('geetest');
const logger = global.yoho.logger;

const captcha = new Geetest({
    geetest_id: 'bce95d796bc3058615fdf2ec2c0aef29',
    geetest_key: '124c41d3a22aa48f36ae3cd609c51db5'
});

const geetest = {
    register(req, res, next) {
        captcha.register().then(function(data) {

            // data 为一个对象,包含 gt, challenge, success, new_captcha 字段
            // success 为 1 表示正常模式,为 0 表示宕机模式(failback, fallback)
            // var body = {
            //     gt: data.geetest_id,
            //     challenge: data.challenge,
            //     success: data.success
            // };

            res.send(data);
        }).catch(next);
    },
    validate(req, res, next) {
        let challenge = req.body.geetest_challenge,
            validate = req.body.geetest_validate,
            seccode = req.body.geetest_seccode;

        let errRes = {
            code: 400,
            message: '验证码错误',
            captchaShow: true,
            changeCaptcha: true
        };

        // 使用极验证
        let useGeetest = !_.get(req.app.locals.wap, 'geetest.validation', false);

        if (!useGeetest) {
            return next();
        }
        if (!challenge || !validate || !seccode) {
            return res.send(errRes);
        }

        captcha.validate({
            challenge,
            validate,
            seccode
        }).then(function(success) {
            if (success) {
                logger.info('geetest success');
                return next();
            }
            logger.info('geetest faild');
            return res.send(errRes);
        });
    }
};

module.exports = geetest;