如何将Google的reCaptcha整合到内部:autoform(meteor)

时间:2015-08-13 16:17:37

标签: javascript meteor

我要做的是阻止用户绕过验证码。现在,在联系表单上,用户可以填写除验证码之外的所有字段,并使表单仍然提交

以下是显示联系表单的网页 - > 这是页面 - > http://ec2-52-5-104-185.compute-1.amazonaws.com/contact

以下是显示此联系表单的代码 - >

{{# autoForm schema='ContactSchema' id="contactForm" type="method" meteormethod="sendContact"}}
    {{> afQuickField name="categoryId"}}                       
    {{> afQuickField name="email" }}
    {{> afQuickField name="title" }}
    {{> afQuickField name="message" rows=8 }}

    <!-- googles reCaptcha , i'm using ayue:recaptcha  package to render this captcha -->
    {{> reCAPTCHA}}
{{/ autoForm }} 

这是客户端JS meteor调用验证码

Template.contact.events({
    'submit form': function(e) {
        e.preventDefault();

        var formData = {
            //get the data from your form fields
        };

        //get the captcha data
        var recaptchaResponse = grecaptcha.getResponse();

        Meteor.call('formSubmissionMethod', formData, recaptchaResponse, function(error, result) {
            if (error) {
                console.log('There was an error: ' + error.reason);
            } else {
                console.log('Success!');
            }
        });
    }
});

以下是从联系表单中获取sendContact方法的服务器端代码以及recaptcha meteor.call方法

Meteor.methods({
    formSubmissionMethod: function(formData, recaptchaResponse) {

        var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(recaptchaResponse, this.connection.clientAddress);

        if (!verifyCaptchaResponse.success) {
            console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
            throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
        } else {
            console.log('reCAPTCHA verification passed!');
        }

        //do stuff with your formData

        return true;
    },

    sendContact: function (doc) {
        check(doc, ContactSchema);

        var html = "<b>" + doc.title + "</b><br>"
        + "<b>" + doc.email + "</b><br><br>"
        + doc.message.escape();

        this.unblock();

        Email.send({
            to: orion.dictionary.get('contact form.email') && doc.categoryId,
            from: orion.config.get('MAIL_FROM'),
            // subject: orion.dictionary.get('global.siteName') + ' - Contact',
            subject: doc.title + ' - Contact',
            replyTo: doc.email,
            html: html
        })
    }
});

1 个答案:

答案 0 :(得分:2)

不要在服务器端方法上抛出错误,只需返回成功值,如:

verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, doc.gRecaptchaResponse);

  if (verifyCaptchaResponse.data.success === false) {
    return verifyCaptchaResponse.data;
  }

在回调中回到客户端,执行以下操作:

if (result && result.success === false) {
      //CAPTCHA failed
      Modal.show('recaptcha');
    }
return false;

而不是使用提交表单&#39;事件,使用AutoForm.hooks,然后使用AutoForm.hooks中的onSubmit方法为您的表单。