/home/awneajlw/www/codestechvista.com/includes/auth.php
<?php
/**
 * Authentication and Session Management
 * This file handles all authentication-related functions including:
 * - User login/logout functionality
 * - Session management and security
 * - Login status checking
 * - Session timeout handling
 */

/**
 * Session Configuration and Initialization
 * Set secure session parameters for better security
 */
if (session_status() == PHP_SESSION_NONE) {
    // Configure session settings for security (NO TIMEOUT)
    ini_set('session.cookie_lifetime', 0);    // Session cookie lifetime: 0 (no timeout)
    ini_set('session.gc_maxlifetime', 0);     // Session garbage collection: 0 (no timeout)
    ini_set('session.cookie_httponly', 1);    // Prevent XSS attacks
    ini_set('session.cookie_secure', 0);      // Set to 1 for HTTPS in production
    ini_set('session.use_strict_mode', 1);    // Prevent session fixation
    ini_set('session.cookie_path', '/');      // Set cookie path to root
    ini_set('session.cookie_domain', '');     // Allow all domains
    
    session_start();
    
    // No session timeout - sessions will persist until browser is closed or manual logout
}

/**
 * Check if user is logged in
 * Validates user session and checks for expiration
 * @return bool True if user is logged in and session is valid
 */
function isLoggedIn() {
    // Debug: Log session check
    error_log("DEBUG isLoggedIn: Session data: " . print_r($_SESSION, true));
    error_log("DEBUG isLoggedIn: Session ID: " . session_id());
    
    // Check if user_id exists in session
    if (isset($_SESSION['user_id'])) {
        error_log("DEBUG isLoggedIn: user_id found: " . $_SESSION['user_id']);
        
        // No session timeout - user stays logged in until manual logout
        error_log("DEBUG isLoggedIn: User is logged in (no timeout)");
        return true;
    }
    error_log("DEBUG isLoggedIn: No user_id in session");
    return false;
}

/**
 * Logout user and destroy session
 * Clears all session data and redirects to welcome page
 */
function logout() {
    // Start output buffering to prevent headers already sent error
    ob_start();
    
    session_start();
    
    // Clear all session variables
    session_unset();
    
    // Destroy the session
    session_destroy();
    
    // Clear session cookie
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    
    // Clear any remaining session data
    $_SESSION = array();
    
    // Force session regeneration
    session_regenerate_id(true);
    
    // Redirect to welcome page
    header('Location: welcome.php');
    exit();
}

/**
 * Check if current user is admin
 * @return bool True if user role is admin
 */
function isAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

/**
 * Require user to be logged in
 * Redirects to welcome page if user is not logged in
 */
function requireLogin() {
    if (!isLoggedIn()) {
        // Clear any existing session data
        session_unset();
        session_destroy();
        header('Location: welcome.php');  // Redirect to welcome page
        exit();
    }
}

/**
 * Require user to be admin
 * First checks if user is logged in, then checks if user is admin
 */
function requireAdmin() {
    requireLogin();  // First ensure user is logged in
    if (!isAdmin()) {
        header('Location: index.php');  // Redirect if not admin
        exit();
    }
}

/**
 * Sanitize user input to prevent XSS attacks
 * @param string $data Input data to sanitize
 * @return string Sanitized data
 */
function sanitizeInput($data) {
    $data = trim($data);              // Remove whitespace
    $data = stripslashes($data);      // Remove backslashes
    $data = htmlspecialchars($data);  // Convert special characters to HTML entities
    return $data;
}

/**
 * Hash password using PHP's secure password hashing
 * @param string $password Plain text password
 * @return string Hashed password
 */
function hashPassword($password) {
    return password_hash($password, PASSWORD_DEFAULT);
}

/**
 * Verify password against hash
 * @param string $password Plain text password
 * @param string $hash Stored password hash
 * @return bool True if password matches hash
 */
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

/**
 * Google User Authentication
 * Handles Google OAuth user authentication and session creation
 * @param array $user_data Google user data from OAuth
 * @return bool True if authentication successful
 */
function authenticateGoogleUser($user_data) {
    require_once 'config/database.php';
    
    $database = Database::getInstance();
    $conn = $database->getConnection();
    
    $email = $user_data['email'];
    $name = $user_data['name'] ?? '';
    $google_id = $user_data['id'] ?? '';
    $picture = $user_data['picture'] ?? '';
    
    try {
        // Check if user exists
        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? OR google_id = ?");
        $stmt->execute([$email, $google_id]);
        $existing_user = $stmt->fetch();
        
        if ($existing_user) {
            // Update existing user with Google info
            $stmt = $conn->prepare("UPDATE users SET google_id = ?, name = ?, profile_picture = ?, login_method = 'google', last_login = NOW() WHERE id = ?");
            $stmt->execute([$google_id, $name, $picture, $existing_user['id']]);
            
            // Set session
            $_SESSION['user_id'] = $existing_user['id'];
            $_SESSION['user_name'] = $name;
            $_SESSION['user_email'] = $email;
            $_SESSION['user_type'] = $existing_user['user_type'];
            $_SESSION['parent_user_id'] = $existing_user['parent_user_id'];
            $_SESSION['login_method'] = 'google';
            $_SESSION['logged_in'] = true;
            $_SESSION['last_activity'] = time();
            
            $database->closeConnection();
            return true;
        } else {
            // Create new user
            $stmt = $conn->prepare("INSERT INTO users (email, name, google_id, profile_picture, user_type, login_method, created_at, last_login) VALUES (?, ?, ?, ?, 'main', 'google', NOW(), NOW())");
            $stmt->execute([$email, $name, $google_id, $picture]);
            
            $new_user_id = $conn->lastInsertId();
            
            // Set session
            $_SESSION['user_id'] = $new_user_id;
            $_SESSION['user_name'] = $name;
            $_SESSION['user_email'] = $email;
            $_SESSION['user_type'] = 'main';
            $_SESSION['parent_user_id'] = null;
            $_SESSION['login_method'] = 'google';
            $_SESSION['logged_in'] = true;
            $_SESSION['last_activity'] = time();
            
            $database->closeConnection();
            return true;
        }
    } catch (Exception $e) {
        error_log("Google authentication error: " . $e->getMessage());
        $database->closeConnection();
        return false;
    }
}
?>