Search in sources :

Example 1 with CreateAssessmentRequest

use of com.google.recaptchaenterprise.v1.CreateAssessmentRequest in project java-recaptchaenterprise by googleapis.

the class RecaptchaEnterpriseServiceV1Beta1ClientTest method createAssessmentTest2.

@Test
public void createAssessmentTest2() throws Exception {
    Assessment expectedResponse = Assessment.newBuilder().setName(AssessmentName.of("[PROJECT]", "[ASSESSMENT]").toString()).setEvent(Event.newBuilder().build()).setScore(109264530).setTokenProperties(TokenProperties.newBuilder().build()).addAllReasons(new ArrayList<Assessment.ClassificationReason>()).build();
    mockRecaptchaEnterpriseServiceV1Beta1.addResponse(expectedResponse);
    String parent = "parent-995424086";
    Assessment assessment = Assessment.newBuilder().build();
    Assessment actualResponse = client.createAssessment(parent, assessment);
    Assert.assertEquals(expectedResponse, actualResponse);
    List<AbstractMessage> actualRequests = mockRecaptchaEnterpriseServiceV1Beta1.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateAssessmentRequest actualRequest = ((CreateAssessmentRequest) actualRequests.get(0));
    Assert.assertEquals(parent, actualRequest.getParent());
    Assert.assertEquals(assessment, actualRequest.getAssessment());
    Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) ArrayList(java.util.ArrayList) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Test(org.junit.Test)

Example 2 with CreateAssessmentRequest

use of com.google.recaptchaenterprise.v1.CreateAssessmentRequest in project pomocua-ogloszenia by coi-gov-pl.

the class CaptchaValidator method validate.

public boolean validate(String recaptchaResponse) {
    if (!properties.isEnabled()) {
        log.debug("Skip captcha validation. To enable change 'app.captcha.enabled' property");
        return true;
    }
    if (!responseSanityCheck(recaptchaResponse)) {
        log.warn("Response contains invalid characters");
        return false;
    }
    ProjectName projectName = ProjectName.of(properties.getGoogleCloudProjectId());
    Event event = Event.newBuilder().setSiteKey(properties.getSiteKey()).setToken(recaptchaResponse).build();
    CreateAssessmentRequest createAssessmentRequest = CreateAssessmentRequest.newBuilder().setParent(projectName.toString()).setAssessment(Assessment.newBuilder().setEvent(event).build()).build();
    Assessment response = recaptchaClient.createAssessment(createAssessmentRequest);
    if (response == null) {
        log.warn("Empty response from reCaptcha");
        return false;
    }
    // Check if the token is valid.
    if (!response.getTokenProperties().getValid()) {
        String invalidTokenReason = response.getTokenProperties().getInvalidReason().name();
        log.debug("The CreateAssessment call failed because the token was: " + invalidTokenReason);
        return false;
    }
    float score = response.getScore();
    if (score < properties.getAcceptLevel()) {
        List<String> reasons = response.getReasonsList().stream().map(classificationReason -> classificationReason.getDescriptorForType().getFullName()).collect(Collectors.toList());
        log.debug("Validation failed. Score: " + score + ". Reasons: " + String.join(", ", reasons));
        return false;
    }
    log.debug("Validation OK - score: " + score);
    return true;
}
Also used : Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Service(org.springframework.stereotype.Service) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) RecaptchaEnterpriseServiceV1Beta1Client(com.google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterpriseServiceV1Beta1Client) ProjectName(com.google.recaptchaenterprise.v1beta1.ProjectName) Pattern(java.util.regex.Pattern) Collectors(java.util.stream.Collectors) Event(com.google.recaptchaenterprise.v1beta1.Event) StringUtils(org.springframework.util.StringUtils) ProjectName(com.google.recaptchaenterprise.v1beta1.ProjectName) Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Event(com.google.recaptchaenterprise.v1beta1.Event)

Example 3 with CreateAssessmentRequest

use of com.google.recaptchaenterprise.v1.CreateAssessmentRequest in project java-recaptchaenterprise by googleapis.

the class RecaptchaEnterpriseServiceClientTest method createAssessmentTest.

@Test
public void createAssessmentTest() throws Exception {
    Assessment expectedResponse = Assessment.newBuilder().setName(AssessmentName.of("[PROJECT]", "[ASSESSMENT]").toString()).setEvent(Event.newBuilder().build()).setRiskAnalysis(RiskAnalysis.newBuilder().build()).setTokenProperties(TokenProperties.newBuilder().build()).setAccountDefenderAssessment(AccountDefenderAssessment.newBuilder().build()).build();
    mockRecaptchaEnterpriseService.addResponse(expectedResponse);
    ProjectName parent = ProjectName.of("[PROJECT]");
    Assessment assessment = Assessment.newBuilder().build();
    Assessment actualResponse = client.createAssessment(parent, assessment);
    Assert.assertEquals(expectedResponse, actualResponse);
    List<AbstractMessage> actualRequests = mockRecaptchaEnterpriseService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateAssessmentRequest actualRequest = ((CreateAssessmentRequest) actualRequests.get(0));
    Assert.assertEquals(parent.toString(), actualRequest.getParent());
    Assert.assertEquals(assessment, actualRequest.getAssessment());
    Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) ProjectName(com.google.recaptchaenterprise.v1.ProjectName) Assessment(com.google.recaptchaenterprise.v1.Assessment) AccountDefenderAssessment(com.google.recaptchaenterprise.v1.AccountDefenderAssessment) CreateAssessmentRequest(com.google.recaptchaenterprise.v1.CreateAssessmentRequest) Test(org.junit.Test)

Example 4 with CreateAssessmentRequest

use of com.google.recaptchaenterprise.v1.CreateAssessmentRequest in project java-recaptchaenterprise by googleapis.

the class RecaptchaEnterpriseServiceV1Beta1ClientTest method createAssessmentTest.

@Test
public void createAssessmentTest() throws Exception {
    Assessment expectedResponse = Assessment.newBuilder().setName(AssessmentName.of("[PROJECT]", "[ASSESSMENT]").toString()).setEvent(Event.newBuilder().build()).setScore(109264530).setTokenProperties(TokenProperties.newBuilder().build()).addAllReasons(new ArrayList<Assessment.ClassificationReason>()).build();
    mockRecaptchaEnterpriseServiceV1Beta1.addResponse(expectedResponse);
    ProjectName parent = ProjectName.of("[PROJECT]");
    Assessment assessment = Assessment.newBuilder().build();
    Assessment actualResponse = client.createAssessment(parent, assessment);
    Assert.assertEquals(expectedResponse, actualResponse);
    List<AbstractMessage> actualRequests = mockRecaptchaEnterpriseServiceV1Beta1.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateAssessmentRequest actualRequest = ((CreateAssessmentRequest) actualRequests.get(0));
    Assert.assertEquals(parent.toString(), actualRequest.getParent());
    Assert.assertEquals(assessment, actualRequest.getAssessment());
    Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) ProjectName(com.google.recaptchaenterprise.v1beta1.ProjectName) Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) ArrayList(java.util.ArrayList) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Test(org.junit.Test)

Example 5 with CreateAssessmentRequest

use of com.google.recaptchaenterprise.v1.CreateAssessmentRequest in project java-recaptchaenterprise by googleapis.

the class CreateAssessment method createAssessment.

/**
 * Create an assessment to analyze the risk of an UI action. Assessment approach is the same for
 * both 'score' and 'checkbox' type recaptcha site keys.
 *
 * @param projectID : GCloud Project ID
 * @param recaptchaSiteKey : Site key obtained by registering a domain/app to use recaptcha
 *     services. (score/ checkbox type)
 * @param token : The token obtained from the client on passing the recaptchaSiteKey.
 * @param recaptchaAction : Action name corresponding to the token.
 */
public static void createAssessment(String projectID, String recaptchaSiteKey, String token, String recaptchaAction) throws IOException {
    // clean up any remaining background resources.
    try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
        // Set the properties of the event to be tracked.
        Event event = Event.newBuilder().setSiteKey(recaptchaSiteKey).setToken(token).build();
        // Build the assessment request.
        CreateAssessmentRequest createAssessmentRequest = CreateAssessmentRequest.newBuilder().setParent(ProjectName.of(projectID).toString()).setAssessment(Assessment.newBuilder().setEvent(event).build()).build();
        Assessment response = client.createAssessment(createAssessmentRequest);
        // Check if the token is valid.
        if (!response.getTokenProperties().getValid()) {
            System.out.println("The CreateAssessment call failed because the token was: " + response.getTokenProperties().getInvalidReason().name());
            return;
        }
        // (If the key is checkbox type and 'action' attribute wasn't set, skip this check.)
        if (!response.getTokenProperties().getAction().equals(recaptchaAction)) {
            System.out.println("The action attribute in reCAPTCHA tag is: " + response.getTokenProperties().getAction());
            System.out.println("The action attribute in the reCAPTCHA tag " + "does not match the action (" + recaptchaAction + ") you are expecting to score");
            return;
        }
        // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
        for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
            System.out.println(reason);
        }
        float recaptchaScore = response.getRiskAnalysis().getScore();
        System.out.println("The reCAPTCHA score is: " + recaptchaScore);
        // Get the assessment name (id). Use this to annotate the assessment.
        String assessmentName = response.getName();
        System.out.println("Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1));
    }
}
Also used : Assessment(com.google.recaptchaenterprise.v1.Assessment) CreateAssessmentRequest(com.google.recaptchaenterprise.v1.CreateAssessmentRequest) Event(com.google.recaptchaenterprise.v1.Event) ClassificationReason(com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason) RecaptchaEnterpriseServiceClient(com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient)

Aggregations

AbstractMessage (com.google.protobuf.AbstractMessage)4 Test (org.junit.Test)4 Assessment (com.google.recaptchaenterprise.v1.Assessment)3 CreateAssessmentRequest (com.google.recaptchaenterprise.v1.CreateAssessmentRequest)3 Assessment (com.google.recaptchaenterprise.v1beta1.Assessment)3 CreateAssessmentRequest (com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest)3 AccountDefenderAssessment (com.google.recaptchaenterprise.v1.AccountDefenderAssessment)2 ProjectName (com.google.recaptchaenterprise.v1beta1.ProjectName)2 ArrayList (java.util.ArrayList)2 RecaptchaEnterpriseServiceClient (com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient)1 RecaptchaEnterpriseServiceV1Beta1Client (com.google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterpriseServiceV1Beta1Client)1 ByteString (com.google.protobuf.ByteString)1 Event (com.google.recaptchaenterprise.v1.Event)1 ProjectName (com.google.recaptchaenterprise.v1.ProjectName)1 ClassificationReason (com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason)1 Event (com.google.recaptchaenterprise.v1beta1.Event)1 List (java.util.List)1 Pattern (java.util.regex.Pattern)1 Collectors (java.util.stream.Collectors)1 RequiredArgsConstructor (lombok.RequiredArgsConstructor)1