Jump to content

Output returning Null


Xtremer360

Recommended Posts

I'll be honest I don't see why I'm getting null for the ajax post response. Would someone be willing to take a second pair of eyes and see if they can spot it. It'd be much appreciated. I think it has to do with the timeRemaining area if the user is locked out but not positive.

 

<?php

session_start();

// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');

//Login submitted
if (isset($_POST['submit'])) { 

// Not already logged in
    if(!isset($_SESSION[$loggedinUserDataArray])) { 
    
        // Errors defined as not being any
        $errors = "no";
        
        // Assign variable values if there is values
        if((empty($_POST['username'])) || (trim($_POST['username'])=="") || ($_POST['username'] == NULL) || (!isset($_POST['username']))){$errors = "yes";}
        if((empty($_POST['password'])) || (trim($_POST['password'])=="") || ($_POST['password'] == NULL) || (!isset($_POST['password']))){$errors = "yes";}
        
        // Error checking, report errors if any
	if ($errors == "yes") {

            // Not all fields were entered error
            $message = "You must enter values for the username and password!";
        
            $output = array('errorsExist' => true, 'message' => $message);
            
	} else {
      
            // No errors reported 
            // Escape post data
            $username = mysqli_real_escape_string($dbc,$_POST['username']);
            
            // Query the database for user info with username
            $query = "SELECT * FROM manager_users WHERE username = '".$username."'";
            $result = mysqli_query($dbc,$query);
            
            // Count number of returned results from query
            if (mysqli_num_rows($result) > 0) {
                
                // Fetch returned data from result set
                $row = mysqli_fetch_array($result);
                
                $statusID = $row['statusID'];
                $userID = $row['userID'];
                
                if ($statusID == 1) {
                    
                    // User was not verified error
                    $errors = "yes";
                    $output = array('errorsExist' => true, 'message' => 'Sorry you must verify your email address before logging in. Didn\'t get the verification email? Don\'t worry we can <a href="javascript:void(0);" id="resendVerification">resend it</a>!');
                    
                } else if ($statusID == 3) {
                    
                    // User is suspended error
                    $errors = "yes";
                    $output = array('errorsExist' => true, 'message' => 'Your account has been suspended. If you would like to contest this action <a href="javascript:void(0);" id="contestSuspension">click here</a>!');
                    
                } else if ($statusID == 4) {
                    
                    // User is pending deletion error
                    $errors = "yes";
                    $output = array('errorsExist' => true, 'message' => 'Your account is currently deleted, would you like to reactivate it? <a href="javascript:void(0);" id="undeleteAccount">Yes, Reactivate</a>!');
                    
                } else {
                    
                    // User is registered and verified
                    
                    $query = "SELECT * FROM manager_users_logins_hacking WHERE userID = '".$userID."'";
                    $result = mysqli_query($dbc,$query);
                    $row = mysqli_fetch_array($result);
                    
                    $lockDate = $row['lockDate'];
                    
                    // Find out if user is locked out of their account
                    if (($lockDate !== "0000-00-00 00:00:00") AND (strtotime($lockDate) <= time())) {
                        
                        $currentDateTime = time();
                        $minutes = floor(($currentDateTime-$lockDate) / 60);
                        
                        // Take minutes and perform tasks
                        if ($lockDate > 0 && $minutes < 10) {
                            
                            // Calculate time remaining
                            $timeRemaining = 10 - $minutes;
                        
                            // Account locked error
                            $output = array('errorsExist' => true, 'message' => 'Your account is currently locked, we appologize for the inconvienence. You must wait ' .$timeRemaining.' minutes before you can log in again!');
                            
                        } else {
                            
                            // Clear the lock
                            $query = "UPDATE manager_users_logins_hacking SET lockDate = NULL WHERE userID = '".$userID."'";
                            $result = mysqli_query($dbc,$query);
                            
                            // Reset the value of number of attempts
                            $_SESSION['numberOfAttempts'] = 0;
                            
                        } 
                        
                    } else {
                        
                        // Escape post data
                        $password = mysqli_real_escape_string($dbc,$_POST['password']);
                        
                        $query = "SELECT * FROM manager_users WHERE userID = '".$userID."'";
                        $result = mysqli_query($dbc,$query);
                        $row = mysqli_fetch_array($result);
                        
                        // Assign password value from database to variable
                        $passwordDB = $row['password'];
                        
                        // Assign password 2 value from database to variable
                        $passwordDB2 = $row['password2'];
                        
                        // Assign hashed password to variable
                        $regenFromPostPW = reGenPassHash($password, $passwordDB2);
                        
                        // Comparing the database password with the posted password
                        if ($passwordDB == $regenFromPostPW) {
                            
                            $query = "SELECT * FROM manager_users_logins WHERE userID = '".$userID."'";
                            $result = mysqli_query($dbc,$query);
                            $row = mysqli_fetch_array($result);
                            
                            // Login successful
                            $numberOfLogins = $row['numberOfLogins']+1;
                            
                            $query2 = "UPDATE manager_users_logins SET numberOfLogins = '".$numberOfLogins."', lastOnline = CURRENT_TIMESTAMP";
                            $result2 = mysqli_query($dbc,$query2);
                            
                            // Query the database for user info with userID
                            $query3 = "SELECT * FROM manager_users WHERE userID = '".$userID."'";
                            $result3 = mysqli_query($dbc,$query3);
                            
                            // Fetch returned data from result set
                            $row3 = mysqli_fetch_array($result3);
                            
                            // Assign query array values to variables
                            $userID = $row3['userID'];
                            $firstName = $row3['firstName'];
                            $lastName = $row3['lastName'];
                            
                            // Assign user data into an array
                            $loggedinUserDataArray = array('userID' => $userID, 'name' => $firstName . " " . $lastName);
                            
                            // Assign user data array to new session
                            $_SESSION['user_data'] = $loggedinUserDataArray;
                            
                            // See if the remember me checkbox was checked
                            if (isset($_POST['remember'])) {
                                
                                // Sets an expiration time for the cookie
                                $myExpiration = time()+60*60*24*100;
                                
                                // Sets the cookie for the username
                                setcookie("username", $username, $myExiration, "/");
                                
                            }
                            
                            // Succesful login complete
                            $output = array('errorsExist' => false, 'message' => 'You have been logged in, please allow a moment while we load your account data!');
                            
                        } else {
                            
                            // Login unsuccessful
                            // Add to number of tries
                            $_SESSION['numberOfAttempts'] = $_SESSION['numberOfAttempts']+1;
                            
                            // Take numberOfAttempts and compare it 
                            if ($_SESSION['numberOfAttempts'] >= 5) {
                                
                                // Retrieve IP Address of user trying to hack into account
                                $hackerIPAddress = $_SERVER['REMOTE_ADDR'];
                                
                                // Update database after account getting hacked and run query
                                $query = "UPDATE manager_users_logins_hacking SET lockDate = CURRENT_TIMESTAMP, hackerIPAddress = '".$hackerIPAddress."' WHERE userID = '".$userID."'";
                                $result = mysqli_query($dbc,$query);
                                
                                $query2 = "SELECT * FROM manager_users WHERE userID = '".$userID."'";
                                $result2 = mysqli_query($dbc,$query2);
                                $row = mysqli_fetch_array($result2);
                                $firstName = $row['firstName'];
                                $lastName = $row['lastName'];
                                
                                // Email user new registration account
                                function my_domain_name() {
                            		$my_domain = $_SERVER['HTTP_HOST'];
                            		$my_domain = str_replace('www.', '', $my_domain);
                            		return $my_domain;
                            	}
                                $sender_email = "noreply@kansasoutlawwrestling.com";
                                $reply_to = "noreply@kansasoutlawwrestling.com";
                                $recipient_email = $email; 
                                $email_subject = "KOW Manager Account Locked";
                        
                                $email_body = 'Hello '.$firstName.' '.$lastName.' You, or someone using your account at '.my_domain_name().', has attempted to hack into your account. If this is an error, ignore this email and you will be removed from our mailing list.<br /><br />Regards, '.my_domain_name().' Team';
                                
                                mailSomeone($email, $sender_email, $email_subject, $email_body);
                                
                                // Account locked error
                                $output = array('errorsExist' => true, 'message' => 'Your account is currently locked, we appologize for the inconvienence. This is a security messure implimented by to many failed login\'s! You must wait 10 minutes before you can login again!');         
                            
                            } else {
                                
                                // Calculate how many chances the user has to login before account gets locked
                                $chancesLeft = 5 - $_SESSION['numberOfAttempts'];
                                
                                // Invalid username and password error 
                                $output = array('errorsExist' => true, 'message' => 'Invalid Username and Password combination! You have ' .$chancesLeft.' chances left to login succesfully or the account will be locked!'); 
                                
                            }
                            
                        }
                
                    }
                    
                }

            } else {
               
               // User doesn't exist in database error
               $output = array('errorsExist' => true, 'message' => 'Sorry we can\'t seem to find you in our system, please check your username and try again!'); 
                
            }
           

        }
        
} else {

        // User alread logged in and reported session exists
        $output = array('errorsExist' => true, 'message' => 'Already logged in!');
        
}
    
}

//Output the result
$output = json_encode($output);
echo $output;

?>

Link to comment
Share on other sites

Are you sure that your ajax code is even setting - $_POST['submit']?

 

I recommend that you either use error_log statements or http://www.firephp.org/ in your code so that you can determine what exactly your code is doing.

 

Without all your code, the database definition, and test data that would be needed to duplicate the problem, you cannot really expect someone else to try and figure out what 200+ lines of code is doing?

 

Edit: You could always debug your code using a HTML form (which you should have inside <noscript></noscript> tags anyway so that your page works in an expected manner when someone does not have javascript enabled.)

 

Link to comment
Share on other sites

I did look at some of your code and here are some hints -

 

1) The following code -

                            $query = "SELECT * FROM manager_users_logins WHERE userID = '".$userID."'";
                            $result = mysqli_query($dbc,$query);
                            $row = mysqli_fetch_array($result);
                            
                            // Login successful
                            $numberOfLogins = $row['numberOfLogins']+1;
                            
                            $query2 = "UPDATE manager_users_logins SET numberOfLogins = '".$numberOfLogins."', lastOnline = CURRENT_TIMESTAMP";
                            $result2 = mysqli_query($dbc,$query2);

 

Can be replaced by the following (you don't need to select data in order to update it and you had an error in the update query in that it was updating every row in your table because it didn't have a WHERE clause to cause it to match a specific row) -

 

                            $query2 = "UPDATE manager_users_logins SET numberOfLogins = numberOfLogins + 1, lastOnline = CURRENT_TIMESTAMP WHERE userID = '".$userID."'";
                            $result2 = mysqli_query($dbc,$query2);

 

2) You are executing a select query: SELECT * FROM manager_users WHERE ... 3 or 4 different times in that code, but all of them after the first one (the first one tests username in the where clause, the rest test the userID that the first one retrieved) are inside of conditional logic that is only true when the first one matched the username in the table. Just use the data that the first query returned instead of executing a query several more times to get data that you already have.

 

3) You are using a session variable to store the number of log in attempts. That won't work because A) It requires that the bot script attempting to log in even supports sessions and B) all you have to do to bypass your logic is to drop the session id and get a new session and you can keep making attempts. You must keep track of the number of log in attempts in a database table.

 

4) And I just saw in your Login successful code that you are setting $_SESSION['user_data']. You would probably want test that same session variable in your code that checks if someone is not already logged in. The following -

if(!isset($_SESSION[$loggedinUserDataArray])) { 

 

should be -

 

if(!isset($_SESSION['user_data'])) { 

 

 

Link to comment
Share on other sites

That's a great response. Thank you. I was able take care of #1 and #4. So your saying that I should add a field called failedAttempts to my logins table. And have it update each time as opposed to how I was dealing with it currently. The other thing is I didn't quite get a good understanding of #2.

Link to comment
Share on other sites

Yes, store a failed_attempts field in your table. Update it each time they have a bad login, and then have a limit defined somewhere. If failed_attempts > the limit, they can't log in. But, make it so that if they haven't received a bad login for X minutes, it clears the failedAttempts.

Link to comment
Share on other sites

For item #2. Near the start of your code, you are executing the following four lines of code -

            $query = "SELECT * FROM manager_users WHERE username = '$username'";
            $result = mysqli_query($dbc,$query);
            
            // Count number of returned results from query
            if (mysqli_num_rows($result) > 0) {
                
                // Fetch returned data from result set
                $row = mysqli_fetch_array($result);

 

The above code is matching the posted username against the username in the  manager_users table and is fetching that row from the table when there is a match. All the rest of your code, down to the }else{ statement that terminates the above if(){ statement, can use the data that you fetched in the above code. Just assign all the variables from that data once and eliminate all the extra queries selecting from that table -

	$statusID = $row['statusID'];
	$userID = $row['userID'];
	$firstName = $row['firstName'];
	$lastName = $row['lastName'];
	$passwordDB = $row['password'];
	$passwordDB2 = $row['password2'];

 

Doing this will greatly simplify and reduce the code from the // Escape post data comment through to the }else{ terminating statement. Your existing code between those two points would become -

 

<?php
                        // Escape post data
		$password = mysqli_real_escape_string($dbc,$_POST['password']); // not sure why you are escaping this since it is not being put into a query and is also being hashed
                        // Assign hashed password to variable
                        $regenFromPostPW = reGenPassHash($password, $passwordDB2);
                        // Comparing the database password with the posted password
                        if ($passwordDB == $regenFromPostPW) {
                            $query2 = "UPDATE manager_users_logins SET numberOfLogins = numberOfLogins + 1, lastOnline = CURRENT_TIMESTAMP WHERE userID = '".$userID."'";
                            $result2 = mysqli_query($dbc,$query2);
                            // Assign user data into an array
                            $loggedinUserDataArray = array('userID' => $userID, 'name' => $firstName . " " . $lastName);
                            // Assign user data array to new session
                            $_SESSION['user_data'] = $loggedinUserDataArray;

                            // See if the remember me checkbox was checked
                            if (isset($_POST['remember'])) {
                                // Sets an expiration time for the cookie
                                $myExpiration = time()+60*60*24*100;
                                // Sets the cookie for the username
                                setcookie("username", $username, $myExiration, "/");
                            }
                            
                            // Successful login complete
                            $output = array('errorsExist' => false, 'message' => 'You have been logged in, please allow a moment while we load your account data!');
                        } else {
                            // Login unsuccessful
                            // Add to number of tries
                            $_SESSION['numberOfAttempts'] = $_SESSION['numberOfAttempts']+1;
                            // Take numberOfAttempts and compare it 
                            if ($_SESSION['numberOfAttempts'] >= 5) {
                                // Retrieve IP Address of user trying to hack into account
                                $hackerIPAddress = $_SERVER['REMOTE_ADDR'];
                                // Update database after account getting hacked and run query
                                $query = "UPDATE manager_users_logins_hacking SET lockDate = CURRENT_TIMESTAMP, hackerIPAddress = '".$hackerIPAddress."' WHERE userID = '".$userID."'";
                                $result = mysqli_query($dbc,$query);
                                // Email user new registration account
                                function my_domain_name() {
                            		$my_domain = $_SERVER['HTTP_HOST'];
                            		$my_domain = str_replace('www.', '', $my_domain);
                            		return $my_domain;
                            	}
                                $sender_email = "noreply@kansasoutlawwrestling.com";
                                $reply_to = "noreply@kansasoutlawwrestling.com";
                                $recipient_email = $email; 
                                $email_subject = "KOW Manager Account Locked";
                                $email_body = 'Hello '.$firstName.' '.$lastName.' You, or someone using your account at '.my_domain_name().', has attempted to hack into your account. If this is an error, ignore this email and you will be removed from our mailing list.<br /><br />Regards, '.my_domain_name().' Team';
                                mailSomeone($email, $sender_email, $email_subject, $email_body);
                                
                                // Account locked error
                                $output = array('errorsExist' => true, 'message' => 'Your account is currently locked, we appologize for the inconvienence. This is a security messure implimented by to many failed login\'s! You must wait 10 minutes before you can login again!');         
                            } else {
                                // Calculate how many chances the user has to login before account gets locked
                                $chancesLeft = 5 - $_SESSION['numberOfAttempts'];
                                // Invalid username and password error 
                                $output = array('errorsExist' => true, 'message' => 'Invalid Username and Password combination! You have ' .$chancesLeft.' chances left to login succesfully or the account will be locked!'); 
                            }
                        }
                    }
                }
            } else {

Link to comment
Share on other sites

Thank you greatly. Only issue is my if else statement that is centered around the failedLogins part because with the chancesLeft if it should show 0 it should be doing the part of the if statement above that is >=5 but its not.

 

That should cover everything else that was considered about changing in this topic post.

 

http://pastebin.com/vFZwmJuc

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.