img-captcha.js 1.82 KB
/**
 * Created by TaoHuang on 2016/6/18.
 */

/**
 * 验证码的形式: xxxx|page
 */

const CaptchaServiceModel = require('../models/captcha-img-service');
const request = require('request');

// 对比函数
const _mustEqualAsync = (req) => {
    let id = req.session.id;
    let verifyCode = req.body.verifyCode;

    if (!id || !verifyCode) {
        return Promise.resolve({
            code: 405,
            message: '请将所有图片点击翻转至正向朝上'
        });
    }

    return req.ctx(CaptchaServiceModel).check(id, verifyCode);
};

// 中间件
const requiredAPI = (req, res, next) => {
    _mustEqualAsync(req).then((result) => {
        if (result.code === 200) {
            return next();
        } else {
            return res.json({
                code: 405,
                message: result.message,
                data: {
                    needCaptcha: true
                }
            });
        }
    }).catch(next);
};

// 七牛验证码
const generate = (req, res, next) => {
    req.ctx(CaptchaServiceModel).generateCaptcha(req.session.id).then((result) => {
        req.session.captchaCount = 0;
        req.session.captchaTime = new Date().getTime();

        res.type('png');
        if (result.code === 200) {
            request({
                url: result.data.url,
                headers: {
                    'X-request-ID': req.reqID || '',
                    'X-YOHO-IP': req.yoho.clientIp || '',
                    'X-Forwarded-For': req.yoho.clientIp || '',
                    'User-Agent': 'yoho/nodejs'
                }
            }).pipe(res);
        }

    }).catch(next);
};

// 端到端检查
const checkAPI = (req, res, next) => {
    _mustEqualAsync(req).then(result => {
        res.json(result);
    }).catch(next);
};

module.exports = {
    requiredAPI,
    generate,
    checkAPI
};