captcha.js 2.56 KB
'use strict';

const imgCheckServiceModel = require('../models/imgcheck');
const request = require('request');

exports.get = (req, res, next) => {
    let data = {
        src: ''
    };
    let udid = req.cookies.udid;

    return req.ctx(imgCheckServiceModel).gen(udid).then(result => {
        if (result.code === 200 && result.data) {
            data.src = `/passport/img-check?t=${Date.now()}`;

            return res.json(data);
        }
        next();
    }).catch(next);
};

exports.imgCheck = (req, res, next) => {
    let udid = req.cookies.udid;

    return req.ctx(imgCheckServiceModel).gen(udid).then(result => {
        if (result.code === 200 && result.data) {
            return request({
                url: result.data.verifiedGraphicCode,
                headers: {
                    'X-request-ID': req.reqID || '',
                    'X-YOHO-IP': req.yoho.clientIp || '',
                    'X-Forwarded-For': req.yoho.clientIp || '',
                    'User-Agent': 'yoho/nodejs'
                }
            }).pipe(res); // eslint-disable-line
        }
        next();
    }).catch(next);
};

exports.imgCheckRisk = (req, res, next) => {
    if (!req.session.apiRiskValidate) {
        return next();
    }

    return req.ctx(imgCheckServiceModel).getRiskCheckImg(req.cookies.udid).then(result => {
        return request({
            url: result,
            headers: {
                'X-request-ID': req.reqID || '',
                'X-YOHO-IP': req.yoho.clientIp || '',
                'X-Forwarded-For': req.yoho.clientIp || '',
                'User-Agent': 'yoho/nodejs'
            }
        }).on('response', response => {
            // status code 204 接口关闭图形验证码,通过cookie通知验证页刷行切换验证方式
            if (response.statusCode === 204) {
                res.cookie('refresh_page', 1, {
                    path: '/',
                    maxAge: 60000
                });

                delete req.session.apiRiskValidate;
                req.session.apiRiskClear = true;

                return res.json({code: 204});
            }
        }).pipe(res); // eslint-disable-line
    }).catch(next);
};

/**
 * 验证img-check验证码
 */
exports.validate = (req, res, next) => {
    // let udid = req.cookies.udid;
    // let captchaInput = req.body.captcha;

    // return req.ctx(imgCheckServiceModel).check(udid, captchaInput).then(result => {
    //     if (result.code === 200) {
    //         return next();
    //     } else {
    //         return res.json(result);
    //     }
    // });

    return next();
};