captcha.js 2.24 KB
/**
 * 图形验证码
 * Created by TaoHuang on 2016/6/18.
 */

'use strict';

const captchaService = require('../models/captcha-service');
const helpers = global.yoho.helpers;

/**
 * 验证图形验证码中间件,返回JSON
 */
const requiredAPI = (req, res, next) => {
    let captchaToken = req.body.verifyCode || '';
    let count = req.session.captchaCount;

    if (count >= 4) {
        return res.json({
            code: 403,
            captchaCount: false,
            message: '该验证码已失效'
        });
    }

    req.session.captchaCount = count + 1;

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

/**
 * 验证图形验证码,失败后跳转页面
 */
const requiredPage = (req, res, next) => {
    let captchaToken = req.body.verifyCode || '';

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

/**
 * 生成图形验证码
 */
const generate = (req, res) => {
    let width = req.query.w || 150;
    let height = req.query.h || 50;
    let length = +(req.query.l || 4);
    let captcha = captchaService.generateCaptcha(width, height, length);

    req.session.sendMobile = '';
    req.session.captcha = captcha.text;
    req.session.captchaCount = 0;

    res.writeHead(200, {
        'Content-Type': 'image/png'
    });

    res.end(captcha.image);
};

/**
 * 验证图形码
 */
const requiredPost = (req, res) => {
    let captchaToken = req.body.verifyCode || '';
    let count = req.session.captchaCount;

    if (count >= 4) {
        return res.json({
            code: 403,
            captchaCount: false,
            message: '该验证码已失效'
        });
    }

    req.session.captchaCount = count + 1;

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

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