'use strict';

/**
 * 验证码
 *
 * @author CaiAoLin
 * @date 2017/10/13
 * @version
 */
const Geetest = require('gt3-sdk');
class Captcha {

    /**
     * 构造函数
     *
     * @param {Object} app - egg中的全局变量app(用于获取配置)
     * @return {void}
     */
    constructor(app) {
        this.captcha = new Geetest({
            geetest_id: app.config.geetest.id,
            geetest_key: app.config.geetest.key,
        });
    }

    /**
     * 验证码注册
     *
     * @param {Object} ctx - egg中的全局变量context
     * @return {String} - 返回生成所需的json数据
     */
    async register(ctx) {
        let response = {
            success: 0,
        };
        try {
            const data = await this.captcha.register(null);
            ctx.session.fallback = !data.success;
            response = data;
        } catch (error) {
            response.success = 0;
            response.message = error;
            JSON.stringify(response);
        }

        return response;
    }

    /**
     * 验证码校验
     *
     * @param {Object} ctx - egg中的全局变量context
     * @return {Boolean} - 返回是否校验成功
     */
    async validate(ctx) {
        let result = false;

        const challenge = ctx.request.body.geetest_challenge;
        const validate = ctx.request.body.geetest_validate;
        const seccode = ctx.request.body.geetest_seccode;

        try {
            if (challenge === '' || validate === '' || seccode === '') {
                throw '参数错误';
            }
            const fallback = ctx.session.fallback;

            result = await this.captcha.validate(fallback, {
                geetest_challenge: challenge,
                geetest_validate: validate,
                geetest_seccode: seccode,
            });

        } catch (error) {
            result = false;
        }

        return result;
    }
}
module.exports = Captcha;
