db = Database::getInstance(); if (LDAP_ENABLED) { $this->ldap = new LDAPAuth(); } } public function login($username, $password) { // First, try to find user in database $sql = "SELECT * FROM users WHERE username = ?"; $user = $this->db->fetch($sql, [$username]); if (!$user) { return false; } // Check authentication based on user's auth type if ($user['auth_type'] === 'ldap' && LDAP_ENABLED) { // LDAP authentication if ($this->ldap->authenticate($username, $password)) { // Get LDAP user info and update database $ldapUserInfo = $this->ldap->getUserInfo($username); if ($ldapUserInfo) { $this->updateUserFromLDAP($user['id'], $ldapUserInfo); } $this->createSession($user); $this->updateLastLogin($user['id']); return true; } } elseif ($user['auth_type'] === 'local') { // Local authentication if ($user['password'] && password_verify($password, $user['password'])) { $this->createSession($user); $this->updateLastLogin($user['id']); return true; } } return false; } public function logout() { session_destroy(); unset($_SESSION); } public function isLoggedIn() { return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true; } public function requireAuth() { if (!$this->isLoggedIn()) { header('Location: login.php'); exit; } } public function getUser() { if ($this->isLoggedIn()) { return [ 'id' => $_SESSION['user_id'], 'username' => $_SESSION['username'], 'role' => $_SESSION['role'] ]; } return null; } public function isAdmin() { return $this->isLoggedIn() && $_SESSION['role'] === 'admin'; } private function createSession($user) { $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $user['username']; $_SESSION['role'] = $user['role']; $_SESSION['auth_type'] = $user['auth_type']; $_SESSION['logged_in'] = true; } private function updateLastLogin($userId) { $sql = "UPDATE users SET last_login = NOW() WHERE id = ?"; $this->db->query($sql, [$userId]); } private function updateUserFromLDAP($userId, $ldapUserInfo) { $updateData = []; if (isset($ldapUserInfo['email'])) { $updateData['email'] = $ldapUserInfo['email']; } if (isset($ldapUserInfo['ldap_dn'])) { $updateData['ldap_dn'] = $ldapUserInfo['ldap_dn']; } if (!empty($updateData)) { $this->db->update('users', $updateData, 'id = ?', [$userId]); } } public function createLDAPUser($username, $ldapUserInfo) { // Check if user already exists $sql = "SELECT id FROM users WHERE username = ?"; $existing = $this->db->fetch($sql, [$username]); if ($existing) { return $existing['id']; } // Create new user from LDAP $userData = [ 'username' => $username, 'email' => $ldapUserInfo['email'] ?? '', 'role' => 'editor', // Default role for LDAP users 'auth_type' => 'ldap', 'ldap_dn' => $ldapUserInfo['ldap_dn'] ?? '' ]; return $this->db->insert('users', $userData); } public function getAuthType() { return $_SESSION['auth_type'] ?? 'local'; } } // Initialize session if (session_status() === PHP_SESSION_NONE) { session_start(); }