captcha-controller.js 1.68 KB
/**
 * 用户controller
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2017/04/13
 */
const _ = require('lodash');
const uuid = require('uuid');
const request = require('request');
const Context = require('../framework/context');
const captchaData = require('../common/captcha');

class CaptchaController extends Context {
    constructor() {
        super();
    }
    captcha(req, res) {
        let random = _.random(0, captchaData.length);
        let captcha = captchaData[random];

        let codeStr = captcha.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 = captcha.verifiedGraphicCode;
        return request(`${captcha.verifiedGraphicCode}?imageView2/0/format/jpg/q/70|watermark/2/text/${uuid.v4()}/fontsize/120/dissolve/10`).pipe(res); // eslint-disable-line
    }
    check(req, res, next) {
        // let isCaptcha = req.session.isCaptcha;

        // if (isCaptcha) {
        if (req.body.captcha === req.session.captcha) {
            if (new Date().getTime() > req.session.captchaTimeout) {
                return res.json({
                    code: 400,
                    captcha: true,
                    expired: true,
                    message: '验证码过期'
                });
            }
            return next();
        } else {
            return res.json({
                code: 400,
                captcha: true,
                message: '验证码错误'
            });
        }

        // }
        // return next();
    }
}

module.exports = CaptchaController;