How to verify recaptcha in server call? - javascript

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>Password?</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 {
}
});
});

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

Related

im using jquery/ajax for login. Sending works and server side returns to log in, but this fails

I have created a login system with PHP, however, i also added two factor authentication. I wanted to log in without having to refresh the page so it looks better when asking for the 2FA code
The way i have done this is by sending the username and password via ajax. my php script then checks this and then it would echo login or error
Here's my javascript code
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'text',
success: function(data)
{
alert(data);
if (data === 'login') {
window.location = '/user-page.php';
}
else {
alert('Invalid Credentials');
}
},
});
});
});
This works fine, when i alert the data i get 'login' (without quotes, obviously) however it doesn't send me to user-page.php, instead, it gives me the invalid credentials alert. Despite the php page returning login, javascript is like "nope!"
What am i doing wrong?
Here's my form
<form class="form" id="login-form" name="login-form" method="post" role="form" accept-charset="UTF-8">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Gebruikersnaam</label>
<input type="username" class="form-control" id="gebruikersnaam" name="gebruikersnaam" placeholder="gebruikersnaam" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Wachtwoord</label>
<input type="password" class="form-control" id="wachtwoord" name="wachtwoord" placeholder="Password" required>
<div class="help-block text-right">Forget the password ?</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
I run the javascript from this page via <script src="auth.js"></script>. I also tried putting it directly inside script tags witch failed too.
This is for testing purpose
I believe your dataType should be either html or json
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data)
{
alert(data);
if (data == 'login') {
window.location = '/user-page.php';
}
if (data == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
In absence of your server logic
Your php inc/auth.php FOR Testing purpose
//$gebruikersnaam= $_POST['gebruikersnaam'];
//$wachtwoord= $_POST['wachtwoord'];
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
echo "login";
}
else
{
echo "failed";
}
As for CSRF attack mentioned by SO Scholar in the comment. you will need to generate something like md5 token that will be stored in a session. you will now send it with each request eg. in a hidden form input and verify that it matches the one on the server side. if match allow login otherwise trigger impersonation
Updates
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'JSON',
success: function(data)
{
alert(data);
if (data.login == 'success') {
window.location = '/user-page.php';
}
if (data.login == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
PHP
<?php
error_reporting(0);
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
$return_arr = array('login'=>'success');
}
else
{
$return_arr = array('login'=>'failed');
}
echo json_encode($return_arr);

jQuery validation AJAX form

I'm trying to add validation to my ResetPassword function. validation its work fine, but I got another problem my ResetPassword function not going to work after I add validation.Can anyone direct me in the right direction? thx.
HTML code:
<div class="PopUpBG">
<div class="PopUp">
<h3 class="modal-title">
<span>Reset PAssword</span>
</h3>
<form id="form">
<input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>
<input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>
</form>
</div>
</div>
ResetPassword & validation code:
function ResetPassword(e) {
var email = $("#ResetEmail").val();
if ($("#form").validate()) {
return true;
} else {
return false;
}
$(".PopUp").html("We have sent mail to you");
$.ajax(
{
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: email,
},
complete: function () {
console.log("send");
$(".PopUpBG").fadeOut();
}
})
}
The issue is because you're always exiting the function before you send the AJAX request due to your use of the return statement in both conditions of your if statement.
Change your logic to only exit the function if the validation fails:
function ResetPassword(e) {
if (!$("#form").validate())
return false;
$.ajax({
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: $("#ResetEmail").val().trim(),
},
success: function() {
console.log("send");
$(".PopUp").html("We have sent mail to you");
setTimeout(function() {
$(".PopUpBG").fadeOut();
}, 10000); // fadeout the message after a few seconds
},
error: function() {
console.log('something went wrong - debug it!');
}
})
}
Also note that I amended the logic to only show the successful email message after the request completes. Your current code can show the 'email sent' message to the user, even though there is still scope for the function to fail.

Small issue in node js application

In my nodejs application I have route /login which uses sendFile to display my html file which takes name and password.In my server side app.js I wrote post call to take name and password.Now from my html Iam doing an ajax call to call the post call and if success I want to go to /admin page.For this I am thinking of to call in my rest call itself res.send().But Iam not aware how to send html file ..
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/public/views/home.html');
});
app.get('/login', function(req, res, next) {
res.send('respond with a resource');
res.sendFile(__dirname + '/public/views/login.html');
});
app.get('/admin', function(req, res, next) {
res.sendFile(__dirname + '/public/views/admin.html');
});
app.post('/verifylogin',function(req,res){
var username = req.headers.uname;
var password = req.headers.pwd;
var uname = "admin";
var pwd = "admin";
var login = false;
if(uname == username && pwd == password){
console.log("success");
login = true;
} else {
console.log("fail");
login = false;
}
if(login == true){
res.send();//how can I take to /admin here
} else {
res.send("Bad luck");
}
});
html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function login(){
var uname = document.getElementById('uname').value;
var pwd = document.getElementById('pwd').value;
$.ajax({
url : '/verifylogin',
type : "POST",
headers : {
"uname":uname,
"pwd" :pwd
}
});
console.log("name",uname);
}
</script>
<h1>Login</h1>
<p>
<label class="control-label">Username</label>
<input type="text" placeholder="Username" id="uname"/>
</p>
<p>
<label class="control-label">Password</label>
<input type="password" placeholder="Password" id="pwd"/><br/>
</p>
<p>
<button type="submit" class="btn btn-primary" onclick="login()">Login</button>
</p>
If login is success how can I route to /admin ..can someone help here!
As #jfriend00 stated the browser doesn't redirect from an ajax call. So you can do 1 of the 2 options i'll show.
1º Option:
Client: Remove the ajax script and handle the call through html form.
Add a form to your html page:
<form method="post" action="/verifylogin">
<label class="control-label">Username</label>
<input type="text" placeholder="Username" name="uname"/>
<label class="control-label">Password</label>
<input type="password" placeholder="Password" name="pwd"/>
<button type="submit" class="btn btn-primary">Login</button>
</form>
Server:
Use the redirect method instead of send to redirect to the specified URL.
if (login == true) {
res.redirect('/admin');
}
2º Option: Send the page as content to the ajax call and redirect the page to it.
Client:
On your ajax post add the success function:
$.ajax({
url : '/verifylogin',
type : "POST",
headers : {
"uname":uname,
"pwd" :pwd
},
success: function(data) {
window.location = data;
}
});
Server:
if(login == true) {
res.contentType('application/json');
var data = JSON.stringify('your_url') // im not sure if you can use relative path here
res.header('Content-Length', data.length);
res.end(data);
}

Form submit issues using jQuery and Ajax

Actually I have 2 questions about form submit using jQuery and Ajax.
Currenlty, I am validating a login form using jQuery/Ajax request. I want to disabled the login submit button after logged in successfully completed. So that I am using following .js code but it's not disabled the submit button.
Questions
a) what is the issue in my js code ? why it's not disable the login submit button after logged in successfully ?
b) Using jQuery/Ajax for login is safe for security ? If not what I need to to and Should I add server side validation too ?
Thanks a lot :)
.js code for login :
// Login form
function login_form (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'login_process',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data == '<div class="alert alert-success"><strong>Successfully logged!.</strong></div>') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Login Process php page :
It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo '<div class="alert alert-success">';
echo '<strong>Successfully logged!.</strong>';
echo '</div>';
}
Html form :
<div class="container bellow-nav">
<div class="row">
<div class="col-md-6 content-area">
<h3>Login</h3>
<hr/>
<form role="form" method="post" id="login_form">
<div class="form-group">
<label for="email">Email addresse</label>
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="pwd" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="hidden" name="_token" value="<?php echo $form_token; ?>">
<input type="submit" name="submit" value="LOGIN" class="btn btn-booking" id="login_bottom" onclick="login_form(this,event);" >
</div>
<div class="form-group validation_msg">
</div>
<div class="fomr-group">
<label for=""><p>Forgot password?</p></label> |
<label for=""><p>Don't have an account? <a href="signup">Join now</p></label>
</div>
</form>
</div>
</div><!--main row-->
</div><!--main container end-->
One reason could be that the data may have some leading or trailing spaces.
You can extract only the text message from the data and use that for comparison
if ($(data).text().trim() == 'Successfully logged!.') {
$('#login_form')[0].reset();
$("#login_bottom").prop("disabled", true);
} else {
$("#login_bottom").prop("disabled", false);
}
For the second part, I assume the server side login is using a secured cookie to store the authentication information is so yes it is secured.
Use json response insted of HTML
Login Process php page : It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo json_encode(['message'=>'Success'])
}
$.ajax({
url: 'login_process',
type: 'POST',
dataType: 'JSON',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data.message == 'Success') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
First and for most, YOU MUST ADD SERVER SIDE VALIDATIONS. JavaScript can be disabled on the browser and your validations will be disabled when that happens. Javascript can also be edit on the browser and your validations will be useless js validations is only good for user friendly feeling and not for security.
All you have to do is set the disabled attribute to disabled value
$("#login_bottom").attr("disabled","disabled");
However I don't think you are going inside that if. you should console log something and make sure you are passing the if statement.

POST via Ajax does not work correctly

I looked now through a various number of StackOverflow pages and other websites - but can't find the correct solution for my problem. I try to post two values over to a php page via Post:
loginframe.php:
<form class="signin">
<input type="username" id="inputUsername" class="control" placeholder="Username" required autofocus>
<input type="password" id="inputPassword" class="control" placeholder="Password" required>
<div id="remember" class="checkbox">
<label>
<input type="checkbox" value="remember-me">Remember me
</label>
</div>
<button class="btn-login" type="submit" value="login" id="btn-login">Sign in</button>
</form>
My js:
$(document).ready(function(){
$("#btn-login").click(function(){
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
$.ajax(
{
type: "POST",
url: 'login.php',
data: {
user: username,
pass: password
},
success: function(result)
{
$("#result").html(result);
}
});
});
});
My login.php
<?php
if(isset($_POST['user']) && isset($_POST['pass']))
{
echo $_POST['user'];
echo $_POST['pass'];
} else {
include 'loginframe.php';
}
This login.php is just to check now if the data is passed. That is absolutely not the case. It always opens loginframe.php...
I can't find the error - I appreciate your help! Thank you a lot.
Use prevent default method.
$(document).ready(function(){
$("#btn-login").click(function(event){
event.preventDefault(); // this one prevents the default submission of the form
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
$.ajax(
{
type: "POST",
url: 'login.php',
data: {
user: username,
pass: password
},
success: function(result)
{
$("#result").html(result);
}
});
});
});

Categories

Resources