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

'use strict';

const captcha = require('../models/captcha-service');
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.html'));
    }
};

const validate = (req, res, next) => {

};

const generatePage = (req, res, next) => {
    let len = req.query.len || 4;

    captcha.generateAsync(len)
        .then(result => {
            req.session.captcha = result.text.toLowerCase();
            res.writeHead(200, {'Content-Type': 'image/png'})
            res.send(result.image, 'binary');
        })
        .catch(next);
};

module.exports = {
    requiredAPI,
    requiredPage,
    validate,
    generatePage
};