captcha.js 2.88 KB
'use strict';

const _ = require('lodash');
const logger = global.yoho.logger;
let imgCheckAPI = require('../models/imgcheck');
const request = require('request');
const uuid = require('uuid');

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

    return imgCheckAPI.gen().then(result => {
        if (result.code === 200 && result.data) {
            let codeStr = result.data.degrees.reduce((str, rotate) => {
                return str.concat((4 - rotate / 90 % 4) % 4);
            }, '');

            req.session.captcha = codeStr;
            req.session.captchaSrc = result.data.verifiedGraphicCode;

            data.src = `/passport/img-check.jpg?t=${Date.now()}`;

            return res.json(data);
        }

        next();
    }).catch(next);
};


exports.imgCheck = (req, res, next) => {
    return imgCheckAPI.gen().then(result => {
        if (result.code === 200 && result.data) {
            let codeStr = result.data.degrees.reduce((str, rotate) => {
                return str.concat((4 - rotate / 90 % 4) % 4);
            }, '');

            req.session.captcha = codeStr;
            req.session.captchaTimeout = new Date().getTime() + 1000 * 60;
            req.session.captchaSrc = result.data.verifiedGraphicCode;

            return request(`${result.data.verifiedGraphicCode}?imageView2/0/format/jpg/q/70|watermark/2/text/${uuid.v4()}/fontsize/120/dissolve/10`).pipe(res); // eslint-disable-line
        }
        next();
    }).catch(next);
};

/**
 * 验证img-check验证码
 */
exports.validate = (req, res, next) => {
    let captchaInput = req.body.captcha;
    let captchaCode = _.get(req.session, 'captcha');
    let captchaTimeout = _.get(req.session, 'captchaTimeout');

    if (new Date().getTime() > captchaTimeout) {
        _.set(req.session, 'captchaValidCount', 5);
        req.session.captcha = null;
        return res.json({
            code: 400,
            message: '验证码超时,请重试',
            changeCaptcha: true,
            captchaShow: true
        });
    }

    let errorCount = _.get(req.session, 'captchaValidCount'); // 初始1次 + 后续4次, 同一个验证码 共5次

    let jsonData = {
        code: 400,
        message: '请将图片旋转到正确方向',
        captchaShow: true
    };

    logger.info(`captcha validate result${(captchaInput && captchaInput.toString()) === captchaCode},user:${captchaInput};server:${captchaCode}`); // eslint-disable-line

    _.set(req.session, 'captchaValidCount', errorCount - 1);

    if (!errorCount) {
        _.set(req.session, 'captchaValidCount', 5);
        req.session.captcha = null;
        jsonData.changeCaptcha = true;
    }

    if (!(captchaInput && captchaCode && captchaInput === captchaCode)) {
        return res.json(jsonData);
    }
    req.session.captcha = null;
    req.session.captchaValidCount = null;
    req.session.useYohoCaptcha = null;
    return next();
};