82 lines
2.8 KiB
PHP
82 lines
2.8 KiB
PHP
<?php
|
|
session_start();
|
|
require_once __DIR__ . '/db/config.php';
|
|
|
|
// If user is already logged in, redirect to dashboard
|
|
if (isset($_SESSION['user_id'])) {
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|
|
|
|
$error_message = '';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$username = $_POST['username'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
|
|
if (empty($username) || empty($password)) {
|
|
$error_message = 'Please enter both username and password.';
|
|
} else {
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
|
|
$stmt->execute([$username]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
// Password is correct, start session
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['user_username'] = $user['username'];
|
|
$_SESSION['user_role'] = $user['role'];
|
|
$_SESSION['user_fullName'] = $user['full_name'];
|
|
|
|
// Update last login timestamp
|
|
$updateStmt = $pdo->prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?');
|
|
$updateStmt->execute([$user['id']]);
|
|
|
|
header('Location: index.php');
|
|
exit;
|
|
} else {
|
|
$error_message = 'Invalid username or password.';
|
|
}
|
|
} catch (PDOException $e) {
|
|
$error_message = 'Database error. Please try again later.';
|
|
// In a real app, you would log this error instead of showing a generic message.
|
|
// error_log($e->getMessage());
|
|
}
|
|
}
|
|
}
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Login - Coho Connect</title>
|
|
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
|
|
</head>
|
|
<body class="login-body">
|
|
<div class="login-container">
|
|
<h2>Welcome to Coho Connect</h2>
|
|
<p>Please sign in to continue</p>
|
|
|
|
<?php if (!empty($error_message)): ?>
|
|
<div class="error-message"><?php echo htmlspecialchars($error_message); ?></div>
|
|
<?php endif; ?>
|
|
|
|
<form action="login.php" method="post">
|
|
<div class="form-group">
|
|
<label for="username">Username</label>
|
|
<input type="text" id="username" name="username" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="password">Password</label>
|
|
<input type="password" id="password" name="password" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<button type="submit">Sign In</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</body>
|
|
</html>
|