Refactor HCaptchaValidator to improve token verification and logging.
This commit is contained in:
@@ -4,6 +4,8 @@ import dev.rheinsw.server.contact.model.HCaptchaConfig;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.LinkedMultiValueMap;
|
||||||
|
import org.springframework.util.MultiValueMap;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -26,29 +28,41 @@ public class HCaptchaValidator {
|
|||||||
|
|
||||||
public boolean isValid(String token) {
|
public boolean isValid(String token) {
|
||||||
if (token == null || token.isBlank()) {
|
if (token == null || token.isBlank()) {
|
||||||
log.warn("Captcha token is missing or blank");
|
log.warn("[hCaptcha] Token is missing or blank");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
String secret = config.getSecret();
|
String secret = config.getSecret();
|
||||||
if (secret == null || secret.isBlank()) {
|
if (secret == null || secret.isBlank()) {
|
||||||
log.error("Captcha secret is missing");
|
log.error("[hCaptcha] Secret is not configured");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var response = restTemplate.postForObject(
|
log.info("[hCaptcha] Verifying token with https://api.hcaptcha.com/siteverify");
|
||||||
|
|
||||||
|
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
|
||||||
|
body.add("secret", secret);
|
||||||
|
body.add("response", token);
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> response = restTemplate.postForObject(
|
||||||
"https://api.hcaptcha.com/siteverify",
|
"https://api.hcaptcha.com/siteverify",
|
||||||
new org.springframework.util.LinkedMultiValueMap<String, String>() {{
|
body,
|
||||||
add("secret", secret);
|
|
||||||
add("response", token);
|
|
||||||
}},
|
|
||||||
Map.class
|
Map.class
|
||||||
);
|
);
|
||||||
|
|
||||||
return response != null && Boolean.TRUE.equals(response.get("success"));
|
log.info("[hCaptcha] Verification response: {}", response);
|
||||||
|
|
||||||
|
boolean success = response != null && Boolean.TRUE.equals(response.get("success"));
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
log.warn("[hCaptcha] Verification failed: {}", response);
|
||||||
|
}
|
||||||
|
|
||||||
|
return success;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to verify hCaptcha", e);
|
log.error("[hCaptcha] Exception during verification", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user