Skip to content
This repository has been archived by the owner on Sep 16, 2023. It is now read-only.

docs(samples): create recaptcha samples #535

Merged
merged 33 commits into from Aug 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
413b6b6
(feat): init commit client code samples
Sita04 Jul 16, 2021
ed0464d
(feat): init commit
Sita04 Jul 16, 2021
59f22fd
(docs): modified var names
Sita04 Jul 19, 2021
7d15c34
(refactor): modified checking for site key properties
Sita04 Jul 19, 2021
168353f
(docs): added region tag and comments
Sita04 Jul 19, 2021
d069696
(docs): modified comments and var names
Sita04 Jul 19, 2021
b2c3286
(docs): changed the print var
Sita04 Jul 19, 2021
20c81fe
(refactor): dis-allow amp traffic
Sita04 Jul 19, 2021
056e2ce
(refactor): added assessment name and modified var name.
Sita04 Jul 23, 2021
c1ddfe8
fix: added copyright. Minor var name fixes.
Sita04 Aug 3, 2021
780851a
fix: changed key type. Added copyright.
Sita04 Aug 3, 2021
d1cb5e7
feat: init commit adding test cases and snippets
Sita04 Aug 18, 2021
9ca5108
refactor: lint fix and added dependencies
Sita04 Aug 18, 2021
0cd5d04
refactor: added webdrivermanager to remove driver binary dependency
Sita04 Aug 18, 2021
6e5ffc2
fix: lint error
Sita04 Aug 24, 2021
aa06bad
docs(samples): init commit client code samples
Sita04 Jul 16, 2021
06f6452
(feat): init commit
Sita04 Jul 16, 2021
60e3d43
(docs): modified var names
Sita04 Jul 19, 2021
c90c56c
(refactor): modified checking for site key properties
Sita04 Jul 19, 2021
30ae015
(docs): added region tag and comments
Sita04 Jul 19, 2021
eb88a5f
(docs): modified comments and var names
Sita04 Jul 19, 2021
0e5b4a3
(docs): changed the print var
Sita04 Jul 19, 2021
70a3ec3
(refactor): dis-allow amp traffic
Sita04 Jul 19, 2021
cd63b21
(refactor): added assessment name and modified var name.
Sita04 Jul 23, 2021
aa6a193
fix: added copyright. Minor var name fixes.
Sita04 Aug 3, 2021
8e40402
fix: changed key type. Added copyright.
Sita04 Aug 3, 2021
40d68d0
feat: init commit adding test cases and snippets
Sita04 Aug 18, 2021
16e74c7
refactor: lint fix and added dependencies
Sita04 Aug 18, 2021
46aab64
refactor: added webdrivermanager to remove driver binary dependency
Sita04 Aug 18, 2021
b11d34e
fix: lint error
Sita04 Aug 24, 2021
1342df2
fix: pom mismatch fixup
Sita04 Aug 24, 2021
5a7b6e9
Merge remote-tracking branch 'origin/update-client-samples' into upda…
Sita04 Aug 24, 2021
e28aae2
fix: pom mismatch fixup
Sita04 Aug 24, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions samples/snippets/cloud-client/src/main/java/app/Main.java
@@ -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);
}

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

@@ -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]
@@ -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]