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.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @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");
connection.setDoOutput(true);
String postParams = "secret=" + captchaPrivateKey + "&response=" + hCaptchaResponse;
// Send post request
try (DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream())) {
dataOutputStream.writeBytes(postParams);
dataOutputStream.flush();
}
int responseCode = connection.getResponseCode();
LOG.info("Send hCaptcha post request to --> {}\nPost parameters : {}\n Response Code : {}", url, postParams, responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
final JsonNode jsonNode;
try (InputStream is = connection.getInputStream()) {
jsonNode = objectMapper.readTree(is);
}
LOG.info("hCaptcha response: {}", jsonNode);
return jsonNode.findValue("success").asBoolean();
} else {
throw new IOException("hCaptcha verification failed with HTTP " + responseCode);
}
}
}