استفاده از reCAPTCHA گوگل در Node.js
ﺯﻣﺎﻥ ﻣﻄﺎﻟﻌﻪ: 3 دقیقه

استفاده از reCAPTCHA گوگل در Node.js

کارهایی که میخواهیم در این مقاله انجام بدیم به شرح زیر است : 

  • ثبت فرم با استفاده از Ajax
  • دریافت کلید پاسخ گوگل در سرور Node.js
  • بازگردانی کلید و ارسال پاسخ به UI

برای ثبت فرم با Ajax ما از کتابخانه Jquery.form استفاده می کنیم. برای سرور ما از Express و برای صدا زدن HTTP از request بهره می بریم.

فایل Package.json

یک مسیر جدید ساخته و فایل package.json رو در اون ایجاد کنید. بهتره با استفاده از npm init این کار رو انجام بدیم. این فایل package.json ما هست :

{

  "name": "google-racapcha-node",

  "version": "1.0.0",

  "description": "",

  "main": "app.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "repository": {

    "type": "git",

    "url": "git+https://github.com/codeforgeek/google-racapcha-node.git"

  },

  "author": "Shahid shaikh",

  "license": "MIT",

  "bugs": {

    "url": "https://github.com/codeforgeek/google-racapcha-node/issues"

  },

  "homepage": "https://github.com/codeforgeek/google-racapcha-node#readme"

} 

نوبت نصب وابستگی هاست :

npm i --save express request body-parser

همینطور که اشاره شد ما از express بعنوان فریمورک وب, از request برای صدا زدن HTTP و از body-parser برای خروجی گرفتن از متغیرهای POST در Express استفاده می کنیم.

برای رابط کاربری از کتابخانه های زیر استفاده می کنیم :

jquery

jquery.form

ثبت سایت در Google reCAPTCHA

سایت خودتون رو در پلتفرم Google recaptcha ثبت کنید تا کلیدهای مورد نیاز در کد رو بدست بیارید. اینجا رو کلیک کنید تا وارد سایت Google recaptcha بشید.

بعد از ورود اطلاعات سایت رو وارد کنید.

بعد از ثبت نام در اون سایت شما کلید های Site Key و Secret Key رو دریافت می کنید.

ساخت فرم Google reCAPTCHA در HTML

این کد HTML ما برای ساخت یک فرم ساده ی reCAPTCHA هست :

<html>

  <head>

    <title>Google recapcha demo - Codeforgeek</title>

    <script src='https://www.google.com/recaptcha/api.js'></script>

  </head>

  <body>

    <h1>Google reCAPTHA Demo</h1>

    <form id="comment_form" action='/submit' method="post">

      <input type="email" placeholder="Type your email" size="40"><br><br>

      <textarea name="comment" rows="8" cols="39"></textarea><br><br>

      <div class="g-recaptcha" data-sitekey="--paste your site key here--"></div><br>

      <input type="submit" name="submit" value="Post comment"><br><br>

    </form>

  </body>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>

  <script>

   // Will put our custom code here.

  </script>

</html>

ما یک فرم ساده بهمراه اکشن submit/ ساختیم. مرورگر اطلاعات رو به آدرس url+'/submit' ارسال می کنه. ما به API خودمون نیاز داریم تا اتصال و دیتا POST رو تایید کنه. 

Site key که دریافت کردید رو به Google recaptcha div اضافه کنید. 

این کد جاوا اسکریپتی هست که ثبت ajax رو مدیریت می کنه :

 <script>

    $(document).ready(function() {

      $('#comment_form').submit(function() {

        $(this).ajaxSubmit({

          error: function(xhr) {

            status('Error: ' + xhr.status);

          },

         success: function(response) {

          console.log(response);

         }

        });

        //Very important line, it disable the page refresh.

        return false;

      });

    });

  </script>

این کد رو بعد از بارگذاری اسکریپت ها در صفحه html قرار بدید.

سرور Nodejs

فرم ما آمادست. بیاییم فایل سرور رو نوشته و مسیر submit/ رو که اشاره کردیم مدیریت کنیم.

فایل app.js

var express = require('express');

var bodyParser = require('body-parser');

var request = require('request');

var app = express();



app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended : false}));



app.get('/',function(req,res) {

  // Sending our HTML file to browser.

  res.sendFile(__dirname + '/index.html');

});



app.post('/submit',function(req,res){

  // g-recaptcha-response is the key that browser will generate upon form submit.

  // if its blank or null means user has not selected the captcha, so return the error.

  if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {

    return res.json({"responseCode" : 1,"responseDesc" : "Please select captcha"});

  }

  // Put your secret key here.

  var secretKey = "--paste your secret key here--";

  // req.connection.remoteAddress will provide IP address of connected user.

  var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;

  // Hitting GET request to the URL, Google will respond with success or error scenario.

  request(verificationUrl,function(error,response,body) {

    body = JSON.parse(body);

    // Success will be true or false depending upon captcha validation.

    if(body.success !== undefined && !body.success) {

      return res.json({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});

    }

    res.json({"responseCode" : 0,"responseDesc" : "Sucess"});

  });

});



// This will handle 404 requests.

app.use("*",function(req,res) {

  res.status(404).send("404");

})



// lifting the app on port 3000.

app.listen(3000);

اجرای اپلیکیشن

برای اجرای اپلیکیشن به فولدر پروژه رفته و دستور زیر رو وارد نمایید :

node app.js

به آدرس localhost:3000 رفته و نتیجه را ببینید.

وارد کردن صحیح captcha 

فرمی که بهتون نمایش داده میشه :

بعد از انجام صحیح این کار پیام زیر رو بهتون نمایش میده :

منبع

چه امتیازی برای این مقاله میدهید؟

خیلی بد
بد
متوسط
خوب
عالی
3 از 1 رای

دیدگاه و پرسش

برای ارسال دیدگاه لازم است وارد شده یا ثبت‌نام کنید ورود یا ثبت‌نام

در حال دریافت نظرات از سرور، لطفا منتظر بمانید

در حال دریافت نظرات از سرور، لطفا منتظر بمانید