zitinexus-router-script/UI/includes/auth.php

108 lines
2.8 KiB
PHP

<?php
/**
* Authentication handler for Ziti Router Enrollment UI
*/
require_once 'config.php';
class AuthManager {
/**
* Authenticate user with username and password
*/
public static function authenticate($username, $password) {
$username = sanitizeInput($username);
if ($username === ADMIN_USERNAME && password_verify($password, ADMIN_PASSWORD_HASH)) {
$_SESSION['authenticated'] = true;
$_SESSION['username'] = $username;
$_SESSION['last_activity'] = time();
$_SESSION['login_time'] = time();
// Generate new CSRF token
generateCSRFToken();
logMessage('INFO', "User '$username' logged in successfully from " . $_SERVER['REMOTE_ADDR']);
return true;
}
logMessage('WARNING', "Failed login attempt for user '$username' from " . $_SERVER['REMOTE_ADDR']);
return false;
}
/**
* Logout user
*/
public static function logout() {
if (isset($_SESSION['username'])) {
logMessage('INFO', "User '{$_SESSION['username']}' logged out");
}
session_destroy();
session_start();
}
/**
* Check if user is authenticated and session is valid
*/
public static function requireAuth() {
if (!isAuthenticated() || !isSessionValid()) {
header('Location: index.php?error=session_expired');
exit;
}
}
/**
* Get current user info
*/
public static function getCurrentUser() {
if (!isAuthenticated()) {
return null;
}
return [
'username' => $_SESSION['username'] ?? '',
'login_time' => $_SESSION['login_time'] ?? 0,
'last_activity' => $_SESSION['last_activity'] ?? 0
];
}
/**
* Check CSRF token for forms
*/
public static function requireCSRF() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token = $_POST[CSRF_TOKEN_NAME] ?? '';
if (!verifyCSRFToken($token)) {
http_response_code(403);
die('CSRF token validation failed');
}
}
}
}
/**
* Handle login form submission
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
if (AuthManager::authenticate($username, $password)) {
header('Location: dashboard.php');
exit;
} else {
$loginError = 'Invalid username or password';
}
}
/**
* Handle logout
*/
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
AuthManager::logout();
header('Location: index.php?message=logged_out');
exit;
}
?>