This is the code to my login.php
<?php
// Include the database connection file
include('db.php');
// Start the session
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array('success' => false, 'message' => '');
// Clean input data
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$password = $_POST['password'];
try {
// Check if the email exists
$stmt = $pdo->prepare("SELECT * FROM Users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
$response['message'] = "Email or password is incorrect";
echo json_encode($response);
exit();
}
// Verify the password
if (!password_verify($password, $user['password'])) {
$response['message'] = "Email or password is incorrect";
echo json_encode($response);
exit();
}
// Get the user's roles
$stmt = $pdo->prepare("SELECT r.role_name
FROM UserRoles ur
INNER JOIN Roles r ON ur.role_id = r.role_id
WHERE ur.user_id = ?");
$stmt->execute([$user['user_id']]);
$user_roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$user_roles) {
$response['message'] = "User roles not found!";
echo json_encode($response);
exit();
}
// Create session token
$token = bin2hex(random_bytes(16));
$expiresAt = date("Y-m-d H:i:s", strtotime('+1 hour'));
// Insert session into LoginSessions table
$stmt = $pdo->prepare("INSERT INTO LoginSessions (user_id, session_token, expires_at) VALUES (?, ?, ?)");
$stmt->execute([$user['user_id'], $token, $expiresAt]);
$_SESSION['session_token'] = $token;
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_role'] = $user_roles[0]['role_name']; // Assuming the first role is the primary role
$response['success'] = true;
$response['message'] = "Login successful!";
$response['role'] = $user_roles[0]['role_name']; // Assuming the first role is the primary role
} catch (Exception $e) {
$response['message'] = "An error occurred: " . $e->getMessage();
}
echo json_encode($response);
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<div class="container">
<h2>Login</h2>
<div id="message"></div>
<form id="loginForm" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="form-group">
<input type="checkbox" id="showPassword"> Show Password
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
<div class="form-group">
<a href="forgot_password.php">Forgot Password?</a>
</div>
</div>
<script>
$(document).ready(function(){
$("#loginForm").on("submit", function(event){
event.preventDefault();
$.ajax({
url: "login.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(response) {
if (response.success) {
$("#message").html('<div class="alert alert-success">' + response.message + '</div>');
setTimeout(function() {
var role = response.role;
switch(role) {
case 'Super Admin':
window.location.href = "super_admin_dashboard.php";
break;
case 'General Overseer':
window.location.href = "general_overseer_dashboard.php";
break;
case 'Regional Overseer':
window.location.href = "regional_overseer_dashboard.php";
break;
case 'District/Area Overseer':
window.location.href = "district_area_overseer_dashboard.php";
break;
case 'Church Administrator':
window.location.href = "church_administrator_dashboard.php";
break;
case 'Finance Officer':
window.location.href = "finance_officer_dashboard.php";
break;
case 'Pastor':
window.location.href = "pastor_dashboard.php";
break;
case 'Member':
window.location.href = "member_dashboard.php";
break;
default:
window.location.href = "dashboard.php";
}
}, 2000);
} else {
$("#message").html('<div class="alert alert-danger">' + response.message + '</div>');
}
},
error: function(xhr, status, error) {
console.log("Error status: " + status);
console.log("Error message: " + error);
console.log("XHR: " + xhr.responseText);
$("#message").html('<div class="alert alert-danger">An error occurred while processing your request. Please try again.</div>');
}
});
});
// Show/hide password functionality
$('#showPassword').on('change', function() {
var passwordField = $('#password');
var confirmPasswordField = $('#confirm_password');
var type = $(this).is(':checked') ? 'text' : 'password';
passwordField.attr('type', type);
confirmPasswordField.attr('type', type);
});
});
</script>
</body>
<footer class="footer">
<div class="container">
<span class="text-muted">© 2024 Your Church. All Rights Reserved.</span>
</div>
</footer>
</html>
Below is my session.php
code
<?php
session_start();
include('db.php');
include_once('functions.php');
// Check if the user is logged in
if (!isset($_SESSION['session_token']) || !isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
$user_id = sanitize_input($_SESSION['user_id'], $pdo);
// Validate the session token
$sql = "SELECT * FROM LoginSessions WHERE user_id = ? AND session_token = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$user_id, $_SESSION['session_token']]);
$session = $stmt->fetch(PDO::FETCH_ASSOC);
// Fetch user role
$sql = "SELECT r.role_name
FROM UserRoles ur
INNER JOIN Roles r ON ur.role_id = r.role_id
WHERE ur.user_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$user_id]);
$user_role = $stmt->fetch(PDO::FETCH_ASSOC)['role_name'];
if ($user_role) {
$_SESSION['user_role'] = $user_role;
} else {
// No role found for the user
echo "User role not found!";
exit();
}
// Redirect based on user role
switch ($user_role) {
case 'Super Admin':
header('Location: super_admin_dashboard.php');
break;
case 'General Overseer':
header('Location: general_overseer_dashboard.php');
break;
case 'Regional Overseer':
header('Location: regional_overseer_dashboard.php');
break;
case 'District/Area Overseer':
header('Location: district_area_overseer_dashboard.php');
break;
case 'Church Administrator':
header('Location: church_administrator_dashboard.php');
break;
case 'Finance Officer':
header('Location: finance_officer_dashboard.php');
break;
case 'Pastor':
header('Location: pastor_dashboard.php');
break;
case 'Member':
header('Location: member_dashboard.php');
break;
default:
echo "Invalid user role.";
exit();
}
?>
Please help me fix this error. I have tried clearing cookies and also tried different browsers.
New contributor
CODE THINO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.