Skip to content

Commit

Permalink
docs(samples): create recaptcha samples (#535)
Browse files Browse the repository at this point in the history
* (feat): init commit client code samples

* (feat): init commit

* (docs): modified var names

* (refactor): modified checking for site key properties

* (docs): added region tag and comments

* (docs): modified comments and var names

* (docs): changed the print var

* (refactor): dis-allow amp traffic

* (refactor): added assessment name and modified var name.

* fix: added copyright. Minor var name fixes.

* fix: changed key type. Added copyright.

* feat: init commit adding test cases and snippets

* refactor: lint fix and added dependencies

* refactor: added webdrivermanager to remove driver binary dependency

* fix: lint error

* docs(samples): init commit client code samples

* (feat): init commit

* (docs): modified var names

* (refactor): modified checking for site key properties

* (docs): added region tag and comments

* (docs): modified comments and var names

* (docs): changed the print var

* (refactor): dis-allow amp traffic

* (refactor): added assessment name and modified var name.

* fix: added copyright. Minor var name fixes.

* fix: changed key type. Added copyright.

* feat: init commit adding test cases and snippets

* refactor: lint fix and added dependencies

* refactor: added webdrivermanager to remove driver binary dependency

* fix: lint error

* fix: pom mismatch fixup

* fix: pom mismatch fixup
  • Loading branch information
Sita04 authored Aug 27, 2021
1 parent 9c6acfe commit e56a11f
Show file tree
Hide file tree
Showing 11 changed files with 930 additions and 0 deletions.
29 changes: 29 additions & 0 deletions recaptcha_enterprise/cloud-client/src/main/java/app/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2021 Google LLC
*
* 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 app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {

public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2021 Google LLC
*
* 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 app;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping
public class MainController {

@GetMapping(value = "/")
public static ModelAndView landingPage(
@RequestParam("recaptchaSiteKey") String recaptchaSiteKey) {
ModelMap map = new ModelAndView().getModelMap();
map.put("siteKey", recaptchaSiteKey);
return new ModelAndView("index", map);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Copyright 2021 Google LLC
*
* 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 recaptcha;

// [START recaptcha_enterprise_create_assessment]

import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.Assessment;
import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
import com.google.recaptchaenterprise.v1.Event;
import com.google.recaptchaenterprise.v1.ProjectName;
import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason;
import java.io.IOException;

public class CreateAssessment {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectID = "project-id";
String recaptchaSiteKey = "recaptcha-site-key";
String token = "action-token";
String recaptchaAction = "action-name";

createAssessment(projectID, recaptchaSiteKey, token, recaptchaAction);
}


/**
* Create an assessment to analyze the risk of an UI action.
*
* @param projectID : GCloud Project ID
* @param recaptchaSiteKey : Site key obtained by registering a domain/app to use recaptcha
* services.
* @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 {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the `client.close()` method on the client to safely
// clean up any remaining background resources.
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

// Specify a name for this assessment.
String assessmentName = "assessment-name";
// 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).setName(assessmentName).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;
}

// Check if the expected action was executed.
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;
}

// Get the risk score and the reason(s).
// For more information on interpreting the assessment,
// see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
float recaptchaScore = response.getRiskAnalysis().getScore();
System.out.println("The reCAPTCHA score is: " + recaptchaScore);

for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
System.out.println(reason);
}
}
}
}
// [END recaptcha_enterprise_create_assessment]
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2021 Google LLC
*
* 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 recaptcha;

// [START recaptcha_enterprise_create_site_key]

import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.CreateKeyRequest;
import com.google.recaptchaenterprise.v1.Key;
import com.google.recaptchaenterprise.v1.ProjectName;
import com.google.recaptchaenterprise.v1.WebKeySettings;
import com.google.recaptchaenterprise.v1.WebKeySettings.IntegrationType;
import java.io.IOException;


public class CreateSiteKey {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectID = "your-project-id";
String domainName = "domain-name";

createSiteKey(projectID, domainName);
}

/**
* Create reCAPTCHA Site key which binds a domain name to a unique key.
*
* @param projectID : GCloud Project ID.
* @param domainName : Specify the domain name in which the reCAPTCHA should be activated.
*/
public static String createSiteKey(String projectID, String domainName) throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the `client.close()` method on the client to safely
// clean up any remaining background resources.
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

// Set the type of reCAPTCHA to be displayed.
// For different types, see: https://cloud.google.com/recaptcha-enterprise/docs/keys
Key scoreKey = Key.newBuilder()
.setDisplayName("any_descriptive_name_for_the_key")
.setWebSettings(WebKeySettings.newBuilder()
.addAllowedDomains(domainName)
.setAllowAmpTraffic(false)
.setIntegrationType(IntegrationType.SCORE).build())
.build();

CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
.setParent(ProjectName.of(projectID).toString())
.setKey(scoreKey)
.build();

// Get the name of the created reCAPTCHA site key.
Key response = client.createKey(createKeyRequest);
String keyName = response.getName();
String recaptchaSiteKey = keyName.substring(keyName.lastIndexOf("/") + 1);
System.out.println("reCAPTCHA Site key created successfully. Site Key: " + recaptchaSiteKey);
return recaptchaSiteKey;
}
}
}
// [END recaptcha_enterprise_create_site_key]

Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2021 Google LLC
*
* 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 recaptcha;

// [START recaptcha_enterprise_delete_site_key]

import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.DeleteKeyRequest;
import com.google.recaptchaenterprise.v1.KeyName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteSiteKey {

public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
String projectID = "your-project-id";
String recaptchaSiteKey = "recaptcha-site-key";

deleteSiteKey(projectID, recaptchaSiteKey);
}

/**
* Delete the given reCAPTCHA site key present under the project ID.
*
* @param projectID: GCloud Project ID.
* @param recaptchaSiteKey: Specify the site key to be deleted.
*/
public static void deleteSiteKey(String projectID, String recaptchaSiteKey)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the `client.close()` method on the client to safely
// clean up any remaining background resources.
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

// Set the project ID and reCAPTCHA site key.
DeleteKeyRequest deleteKeyRequest = DeleteKeyRequest.newBuilder()
.setName(KeyName.of(projectID, recaptchaSiteKey).toString())
.build();

client.deleteKeyCallable().futureCall(deleteKeyRequest).get(5, TimeUnit.SECONDS);
System.out.println("reCAPTCHA Site key successfully deleted !");
}
}
}
// [END recaptcha_enterprise_delete_site_key]
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2021 Google LLC
*
* 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 recaptcha;

// [START recaptcha_enterprise_get_site_key]

import com.google.api.core.ApiFuture;
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.GetKeyRequest;
import com.google.recaptchaenterprise.v1.Key;
import com.google.recaptchaenterprise.v1.KeyName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class GetSiteKey {

public static void main(String[] args)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
String projectID = "your-project-id";
String recaptchaSiteKey = "recaptcha-site-key";

getSiteKey(projectID, recaptchaSiteKey);
}


/**
* Get the reCAPTCHA site key present under the project ID.
*
* @param projectID: GCloud Project ID.
* @param recaptchaSiteKey: Specify the site key to get the details.
*/
public static void getSiteKey(String projectID, String recaptchaSiteKey)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the `client.close()` method on the client to safely
// clean up any remaining background resources.
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

// Construct the "GetSiteKey" request.
GetKeyRequest getKeyRequest = GetKeyRequest.newBuilder()
.setName(KeyName.of(projectID, recaptchaSiteKey).toString())
.build();

// Wait for the operation to complete.
ApiFuture<Key> futureCall = client.getKeyCallable().futureCall(getKeyRequest);
Key key = futureCall.get(5, TimeUnit.SECONDS);

System.out.println("Successfully obtained the key !" + key.getName());
}
}
}
// [END recaptcha_enterprise_get_site_key]
Loading

0 comments on commit e56a11f

Please sign in to comment.