CaptchaChecker.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.spring;
import java.io.IOException;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.service.OAuthClientService;
import org.genesys.blocks.security.SecurityContextUtil;
import org.genesys.server.exception.InvalidApiUsageException;
import org.genesys.util.CaptchaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* The ReCaptchaChecker.
*/
public class CaptchaChecker {
private static final Logger LOG = LoggerFactory.getLogger(CaptchaChecker.class);
@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.");
}
}
}