CaptchaUtil.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.genesys.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 org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author matijaobreza
 */
public class CaptchaUtil {

	private final static Logger LOG = LoggerFactory.getLogger(CaptchaUtil.class);
	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;
		}

		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()));
		String inputLine;
		StringBuffer response = new StringBuffer();

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

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

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

}