info : hormis la partie spécifique à django (mais adaptable) ce tutoriel reste valable peut importe votre framework.
Pour utiliser ce service nous allons devoir créer un projet sur google cloud.
Pour ce faire vous devez suivre ce lien
Afin de permettre à notre site web de contacter l'API de google qui va nous renvoyer le score du captcha il nous faut un fichier json.
<script src="https://www.google.com/recaptcha/enterprise.js?render=idkeyaremplacer"></script>
<script>
$("form#contact_form").submit(function (e) {
e.preventDefault();
var form = $(this);
grecaptcha.enterprise.ready(function () {
grecaptcha.enterprise.execute('idkeyaremplacer', {action: 'contact'}).then(function (token) {
$('<input>').attr({
type: 'hidden',
name: 'g-recaptcha-response',
value : token
}).appendTo(form);
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
dataType: 'json',
success: function (data) {
form.find(".loading").hide();
form.find(".sent-message").show();
},
error: function () {
form.find(".loading").hide();
form.find(".error-message").show();
},
});
});
});
});
});
</script>
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "monfichier.json"
from google.cloud import recaptchaenterprise_v1
from google.cloud.recaptchaenterprise_v1 import Assessment
def create_assessment(
project_id: str, recaptcha_site_key: str, token: str, recaptcha_action: str
) -> Assessment:
"""Create an assessment to analyze the risk of a UI action.
Args:
project_id: GCloud Project ID
recaptcha_site_key: Site key obtained by registering a domain/app to use recaptcha services.
token: The token obtained from the client on passing the recaptchaSiteKey.
recaptcha_action: Action name corresponding to the token.
"""
client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()
# Set the properties of the event to be tracked.
event = recaptchaenterprise_v1.Event()
event.site_key = recaptcha_site_key
event.token = token
assessment = recaptchaenterprise_v1.Assessment()
assessment.event = event
project_name = f"projects/{project_id}"
# Build the assessment request.
request = recaptchaenterprise_v1.CreateAssessmentRequest()
request.assessment = assessment
request.parent = project_name
response = client.create_assessment(request)
# Check if the token is valid.
if not response.token_properties.valid:
print(
"The CreateAssessment call failed because the token was "
+ "invalid for for the following reasons: "
+ str(response.token_properties.invalid_reason)
)
return
# Check if the expected action was executed.
if response.token_properties.action != recaptcha_action:
print(
"The action attribute in your reCAPTCHA tag does"
+ "not match the action you are expecting to score"
)
return
else:
# 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
for reason in response.risk_analysis.reasons:
print(reason)
print(
"The reCAPTCHA score for this token is: "
+ str(response.risk_analysis.score)
)
# Get the assessment name (id). Use this to annotate the assessment.
assessment_name = client.parse_assessment_path(response.name).get("assessment")
print(f"Assessment name: {assessment_name}")
return response
def contact(request):
re_captcha_reponse = create_assessment(
project_id="myprojectid",# à récupérer sur le tableau de bord de votre projet dans google cloud
recaptcha_site_key="sitekey",
recaptcha_action="contact",
token=request.POST["g-recaptcha-response"]
)
messagetouser = ""
if re_captcha_reponse.risk_analysis.score > 0.5 and re_captcha_reponse.token_properties.action == "contact":
send_mail(
request.POST["name"],
request.POST["message"],
request.POST["email"],
[EMAIL_TO],
fail_silently=False,
)
return HttpResponse("bien reçu")
A la mise en ligne ne pas oublier d'ajouter l'api google au projet.
Avec l'environnement virtuel du projet activée (venv)
pip install google-cloud-recaptcha-enterprise