captcha.js 1.69 KB
/* eslint-disable newline-after-var */
/* eslint-disable quotes */
'use strict';

const tencentcloud = require('tencentcloud-sdk-nodejs');
const logger = global.yoho.logger;

const CaptchaClient = tencentcloud.captcha.v20190722.Client;
const models = tencentcloud.captcha.v20190722.Models;

const Credential = tencentcloud.common.Credential;
const ClientProfile = tencentcloud.common.ClientProfile;
const HttpProfile = tencentcloud.common.HttpProfile;

const { secretId, secretKey, AppSecretKey, appId } = global.yoho.config.captcha;

let cred = new Credential(secretId, secretKey);

let httpProfile = new HttpProfile();
httpProfile.endpoint = 'captcha.tencentcloudapi.com';
let clientProfile = new ClientProfile();
clientProfile.httpProfile = httpProfile;

let client = new CaptchaClient(cred, 'ap-shanghai', clientProfile);

let captchaReq = new models.DescribeCaptchaResultRequest();

/**
 * 优惠券防刷验证码
 */
module.exports = function(req, res, next) {
    if (!req.couponCheckRequired) {
        return next();
    }

    if (!(req.query.ticket && req.query.randstr)) {
        return res.jsonp({ code: 400, message: '没有验证信息' });
    }

    const params = {
        AppSecretKey,
        CaptchaAppId: appId,
        CaptchaType: 9,
        UserIp: req.yoho.clientIp,
        Ticket: req.query.ticket,
        Randstr: req.query.randstr
    };

    captchaReq.from_json_string(JSON.stringify(params));

    // eslint-disable-next-line new-cap
    client.DescribeCaptchaResult(captchaReq, function(errMsg) {
        if (errMsg) {
            logger.error('tencent captcha fail ', req.user.uid);
            return res.jsonp({ code: 400, message: errMsg.Message });
        }
        next();
    });
};