0

I am creating a login page using PHP and AJAX. I want a user to attempt login only 3 times, after then a timer should be started, if user doesn't enter correct details. Timer should be started so that it will not change even if the user refreshes the page. I am sending data from a AJAX page and validating it into a PHP page.My all code for timer starts from if (res.error == 'not_found') statement . Here are my codes :

AJAX code :

var validateCounter = 0;
var counter = 60;

//login form code

$('#loginForm').submit(function(e) {
    e.preventDefault();
    var username = $('#loginEmail').val();
    var password = $('#loginPassword').val();
    var form1 = document.getElementById('loginForm');
    var len = form1.length;

    $.ajax({
        method: "post",
        url: "loginserver.php",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function(response) {
            var res = JSON.parse(response);
            if (username == '' || password == '') {
                for (i = 0; i < (len - 1); i++) {
                    form1.elements[i].style.border = "1px solid red";
                    form1.elements[i].style.textShadow = "1px 1px 2px #000";
                }
            } else {
                if (res.error == 'not_found') {
                    for (i = 0; i < (len - 1); i++) {
                        form1.elements[i].style.border = "1px solid red";
                        form1.elements[i].value = null;
                    }
                    validateCounter += 1;
                    console.log(validateCounter);
                    if (validateCounter > 2) {
                        var interval = setInterval(function() {
                            counter--;
                            if (counter <= 0) {
                                clearInterval(interval);
                                $('#timer').fadeOut();
                                $('#loginEmail').attr('disabled', false);
                                $('#loginPassword').attr('disabled', false);
                                $('#loginSubmit').attr('disabled', false);
                                validateCounter = 0;

                            } else {
                                $('#timer').show();
                                $('#timer span').text(counter + " s");
                                $('#loginEmail').css('border', 'none');
                                $('#loginEmail').attr('disabled', true);
                                $('#loginPassword').css('border', 'none');
                                $('#loginPassword').attr('disabled', true);
                                $('#loginSubmit').attr('disabled', true);
                            }
                        }, 1000);
                    }
                } else if (res.success == 'authorized') {
                    location.href = "index.php";
                }
            }
        }
    });

});

PHP code :

<?php
session_start();
include('../dbconnection.php');

function validate($data){
    return htmlspecialchars($data);
}
$adminName = validate($_POST['loginEmail']);
$adminPass = validate($_POST['loginPassword']);

//validating admin
$select_stmt = $connection -> prepare("SELECT * FROM `admin`
                                WHERE `admin_username`=? AND `admin_password`=?");
$select_stmt -> bind_param('ss',$adminName, $adminPass);

$select_stmt -> execute();
// get result into a variable
$result = $select_stmt -> get_result();

//store result using fetch_array
$data = $result -> fetch_assoc();

//get rows from result
$num_rows = $result -> num_rows;

if( $num_rows > 0){
    echo json_encode(array('success' => 'authorized'));
    $_SESSION['adminId'] = $data['admin_id'];
}else{
    echo  json_encode(array('error'=>'not_found')); 
}

?>

Actually this login page is for website's admin only and no one else can login from here. Since I know the username and password I will login successfully, but if any other person wants to login, then he should be totally locked after 3 attempts. A timer should start after 3 attempts , so that it will not change when - 1 : Page is refreshed 2 : incognito mode is started 3 : browser is closed and reopened These all 3 criteria should be in the person's device who is trying to login. I should still be able to login from my device .

  • when you detect the 3rd failed attempt, store the time of that attempt in the database on the server, against the username which was attempted. Then, if the user refreshes the page,or tries from another device or browser, you can restart the timer from the correct time (to work it out, just subtract the current time from the time of the 3rd attempt). N.B. This assumes you're trying to lock out people guessing the password for a specific account 3 times. If you just 3 failed attempts of any sort, regardless of the username, then you'd have to store that info in the session, not the database. – ADyson Mar 06 '20 at 13:54
  • P.S. it looks like you are not [hashing your passwords](https://www.php.net/manual/en/faq.passwords.php). You should hash them to improve security. – ADyson Mar 06 '20 at 13:56
  • Thanks @ADyson for quick reply, Can you please tell me that in little brief. – Aftab Ansari Mar 06 '20 at 14:00
  • You're absolutely right @Adyson, I want user to be locked on 4th attempt. Should I do it in php page ? And thanks for your advise on hashing passwords. – Aftab Ansari Mar 06 '20 at 14:08
  • Do not use `validate` when inputting the data into DB. Use `htmlspecialchars` only when outputting to HTML – Dharman Mar 06 '20 at 14:11
  • 2
    **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Mar 06 '20 at 14:11
  • `if( $num_rows > 0)` should be `if($data)` instead. – Dharman Mar 06 '20 at 14:12
  • Thanks @Dharman for your valuable information. I will definitely do that. Can you tell me how to start a timer which does not change on page refresh? – Aftab Ansari Mar 06 '20 at 14:17
  • @ADyson I got you, but now I noticed another thing that what if the person ,who is trying to login, closes the browser and opens that page again ? He will be able to enter data without waiting for time limit. Can you please help me that how can I solve this ? – Aftab Ansari Mar 06 '20 at 14:42
  • If you stored the data about login attempts in the session, then that would be true. But actually, do you really just want to set the timer _any_ 3 login attempts? What is the real purpose of the timer? Most sites will only do this kind of thing if you make 3 failed attempts to login to a specific user account. So if I try and log into your account 3 times and fail,your account would be locked out and need a reset. But I could still log into my own account no problem. – ADyson Mar 06 '20 at 14:49
  • 1
    If you did it that way, then the failed attempts would be stored in the database against a specific user's record. it would not matter if the user closes the browser, or uses another browser, or uses incognito mode, or uses another computer entirely, that account would still be locked out. Whereas you seem to want to lock out a specific device? If you used localstorage to set a flag for that, you could stop the user refreshing the page to get rid of the timer, but you couldn't stop them opening incognito mode, or opening another browser, or switching to another device - all trivial workarounds – ADyson Mar 06 '20 at 14:51

0 Answers0