Link to home
Start Free TrialLog in
Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

asked on

How to Make Login Secure with Ajax

Hello Experts!
Please how can I make this login script more secure? Help me use prepare statement and if possible use Ajax to validate at client side. Thank you so much.
<?php

require '../includes/connection.php';

session_start();
$timeout = 1440; // Set timeout period in seconds

if (isset($_SESSION['start_time'])) {
    $elapsed_time = time() - $_SESSION['start_time'];
    if ($elapsed_time > $timeout) {
        header("Location: ../logout.php");
    }
}
$_SESSION['start_time'] = time();

$date_time = date("Y-m-d H:i:s");

function clean($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

//Login Query
if(isset($_POST['login_btn'])){

    $username = clean($_POST["username"]);
    $password = clean($_POST["password"]);
    
    $sql = "SELECT users.UserId AS UserId, users.Initials AS Initials, users.Username AS Username, users.Password AS Password, users.Role AS Role, users.ClassAssigned AS ClassAssigned, userclass.SubjectTaught AS SubjectTaught, tbl_subjects.Subject_Name AS Subject_Name, userclass.ClassTaught AS ClassTaught from ((users join userclass on((users.UserId = userclass.UserId))) left join tbl_subjects on((userclass.SubjectTaught = tbl_subjects.Subject_Code))) WHERE Username='$username'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {

        // output data of each row
        while($row = $result->fetch_assoc()) {
            if($row['Password'] == $password && $row['Role'] == 'Admin'){
                $_SESSION['username'] = $row['Username'];
                $_SESSION['c_assigned'] = $row['ClassAssigned'];
                $_SESSION['s_taught'] = $row['SubjectTaught'];
                $_SESSION['c_taught'] = $row['ClassTaught'];
                $_SESSION['u_initial'] = $row['Initials'];
                $_SESSION['u_role'] = $row['Role'];
                header("location: admin/dashboard.php");
            
            } elseif ($row['Password'] == $password && $row['Role'] == 'Form Master'){
                $_SESSION['username'] = $row['Username'];
                $_SESSION['c_assigned'] = $row['ClassAssigned'];
                $_SESSION['s_taught'] = $row['SubjectTaught'];
                $_SESSION['c_taught'] = $row['ClassTaught'];
                $_SESSION['u_initial'] = $row['Initials'];
                $_SESSION['u_role'] = $row['Role'];
                header("location: form_masters/dashboard.php");

            } elseif ($row['Password'] == $password && $row['Role'] == 'Subject Teacher') {
                $_SESSION['username'] = $row['Username'];
                $_SESSION['c_assigned'] = $row['ClassAssigned'];
                $_SESSION['s_taught'] = $row['SubjectTaught'];
                $_SESSION['c_taught'] = $row['ClassTaught'];
                $_SESSION['u_initial'] = $row['Initials'];
                $_SESSION['u_role'] = $row['Role'];
                header("location: staff/dashboard.php");

            } else {
                $error_msg = '<div class="alert alert-danger">
                        <strong>Wrong Password!</strong>
                        </div>';
               }
        }

        $status = "UPDATE Users SET Status = 1, login_at = '$date_time' WHERE Username = ?";
        $result = $conn->prepare($status);
        $result->bind_param("s", $username);
        $result->execute();


    } else {
        $error_msg = '<div class="alert alert-danger">
                        Access denied!</strong>
                        </div>';
    }


}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

ASKER

Thank you sir. I keep on getting Invalid Login though the details are correct.

See how I tried it.

<?php

require '../includes/connection.php';

session_start();

// Do we have some POST data
if (!empty($_POST)):

    // Make sure we have some values
    $username = isset($_POST['username']) ? $_POST['username'] : null;
    $password = isset($_POST['password']) ? $_POST['password'] : null;

    // Run the query
    $select = $conn->prepare("SELECT Initials, Username, Password, Role FROM users WHERE Username = ? LIMIT 1 ");

    $select->bind_param("s", $username);
    $select->execute();

    // Fetch a User
    $user = $select->get_result()->fetch_object();

    // Check that we found a user
    if ($user):

        // Check the password is correct
        if (password_verify($password, $user->Password)):

            // Update the login
            $login = $conn->prepare("UPDATE users SET Status = 1, login_at = NOW() WHERE Username = ? ");
            $login->bind_param("s", $username);
            $login->execute();

            // Set your session variable
            unset($user->Password); //we don't want the password stored in the session
            $_SESSION['user'] = $user;

            switch ($user->Role):

                case 'Admin':
                    echo "<p>Login Successful</p>";
                    //header("location: admin/dashboard.php");
                    break;

                case 'Form Master':
                    header("location: form_masters/dashboard.php");
                    break;

                case 'Subject Teacher':
                    header("location: staff/dashboard.php");
                    break;

            endswitch;

        else:

            // Wrong Password
            echo "<p>Invalid Login</p>";
        
        endif;
    
    else:
    
        // Wrong User
        echo "<p>Invalid Login</p>";
    
    endif;

endif;

Open in new window

OK. Have you changed the passwords in your database to be the hashed versions. If they're still the clear text versions, then you can't use password_verify. You'll just have to do a normal check, Change line 27 to this:

if ($password == $user->Password):

That will get you up and running but you should switch to hashed passwords as soon as possible
Thanks sir. It works. I'll get back on EE Question on how to use hashed password. Thank you so much sir
I added the following on dashboard page with the intention of retrieving Initials:
$user = $_SESSION['user'];
$initials =  $user->Initials;

Open in new window

I got "Notice: Undefined variable: _SESSION in"

What am I doing wrong?
Sounds like you're not starting the session. To use $_SESSION, you must call session_start() at the beginning of your script
Now:
Parse error: syntax error, unexpected '$user' (T_VARIABLE) in
Then you've probably missed a semi-colon from the end of the previous line :)
It's working. I included "connection.php" on dashboard page. Am I not supposed to do that?
That's up to you. You only need to include connection.php if you actually want to use the database on the dashboard page. If you don't need access to the DB, then there's no point in connecting to it.
Then you've probably missed a semi-colon from the end of the previous line :)

Correct. That's what I missed. Thanks