Alfie Kemp

Alfie Kemp

1581091260

Google ReCaptcha v3 in Nodejs

In this node js google v3 recaptcha example tutorial, we will use Node.js and express framework to build a Google v3 Recaptcha Security.

1. Get Google reCaptcha v3 credentials

Now, you need to register your site with this URL: https://www.google.com/recaptcha to get the API key and API secret.

Note:- Google Captcha does not natively support the localhost domain so what you need to do is in the text box of the site name, put your local address: 127.0.0.1. That is it.

2. Create a fresh project

Here you need to create project folder and then type the following command into your command prompt (cmd):

mkdir public

npm init 

We are initializing the package.json file.

{

  "name": "googlerecaptcha",

  "version": "1.0.0",

  "description": "",

  "main": "server.js",

  "scripts": {

    "start": "nodemon server"

  },

  "author": "tutsmake.com",

  "license": "ISC",

  "dependencies": {

    "body-parser": "^1.17.2",

    "ejs": "^2.5.7",

    "express": "^4.15.4"

  },

  "devDependencies": {

    "nodemon": "^1.11.0"

  }

}

We have written three packages as dependencies, so go to your terminal and type the command.

npm install

3. Create view file in project

Create one file name index.ejs is called views file. In this file, We are using the Bootstrap CSS Framework for this application, so we will include that CSS file in the public folder.

<!-- index.ejs -->
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Node js Google v3 Recaptcha Example Tutorial</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Google Recaptcha Tutorial</h1><br />
        <form method="post" action="/captcha">
        <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
        <input type="hidden" name="action" value="validate_captcha">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success" style="margin-left:38px">Send</button>
          </div>
        </div>
      </form>
    </div>
 
<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
    grecaptcha.ready(function() {
    // do request for recaptcha token
    // response is promise with passed token
        grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
                  .then(function(token) {
            // add token value to form
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>
 
  </body>
</html>

To access this page, we need to set up one route in a server.js file.

// server.js

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

    res.render('index');

});

Go to your terminal, type following command.

npm start

Go to your browser and type this URL: http://localhost:3000

4. Create server.js and Handle the request at the server-side

Here, we will to do two things. First one is install one HTTP request package called request. So use the following command to install HTTP request package in Node js:

npm install request --save

Second thing creates a server.js file inside your project folder and update the following code into your server.js file:

// server.js
 
const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    request = require('request');
 
const app = express();
   app.set('view engine', 'ejs');
   app.use(express.static('public'));
   app.use(bodyParser.urlencoded({extended: true}));
   app.use(bodyParser.json());
   var port = 3000;
 
app.get('/', function (req, res) {
    res.render('index');
});
 
app.post('/captcha', function(req, res) {
  if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null)
  {
    return res.json({"responseError" : "something goes to wrong"});
  }
  const secretKey = "xxxx";
 
  const verificationURL = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&amp;response=" + req.body['g-recaptcha-response'] + "&amp;remoteip=" + req.connection.remoteAddress;
 
  request(verificationURL,function(error,response,body) {
    body = JSON.parse(body);
 
    if(body.success !== undefined &amp;&amp; !body.success) {
      return res.json({"responseError" : "Failed captcha verification"});
    }
    res.json({"responseSuccess" : "Sucess"});
  });
});
 
app.listen(port, function(){
    console.log('Server is running at port: ',port);
});

Put the secret key according to your site. If you submit the form with captcha verification, you will get success in response.

Note:- If you do not verify captcha and send the form then, you will get an error in response.

#nodejs #javascript #node-js

What is GEEK

Buddha Community

Google ReCaptcha v3 in Nodejs

I am Developer

1629016197

this google recaptcha v3 in nodejs reference from https://www.tutsmake.com/node-js-google-recaptcha-v3-example/

Jon  Gislason

Jon Gislason

1619247660

Google's TPU's being primed for the Quantum Jump

The liquid-cooled Tensor Processing Units, built to slot into server racks, can deliver up to 100 petaflops of compute.

The liquid-cooled Tensor Processing Units, built to slot into server racks, can deliver up to 100 petaflops of compute.

As the world is gearing towards more automation and AI, the need for quantum computing has also grown exponentially. Quantum computing lies at the intersection of quantum physics and high-end computer technology, and in more than one way, hold the key to our AI-driven future.

Quantum computing requires state-of-the-art tools to perform high-end computing. This is where TPUs come in handy. TPUs or Tensor Processing Units are custom-built ASICs (Application Specific Integrated Circuits) to execute machine learning tasks efficiently. TPUs are specific hardware developed by Google for neural network machine learning, specially customised to Google’s Machine Learning software, Tensorflow.

The liquid-cooled Tensor Processing units, built to slot into server racks, can deliver up to 100 petaflops of compute. It powers Google products like Google Search, Gmail, Google Photos and Google Cloud AI APIs.

#opinions #alphabet #asics #floq #google #google alphabet #google quantum computing #google tensorflow #google tensorflow quantum #google tpu #google tpus #machine learning #quantum computer #quantum computing #quantum computing programming #quantum leap #sandbox #secret development #tensorflow #tpu #tpus

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications?

Hire NodeJs Developer to create a real-time, faster, and scalable application to accelerate your business. At HourlyDeveloper.io, we have a team of expert Node.JS developers, who have experience in working with Bootstrap, HTML5, & CSS, and also hold the knowledge of the most advanced frameworks and platforms.

Contact our experts: https://bit.ly/3hUdppS

#hire nodejs developer #nodejs developer #nodejs development company #nodejs development services #nodejs development #nodejs

Anda Lacacima

Anda Lacacima

1598923425

How to Use Google’s reCAPTCHA with Golang

Introduction

It’s always a good practice to prevent malicious software from engaging in abusive activities on your web application. The most popular tool to achieve that is Google’s reCAPTCHA. At the current state, it supports v2 and v3. In this article, we will focus on v3, as it requires less interaction with users and enables analytics.

Prerequisites

  • Go environment (instructions)
  • An already registered website on Google’s reCAPTCHA console
  • A new directory, e.x recaptcha-endpoints, inside your GOPATH where all of our code will live

Getting started

After registering your website, a new API key and secret pair will be generated. To make reCAPTCHA work, it requires changes on both frontend and backend services of your web application. We will only demonstrate on how to use it on the backend service, as Google’s documentation is pretty straight forward regarding the challenge placement on the frontend.

Implementation

We will implement a simple server with a single endpoint to handle the login of users, given an email and password, protected with Google reCAPTCHA.

The way to verify a reCAPTCHA token is to make a POST request on [https://www.google.com/recaptcha/api/siteverify](https://www.google.com/recaptcha/api/siteverify) followed by the secret and the response token as URL parameters. Then evaluate the response to find out if the challenge was successful. Source code is about to follow.

package main

import (
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"os"
	"time"
)

const siteVerifyURL = "https://www.google.com/recaptcha/api/siteverify"

type LoginRequest struct {
	Email             string `json:"email"`
	Password          string `json:"password"`
	RecaptchaResponse string `json:"g-recaptcha-response"`
}

type SiteVerifyResponse struct {
	Success     bool      `json:"success"`
	Score       float64   `json:"score"`
	Action      string    `json:"action"`
	ChallengeTS time.Time `json:"challenge_ts"`
	Hostname    string    `json:"hostname"`
	ErrorCodes  []string  `json:"error-codes"`
}

func main() {
	// Get recaptcha secret from env variable.
	secret := os.Getenv("RECAPTCHA_SECRET")
	
	// Define endpoint to handle login.
	http.HandleFunc("/login", Login(secret))

	log.Println("Server starting at port 8080...")

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

func Login(secret string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Decode request body.
		var body LoginRequest
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		// Check and verify the recaptcha response token.
		if err := CheckRecaptcha(secret, body.RecaptchaResponse); err != nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// Check login credentials.
    		// ....

		w.WriteHeader(http.StatusOK)
	}
}

func CheckRecaptcha(secret, response string) error {
	req, err := http.NewRequest(http.MethodPost, siteVerifyURL, nil)
	if err != nil {
		return err
	}

	// Add necessary request parameters.
	q := req.URL.Query()
	q.Add("secret", secret)
	q.Add("response", response)
	req.URL.RawQuery = q.Encode()

	// Make request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Decode response.
	var body SiteVerifyResponse
	if err = json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return err
	}

	// Check recaptcha verification success.
	if !body.Success {
		return errors.New("unsuccessful recaptcha verify request")
	}

	// Check response score.
	if body.Score < 0.5 {
		return errors.New("lower received score than expected")
	}

	// Check response action.
	if body.Action != "login" {
		return errors.New("mismatched recaptcha action")
	}

	return nil
}

Let’s dive into it step by step

  • A const variable to hold Google’s reCAPTCHA request link
  • LoginRequest struct that contains the user email and password to validate credentials, plus an extra field for reCAPTCHA token.
  • SiteVerifyResponse struct to decode the response from Google reCAPTCHA API.
  • The main function to define the login endpoint handler, passing the reCAPTCHA secret as argument.
  • The Login function that operates as handler where at first decodes the request body. Then checks and verifies the reCAPTCHA token calling the CheckRecaptcha function and finally validate the provided credentials.
  • The CheckRecaptcha function that does all the work regarding reCAPTCHA verification. Accepts the secret and response token as arguments, constructs the proper POST request and makes it. Decode the response into the SiteVerifyResponse struct and checks if the verification was successful, compares the received score against a provided minimum (0.5) and also checks the action name (login)

You can set custom action names for any operation on your website, by setting the _data-action_ attribute. In this way you can have access to a detailed break down of data in admin console and can apply different business logic for each action (e.g. 2FA authentication for login with low scores).

Middleware

The above solution does the work, although it doesn’t scale while your web server is growing. It requires code duplication, generic code inside handlers and an extra field inside each struct, which used to decode requests body.

To avoid all that, we can implement a middleware to handle all the reCAPTCHA verification and apply to any endpoint is required. The previous code now becomes.

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"
)

const siteVerifyURL = "https://www.google.com/recaptcha/api/siteverify"

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type SiteVerifyResponse struct {
	Success     bool      `json:"success"`
	Score       float64   `json:"score"`
	Action      string    `json:"action"`
	ChallengeTS time.Time `json:"challenge_ts"`
	Hostname    string    `json:"hostname"`
	ErrorCodes  []string  `json:"error-codes"`
}

type SiteVerifyRequest struct {
	RecaptchaResponse string `json:"g-recaptcha-response"`
}

func main() {
	// Get recaptcha secret from env variable.
	secret := os.Getenv("RECAPTCHA_SECRET")

	// Define endpoint to handle login.
	http.Handle("/login", RecaptchaMiddleware(secret)(Login()))

	log.Println("Server starting at port 8080...")

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

func Login() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Decode request body.
		var body LoginRequest
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		// Check login credentials.
		// ...

		w.WriteHeader(http.StatusOK)
	}
}

func CheckRecaptcha(secret, response string) error {
	req, err := http.NewRequest(http.MethodPost, siteVerifyURL, nil)
	if err != nil {
		return err
	}

	// Add necessary request parameters.
	q := req.URL.Query()
	q.Add("secret", secret)
	q.Add("response", response)
	req.URL.RawQuery = q.Encode()

	// Make request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Decode response.
	var body SiteVerifyResponse
	if err = json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return err
	}

	// Check recaptcha verification success.
	if !body.Success {
		return errors.New("unsuccessful recaptcha verify request")
	}

	// Check response score.
	if body.Score < 0.5 {
		return errors.New("lower received score than expected")
	}

	// Check response action.
	if body.Action != "login" {
		return errors.New("mismatched recaptcha action")
	}

	return nil
}

func RecaptchaMiddleware(secret string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Get the reCaptcha response token from default request body field 'g-recaptcha-response'.
			bodyBytes, err := ioutil.ReadAll(r.Body)
			if err != nil {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			// Unmarshal body into struct.
			var body SiteVerifyRequest
			if err := json.Unmarshal(bodyBytes, &body); err != nil {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			// Restore request body to read more than once.
			r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

			// Check and verify the recaptcha response token.
			if err := CheckRecaptcha(secret, body.RecaptchaResponse); err != nil {
				http.Error(w, "unauthorized", http.StatusUnauthorized)
				return
			}

			next.ServeHTTP(w, r)
		})
	}
}

We will mention the changes against the first version of our code.

  1. The RecaptchaResponse field has been removed from the LoginRequest struct as is no longer need it.
  2. A new struct SiteVerifyRequest has been introduced and will be used in middleware function to retrieve the reCAPTCHA token from request body.
  3. The Login handler function is now wrapped by RecaptchaMiddleware.
  4. Any source code regarding reCAPTCHA has been removed from handler.
  5. A new function RecaptchaMiddleware that accepts a secret has been created, that operates as middleware. Contains all the code regarding Google’s reCAPTCHA verification. Reads and decodes the request body into SiteVerityRequest struct, then checks and verifies the reCAPTCHA at the same way as before.
  6. There is a tricky part at line 125 that needs attention. In Go, http request body is an io.ReadCloser type that can be read only once. For that reason we have to restore it, to be able to use it again in any following handler.

That’s all the differences regarding the first version of our solution. In this way the code it’s a lot cleaner, handlers only contain the business logic that have been created for and the Google’s reCAPTCHA verification happens to a single place, inside the middleware.

Source code

I have implemented an open source package that handles Google’s reCAPTCHA verification that supports both v2 and v3. An out of the box middleware is also included. You can find it on GitHub.

#google-recaptcha #go #google #recaptcha #golang

What Are Google Compute Engine ? - Explained

What Are Google Compute Engine ? - Explained

The Google computer engine exchanges a large number of scalable virtual machines to serve as clusters used for that purpose. GCE can be managed through a RESTful API, command line interface, or web console. The computing engine is serviced for a minimum of 10-minutes per use. There is no up or front fee or time commitment. GCE competes with Amazon’s Elastic Compute Cloud (EC2) and Microsoft Azure.

https://www.mrdeluofficial.com/2020/08/what-are-google-compute-engine-explained.html

#google compute engine #google compute engine tutorial #google app engine #google cloud console #google cloud storage #google compute engine documentation

Embedding your <image> in google colab <markdown>

This article is a quick guide to help you embed images in google colab markdown without mounting your google drive!

Image for post

Just a quick intro to google colab

Google colab is a cloud service that offers FREE python notebook environments to developers and learners, along with FREE GPU and TPU. Users can write and execute Python code in the browser itself without any pre-configuration. It offers two types of cells: text and code. The ‘code’ cells act like code editor, coding and execution in done this block. The ‘text’ cells are used to embed textual description/explanation along with code, it is formatted using a simple markup language called ‘markdown’.

Embedding Images in markdown

If you are a regular colab user, like me, using markdown to add additional details to your code will be your habit too! While working on colab, I tried to embed images along with text in markdown, but it took me almost an hour to figure out the way to do it. So here is an easy guide that will help you.

STEP 1:

The first step is to get the image into your google drive. So upload all the images you want to embed in markdown in your google drive.

Image for post

Step 2:

Google Drive gives you the option to share the image via a sharable link. Right-click your image and you will find an option to get a sharable link.

Image for post

On selecting ‘Get shareable link’, Google will create and display sharable link for the particular image.

#google-cloud-platform #google-collaboratory #google-colaboratory #google-cloud #google-colab #cloud