CaptchaUtil.java

/*
 * Copyright 2022 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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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;

@Slf4j
public class CaptchaUtil {

	private static final String URL = "https://hcaptcha.com/siteverify";

	private static final ObjectMapper objectMapper = new ObjectMapper();

	public static boolean isValid(String hCaptchaResponse, 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 hCaptcha.");
			return true;
		}

		if (StringUtils.isBlank(hCaptchaResponse)) {
			// No response
			log.warn("Check fails with a blank hCaptcha response.");
			return false;
		}

		if (StringUtils.isBlank(captchaPrivateKey)) {
			// No private key provided
			log.warn("Check fails without a hCaptcha privateKey.");
			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=" + hCaptchaResponse;

		// Send post request
		connection.setDoOutput(true);
		DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
		dataOutputStream.writeBytes(postParams);
		dataOutputStream.flush();
		dataOutputStream.close();

		int responseCode = connection.getResponseCode();
		log.info("Send hCaptcha post request to --> {}\nPost parameters : {}\n Response Code : {}", url, postParams, responseCode);


		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
		String inputLine;
		var response = new StringBuilder();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		log.info("hCaptcha response: {}", response);
		JsonNode jsonNode = objectMapper.readTree(response.toString());

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