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

'use strict';

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

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

    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.captcha = captcha.text;

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

    res.end(captcha.image);
};

const requiredPost = (req, res) => {
    let captchaToken = req.body.verifyCode || '';

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

module.exports = {
    requiredAPI,  // 中间件的验证
    requiredPage, // 跳转页面的验证
    generate,     // 生成验证码
    requiredPost  // 端点验证码
};