geetest.js 1.63 KB
'use strict';
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
            // };

            if (!data.success) {
                req.session.useYohoCaptcha = true;
            }
            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
        };

        if (!challenge || !validate || !seccode) {
            return res.json(errRes);
        }

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

module.exports = geetest;