common.captcha.js 1.54 KB

'use strict';

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

var Utils = {
    generateCaptcha: function (width, height, length) {
        var min = Math.pow(10, (length - 1 || 1));
        var max = Math.pow(10, (length - 1 || 1)) * 9;
        var token = '' + _.random(min, max);
        var 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
        };
    }
};

module.exports = {
    namespace: "captcha",
    apis: {
        create: function (req, callback) {
            var width = req.query.w || 150;
            var height = req.query.h || 50;
            var length = +(req.query.l || 4);
            var captcha = Utils.generateCaptcha(width, height, length);
            req.session.captcha = captcha.text;
            return callback(null, captcha.image);
        },
        checkCaptchaImg: function (req, callback) {
            var captchaToken = req.body.verifyCode || '';
            if (captchaToken === req.session.captcha) {
                return callback(null, {
                    code: 200,
                    message: '验证成功'
                });
            } else {
                return callback(null, {
                    code: 400,
                    message: '您输入的验证码不正确!'
                });
            }
        }


    }
};