Obodo Posted January 26 Share Posted January 26 I don't know where i am missing it. Instead of continue login process, it's validating the form again (asking for username and pasword.) I really don't know why the form is resetting. <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN'; $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN'; $newToken = bin2hex(random_bytes(32)); $errors = []; $forceLogin = isset($_POST['force_login']) && $_POST['force_login'] == '1'; if (empty($_POST['email'])) { $errors['username'] = "Username is required"; } else { $email = trim($_POST['email']); } if (empty($_POST['password'])) { $errors['password'] = "Password is required"; } else { $pass = $_POST['password']; } if (empty($errors)) { $stmt = $pdo->prepare("SELECT * FROM tbl_users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user) { $status = ['type' => 'error', 'message' => 'Invalid credentials.']; }elseif ($user['account_locked_until'] !== null && strtotime($user['account_locked_until']) > time()) { $status = ['type' => 'error', 'message' => 'Account is locked. Please try again later.']; }elseif (password_verify($pass, $user['password'])) { $sessionCheck = $pdo->prepare(" SELECT * FROM tbl_user_session WHERE user_id = ? AND is_active = 'yes' AND expires_at > ? ORDER BY id DESC LIMIT 1 "); $sessionCheck->execute([$user['user_id'], time()]); $activeSession = $sessionCheck->fetch(PDO::FETCH_ASSOC); $haltLogin = false; if ($activeSession && $user['role'] === 'admin' && $forceLogin) { $killSessions = $pdo->prepare(" UPDATE tbl_user_session SET is_active = 'no', expires_at = ? WHERE user_id = ? AND is_active = 'yes' "); $killSessions->execute([time(), $user['user_id']]); $haltLogin = false; }elseif ($activeSession) { if ($user['role'] === 'student') { $haltLogin = true; echo "<script>var showAlert1 = true;</script>"; } if ($user['role'] === 'admin' && !$forceLogin) { $haltLogin = true; echo "<script>var showAlert2 = true;</script>"; } } $reset = $pdo->prepare(" UPDATE tbl_users SET failed_attempts = 0, account_locked_until = NULL, last_login_at = NOW() WHERE user_id = ? "); $reset->execute([$user['user_id']]); $stmt = $pdo->prepare(" INSERT INTO tbl_login_log (admin_id, email, action, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, ?, NOW()) "); $stmt->execute([ $user['user_id'], $user['email'], 'LOGIN_SUCCESS', $ip_address, $userAgent ]); $_SESSION['user'] = [ 'user_id' => $user['user_id'], 'email' => $user['email'], 'role' => $user['role'] ]; $_SESSION['active_id'] = $user['user_id']; $_SESSION['session_token'] = $newToken; $status = ['type' => 'success', 'message' => 'Login successful! Redirecting...']; if (!$haltLogin) { $idleTimeout = 30 * 60; $expiresAt = time() + $idleTimeout; $insertSession = $pdo->prepare(" INSERT INTO tbl_user_session (session_token, user_id, ip_address, user_agent, last_activity, expires_at, is_active, created_at) VALUES (?, ?, ?, ?, NOW(), ?, 'yes', NOW()) "); $insertSession->execute([ $newToken, $user['user_id'], $ip_address, $userAgent, $expiresAt ]); } }else { $failed = $user['failed_attempts'] + 1; $lockTime = null; if ($failed >= 3) { $lockTime = date("Y-m-d H:i:s", strtotime("+15 minutes")); $status = [ 'type' => 'error', 'message' => 'Account locked after 3 failed attempts. Try again in 15 minutes.' ]; } else { $status = [ 'type' => 'error', 'message' => "Invalid credentials. Attempt {$failed} of 3." ]; } $update = $pdo->prepare(" UPDATE tbl_users SET failed_attempts = ?, account_locked_until = ? WHERE user_id = ? "); $update->execute([$failed, $lockTime, $user['user_id']]); $stmt = $pdo->prepare(" INSERT INTO tbl_login_log (admin_id, email, action, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, ?, NOW()) "); $stmt->execute([ $user['user_id'], $user['email'], 'LOGIN_FAILED', $ip_address, $userAgent ]); } } } ?> <script> Swal.fire({ icon: '<?= $status['type'] ?>', title: '<?= $status['message'] ?>', showConfirmButton: false, timer: 2500 }).then(() => { <?php if ($status['type'] === 'success'): ?> const role = '<?= $_SESSION['user']['role'] ?>'; if (role === 'admin' || role === 'staff') { window.location.href = '../admin/index.php'; } else if (role === 'student') { window.location.href = '../student/dashboard.php'; } <?php endif; ?> }); if (typeof showAlert1 !== 'undefined' && showAlert1) { Swal.fire({ icon: 'warning', title: 'Warning', text: 'You are logged in on another device.', }); } if (typeof showAlert2 !== 'undefined' && showAlert2) { Swal.fire({ icon: 'warning', title: 'Warning', text: 'You are logged in on another device. Continue and log out the other session?', showCancelButton: true, confirmButtonText: "Yes, Continue", cancelButtonText: "Cancel" }).then((result) => { if (result.isConfirmed) { document.getElementById('force_login').value = '1'; document.getElementById('loginForm').submit(); } }); } </script> Quote Link to comment https://forums.phpfreaks.com/topic/332511-resetting-login-form-instead-of-continue-login/ Share on other sites More sharing options...
mac_gyver Posted January 26 Share Posted January 26 (edited) the apparent symptom you are having (do you actually see any Swal dialog?) is that of code that redirects to another page that then redirects back to the starting page. you should temporarily comment out the redirect statements and add console.log() statements so that you can uniquely determine which execution path the javascript code takes. do you have a session_start() statement on each page that sets or references a session variable? there is none in the posted code. if you are not seeing any Swal dialog, you will need to determine why. are there errors in the browser's developer console? what data is in $status? the posted code is not displaying any $errors data. if you cannot determine the cause of the problem, you will need to post all the code necessary to reproduce the problem. less anything like database connection credentials, api keys, ... some points for the posted code - the only piece of user data you should store in a session variable is the user id (auto-increment primary index.) you should query on each page request to get any other user data, so that any changes made to the user data will take effect on the very next page request, without requiring the user to log out and back in again. you need to validate the trimmed input data, not the raw input data. by validating the raw value, then trimming and using it, the current code will accept any collection of white-space characters as a valid email address, but use an empty string in the rest of the code. after you determine that the trimmed email input is not an empty string, you need to validate that it is a properly formatted email address. see php's filter_var() with the FILTER_VALIDATE_EMAIL filter. don't change the name of a piece of data in the code. if the input is an email address, don't refer to it as anything else. if you set the default fetch mode to assoc when you make the database connection, you wont need to specify it in each fetch statement. you need to integrate the login operation on any page that needs it, rather than redirecting around on the site. this alone would help with debugging the problem and will simplify all the code. i didn't examine all the logic/possible execution paths in great detail to see if there were any 'holes' where the code wouldn't tell you when something went wrong. by determining what the execution path is and what data is being produced by the code, you should be able to pin down where the problem is occurring. Edited January 26 by mac_gyver Quote Link to comment https://forums.phpfreaks.com/topic/332511-resetting-login-form-instead-of-continue-login/#findComment-1662303 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.