Coder1000 Coder1000 - 1 year ago 66
Ajax Question

How to verify recaptcha in server call?

SITUATION:

I used to check my recaptcha with a simple form submit with POST to "/login".

I need to change my implementation for security reasons and would like to do something like:

1) Jquery form submit.

2) Make call to server to call verify recaptcha on the server.

3) Receive response without reloading page.

4) Accept login request or not based on response.




QUESTION:

It looks like I could make an AJAX request ? But I don't know how.




CLIENT CODE:

<div class ="containerMargins">
<h1 class = "authTitle">Login</h1>
<form id="loginForm">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" id="loginEmail" placeholder="You can't forget it :)" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" id="loginPassword" placeholder="We hope you didn't forget it ^^" required minlength="12">
</div>
<div class="g-recaptcha" data-sitekey="6LcRrxMUAAAAANx-AXSdRLAo4Pyqfqg-1vuPSJ5c"></div>
<button class="btn btn-default" id="loginButton">Submit</button> <span class="userLinks">
<a class="logLinks" href="/users/register">Register</a><a href="/users/password">Password?</a></span>
</form>
</div>

</div>

<% include ../partials/indexScripts %>

<script>

$("#loginForm").submit(function(e) {

e.preventDefault();
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();

// WOULD LIKE TO MAKE SERVER CALL HERE TO CHECK RECAPTCHA BUT I DONT KNOW HOW

$this = $(this);
$.ajax({
type: "POST",
url: "users/register",
data: $this.serialize()
}).done(function(data) {

if (successfulRecaptcha) {
firebase.auth().signInWithEmailAndPassword(email, password ).then( authData => {
}
else {
console.log("You are a robot!");
}





SERVER CODE:

router.post('/login', function(req, res, next) {
verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
if (success) {

} else {

}
});
});

Answer Source

I found the solution :

FRONT END:

$this = $(this);
    $.ajax({
        type: "POST",
        url: "login",
        data: $this.serialize()
    }).done(function(data) {

        if (data == true) {

BACKEND:

router.post('/login', function(req, res, next) {
    verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
        if (success) {
            res.send(true);
        } else {
            res.send(false);
        }
    });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download