cr.ac.siua.tec.services.impl.RecaptchaServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for cr.ac.siua.tec.services.impl.RecaptchaServiceImpl.java

Source

/*
   TRI-S - Web Service
   Developed by: Luis E. Ugalde Barrantes - Diego Ugalde ?vila. 2016.
   This code is licensed under the GNU GENERAL PUBLIC LICENSE (GPL) V3. See LICENSE file for details.
*/

package cr.ac.siua.tec.services.impl;

import com.fasterxml.jackson.annotation.JsonProperty;
import cr.ac.siua.tec.services.RecaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;

@Service
public class RecaptchaServiceImpl implements RecaptchaService {

    private static class RecaptchaResponse {
        @JsonProperty("success")
        private boolean success;
        @JsonProperty("error-codes")
        private Collection<String> errorCodes;
    }

    private final RestTemplate restTemplate;

    @Value("${recaptcha.url}")
    private String recaptchaUrl;

    @Value("${recaptcha.secret-key}")
    private String recaptchaSecretKey;

    @Autowired
    public RecaptchaServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * Validates recaptcha response with Google API using the secret key.
     */
    @Override
    public boolean isResponseValid(String remoteIp, String response) {
        RecaptchaResponse recaptchaResponse;
        try {
            recaptchaResponse = restTemplate.postForEntity(recaptchaUrl,
                    createBody(recaptchaSecretKey, remoteIp, response), RecaptchaResponse.class).getBody();
        } catch (RestClientException e) {
            throw new RuntimeException("Recaptcha API not available due to exception", e);
        }
        return recaptchaResponse.success;
    }

    /**
     * Creates a hashmap with the parameters required for the Recaptcha Verification.
     */
    private MultiValueMap<String, String> createBody(String secret, String remoteIp, String response) {
        MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
        form.add("secret", secret);
        form.add("remoteip", remoteIp);
        form.add("response", response);
        return form;
    }

}