CaptchaChecker.java

/*
 * Copyright 2022 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.gringlobal.spring;

import lombok.extern.slf4j.Slf4j;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.service.OAuthClientService;
import org.genesys.blocks.security.SecurityContextUtil;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@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.");
		}
	}
}