Project

General

Profile

1
package eu.dnetlib.uoaadmintoolslibrary.recaptcha;
2

    
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.beans.factory.annotation.Configurable;
5
import org.springframework.boot.web.client.RestTemplateBuilder;
6
import org.springframework.context.annotation.Bean;
7
import org.springframework.stereotype.Service;
8
import org.springframework.util.StringUtils;
9
import org.springframework.web.client.RestOperations;
10

    
11
import java.net.URI;
12
import java.util.regex.Pattern;
13

    
14
import eu.dnetlib.uoaadmintoolslibrary.configuration.properties.GoogleConfig;
15
import eu.dnetlib.uoaadmintoolslibrary.entities.email.GoogleResponse;
16
import eu.dnetlib.uoaadmintoolslibrary.handlers.InvalidReCaptchaException;
17

    
18
@Service
19
@Configurable
20
public class VerifyRecaptcha {
21

    
22
    @Autowired
23
    private RestOperations restTemplate;
24

    
25
    @Autowired
26
    private GoogleConfig googleConfig;
27

    
28
    private static Pattern RESPONSE_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");
29

    
30
    @Bean
31
    public RestOperations restTemplate(RestTemplateBuilder builder) {
32
        return builder.build();
33
    }
34

    
35
    public void processResponse(String response) throws InvalidReCaptchaException {
36
        if(!responseSanityCheck(response)) {
37
            throw new InvalidReCaptchaException("Response contains invalid characters");
38
        }
39

    
40
        URI verifyUri = URI.create(String.format(
41
                "https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s",
42
                googleConfig.getSecret(), response));
43

    
44
        GoogleResponse googleResponse = restTemplate.getForObject(verifyUri, GoogleResponse.class);
45

    
46
        if(!googleResponse.isSuccess()) {
47
            throw new InvalidReCaptchaException("reCaptcha was not successfully validated");
48
        }
49
    }
50

    
51
    private boolean responseSanityCheck(String response) {
52
        return StringUtils.hasLength(response) && RESPONSE_PATTERN.matcher(response).matches();
53
    }
54
}
    (1-1/1)