Blame view

apps/passport/controllers/img-captcha.js 1.81 KB
htoooth authored
1 2 3 4
/**
 * Created by TaoHuang on 2016/6/18.
 */
htoooth authored
5 6 7
/**
 * 验证码的形式: xxxx|page
 */
htoooth authored
8
htoooth authored
9
const CaptchaServiceModel = require('../models/captcha-img-service');
htoooth authored
10
const request = require('request');
htoooth authored
11
const {CAPTCHA_SWITCH, CAPTCHA_TYPE} = require('../models/captcha-type');
htoooth authored
12 13

// 对比函数
htoooth authored
14 15 16 17 18 19 20 21 22 23
const _mustEqualAsync = (req) => {
    let id = req.session.id;
    let verifyCode = req.body.verifyCode;

    if (!id || !verifyCode) {
        return Promise.resolve({
            code: 405,
            message: '请将所有图片点击翻转至正向朝上'
        });
    }
htoooth authored
24
htoooth authored
25
    return req.ctx(CaptchaServiceModel).check(id, verifyCode);
htoooth authored
26 27 28 29
};

// 中间件
const requiredAPI = (req, res, next) => {
htoooth authored
30
    next();
htoooth authored
31 32
};
htoooth authored
33
// 验证码
htoooth authored
34
const generate = (req, res, next) => {
htoooth authored
35
    req.ctx(CaptchaServiceModel).generateCaptcha(req.session.id).then((result) => {
htoooth authored
36 37
        res.type('png');
        if (result.code === 200) {
htoooth authored
38 39 40 41 42 43 44 45 46
            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);
htoooth authored
47 48 49 50 51 52
        }

    }).catch(next);
};

// 端到端检查
htoooth authored
53 54 55 56
const checkAPI = (req, res, next) => {
    _mustEqualAsync(req).then(result => {
        res.json(result);
    }).catch(next);
htoooth authored
57 58
};
htoooth authored
59 60
const trySwitch = (req) => {
    return req.ctx(CaptchaServiceModel).try().then((result) => {
htoooth authored
61
        const captcha = {
htoooth authored
62
            type: CAPTCHA_TYPE.image,
htoooth authored
63 64 65
            value: result ? CAPTCHA_SWITCH.on : CAPTCHA_SWITCH.off
        };
htoooth authored
66
        req.session.captcha = captcha;
htoooth authored
67
        req.app.locals.captcha = captcha;
htoooth authored
68
    });
htoooth authored
69 70
};
htoooth authored
71 72 73
module.exports = {
    requiredAPI,
    generate,
htoooth authored
74 75
    checkAPI,
    trySwitch
htoooth authored
76
};