captcha.js 1.66 KB
/**
 * Created by TaoHuang on 2016/6/18.
 */

'use strict';

const Captchapng = require('captchapng');
const _ = require('lodash');

const helpers = global.yoho.helpers;

const requiredAPI = (req, res, next) => {
    let captchaToken = +(req.body.verifyCode || '').toLowerCase();

    if (captchaToken === req.session.captcha) {
        return next();
    } else {
        return res.json({
            code: 400,
            message: '您输入的验证码不正确!'
        });
    }
};

const requiredPage = (req, res, next) => {
    let captchaToken = +(req.body.verifyCode || '').toLowerCase();

    if (captchaToken === req.session.captcha) {
        return next();
    } else {
        return res.redirect(helpers.urlFormat('/passport/back/index'));
    }
};


const _generateCaptcha = (width, height, length) => {
    let min = Math.pow(10, (length - 1 || 1));
    let max = Math.pow(10, (length - 1 || 1)) * 9;
    let token = '' + _.random(min, max);

    let png = new Captchapng(width, height, token);//

    png.color(0, 0, 0, 0);  // First color: background (red, green, blue, alpha)
    png.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)

    return {
        image: new Buffer(png.getBase64(), 'base64'),
        text: token
    };
};

const generate = (req, res) => {
    let width = req.query.w || 150;
    let height = req.query.h || 50;
    let length = +(req.query.l || 4);
    let captcha = _generateCaptcha(width, height, length);

    req.session.captcha = captcha.text;
    res.writeHead(200, {
        'Content-Type': 'image/png'
    });

    res.end(captcha.image);
};

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