I need to implement a captcha with v3 in grails but I'm relatively new to implementing captchas has anyone ever implemented it in grails 2.5.6?
we have used google recaptcha in contact us form.
I am using grails 2.2.
In the contact us gsp.
put this in head
<script src='https://www.google.com/recaptcha/api.js'></script>
where you would like captcha to show
<div id="captcha" class="g-recaptcha" data-sitekey="${grailsApplication.config.captchaSiteKey}"></div>
put captchasitekey in config.groovy
captchaSiteKey = "234234lkjh234kjhdsf98sdflhjsdf"
captchaSecretKey = "12121234jh234kjhdsf98sdflhjsdf"
create your keys in google recaptcha admin console
https://www.google.com/recaptcha/about/
contact us submit button
<input type="button" value="Send" onClick="sendRequest()" class="button"/>
Javascript code
<g:javascript>
function sendRequest(){
var email_string = $('input[name="email"]').val();
var body_string = $('textarea[name="body"]').val();
var cap_response = $('textarea[name="g-recaptcha-response"]').val();
var replying = "${params['s']}"
var idd = "${params['i']}"
if(email_string && body_string){
$.ajax('<g:createLink controller="public" action="sendMessage"/>', {
type:"post",
dataType: 'text',
data:{body: body_string, email: email_string, reply: replying, id: idd, recap_response: cap_response},
success: function(data) {
$('#body').val("");
$('#email').val("");
alert("Thanks for contacting us! We will respond promptly.");
},
error: function(xhr){
alert('Sorry there was a problem sending message. Please try again!'); //<----when no data alert the err msg
}
});
}
else{
alert("Please make sure you enter your email and message before sending us message.")
}
}
</g:javascript>
Server side
def sendMessage(){
def res = params['recap_response']
HttpURLConnection post = (HttpURLConnection)(new URL("https://www.google.com/recaptcha/api/siteverify").openConnection());
String urlParameters = "secret=${grailsApplication.config.captchaSecretKey}&response=${res}";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
post.getOutputStream().write(postData);
def postRC = post.getResponseCode();
def recaptchaOK = false
if(postRC.equals(200)) {
def jsonSlurper = new JsonSlurper()
def resp = jsonSlurper.parseText(post.getInputStream().getText())
recaptchaOK = resp.success
}
if(!recaptchaOK){
render "Captcha was wrong. Please try again!"
return
}
This is the documentation i referred to implement mine.
https://developers.google.com/recaptcha/intro
hope this helps!