ReCaptchaUtil.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Matija Obreza
 */
@Slf4j
public class ReCaptchaUtil {

	private static final String URL = "https://www.google.com/recaptcha/api/siteverify";

	public static boolean isValid(String reCaptchaResponse, String remoteAddr, String captchaPrivateKey) throws IOException {
		boolean isLocalRequest = false;

		try {
			final InetAddress remoteInetAddr = InetAddress.getByName(remoteAddr);
			isLocalRequest = remoteInetAddr.isLinkLocalAddress() || remoteInetAddr.isAnyLocalAddress() || remoteInetAddr.isLoopbackAddress();
			log.warn("Remote addr: {} {} isLocal={}", remoteAddr, remoteInetAddr, isLocalRequest);
		} catch (final UnknownHostException e1) {
			log.warn(e1.getMessage());
		}

		if (isLocalRequest) {
			log.info("Ignoring localhost re-captcha.");
			return true;
		}

		if (reCaptchaResponse == null || "".equals(reCaptchaResponse)) {
			return false;
		}

		java.net.URL url = new URL(URL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		// add request header
		connection.setRequestMethod("POST");

		String postParams = "secret=" + captchaPrivateKey + "&response=" + reCaptchaResponse;

		// Send post request
		connection.setDoOutput(true);
		try (DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream())) {
			dataOutputStream.writeBytes(postParams);
			dataOutputStream.flush();
			dataOutputStream.close();
		}
		int responseCode = connection.getResponseCode();
		log.info("Send recaptcha post request to --> {}\nPost parameters : {}\n Response Code : {}", url, postParams, responseCode);


		StringBuilder response = new StringBuilder();
		try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
			String inputLine;
	
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
		}

		ObjectMapper objectMapper = new ObjectMapper();
		JsonNode jsonNode = objectMapper.readTree(response.toString());

		return jsonNode.findValue("success").asBoolean();
	}
}