gee-captcha-controller.js 1.92 KB
/**
 * 用户controller
 * @author: shuiling.wang<shuiling.wang@yoho.cn>
 * @date: 2017/10/17
 */
const Context = require('../framework/context');
const Geetest = require('gt3-sdk');
const logger = global.yoho.logger;

const pcGeetest = new Geetest({
  geetest_id: '4bf7f911856073c1347247667790e7c4',
  geetest_key: '8d41283971d071216f1cef3d190d6b44',
});

class GeeCaptchaController extends Context {
  constructor() {
    super();
  }
  captcha(req, res) {
    return pcGeetest.register(
      {
        client_type: 'web',
      },
      function(err, data) {
        if (err) {
          logger.error(err);
          return res.json({ code: 500 });
        }

        if (!data.success) {
          req.session.fallback = true;
          return res.json({
            code: 501,
            data,
          });
        } else {
          // 正常模式
          req.session.fallback = false;
          return res.send({
            code: 200,
            data,
          });
        }
      }
    );
  }
  check(req, res, next) {
    const verifyCode = req.body.captcha || '';

    if (!verifyCode) {
      return res.send({
        code: 405,
        message: '请将图形验证码拖动至正确位置',
      });
    }

    pcGeetest.validate(
      req.session.fallback,
      {
        geetest_challenge: verifyCode[0],
        geetest_validate: verifyCode[1],
        geetest_seccode: verifyCode[2],
      },
      function(err, success) {
        // logger.info(`geetest captcha auth [${err ? 'fail' : 'success'}]`,
        //     `CLIENT [${req.body.verifyCode}] SERVER [${err}]`);

        if (err) {
          return res.send({
            message: '网络错误',
            code: 405,
          });
        } else if (!success) {
          return res.send({
            message: '图形验证失败',
            code: 405,
          });
        } else {
          return next();
        }
      }
    );
  }
}

module.exports = GeeCaptchaController;