captcha.js 1.73 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, next) => {
    captchaService.generateCaptcha().then((result) => {
        req.session.captcha = result.data.text;

        if (result.code === 200) {
            return res.json({
                code: result.code,
                data: {
                    images: result.data.images
                }
            });
        } else {
            return res.json({
                code: result.code,
                message: result.message
            });
        }

    }).catch(next);
};

// ajax 异步调用
const checkAPI = (req, res) => {
    let captchaToken = req.body.verifyCode || '';

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

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