CaptchaChecker.java
/*
* Copyright 2026 Global Crop Diversity Trust
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
*/
package org.gringlobal.spring;
import java.io.IOException;
import org.genesys.blocks.oauth.impl.OAuthClient;
import org.genesys.blocks.oauth.impl.OAuthClientService;
import org.genesys.blocks.security.SecurityContextUtil;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.util.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class CaptchaChecker {
@Autowired
private OAuthClientService oauthClientService;
/**
* Assure valid recaptcha.
*
* @param response the response
* @param remoteAddr the remote addr
*/
public void assureValidResponseForClient(String response, String remoteAddr) {
String oauthClientId = SecurityContextUtil.getOAuthClientId();
if (oauthClientId != null) {
OAuthClient client = oauthClientService.getClient(oauthClientId);
if (client != null) {
try {
if (CaptchaUtil.isValid(response, remoteAddr, client.getPrivateRecaptchaKey())) {
// All OK
return;
} else {
log.warn("Recaptcha not valid for OAuth client={} and response={}", oauthClientId, response);
throw new InvalidApiUsageException("Captcha check failed.");
}
} catch (IOException e) {
log.warn("Error checking recaptcha: {}", e.getMessage(), e);
throw new RuntimeException(e);
}
} else {
throw new RuntimeException("No such OAuth Client.");
}
} else {
throw new InvalidApiUsageException("Not OAuthClient.");
}
}
}