# OfficeGest Authentication System - Complete Guide

## Overview

The OfficeGest authentication system is a comprehensive dual-mode authentication mechanism that supports both web-based and API-based authentication. It provides secure session management, user validation, and extensive security features including IP restrictions, time-based access controls, and SMS authentication.

## Architecture Components

### Entry Points
- **Web HTTP**: `index.php` - Main web requests with hybrid routing
- **AJAX/API**: `AjaxServer.php` - AJAX requests with deferred initialization

### Key Classes
- **User**: User management and authentication validation
- **Session**: Session creation, validation, and management
- **AjaxServer**: AJAX endpoint handler with built-in authentication

## Web Authentication (index.php)

### Bootstrap Process

The web authentication follows a structured bootstrap process:

```php
// Line 19: Initialize core system
require(__DIR__ . '/_files/init.php');

// Lines 21-22: Execute hook-based initialization
$hooks->execute('init_1');
$hooks->execute('init_2');
```

### Session Validation Flow

#### 1. Session Existence Check
```php
// Lines 31-47: Validate existing user session
if (isset($_SESSION['user'])) {
    if ($s->verify($_SESSION['user'])) {
        if ($u = $u->loadUser($_SESSION['user'], true)) {
            $user = $u->getId();
            if ($u->getIs_active() <= 0) {
                $u->logout();
                header("Location: " . WEBSITE_URL);
            }
        } else {
            $u->logout();
            header("Location: " . WEBSITE_URL);
        }
    } else {
        $u->logout();
        header("Location: " . WEBSITE_URL);
    }
}
```

**Key Validation Steps:**
1. Check if `$_SESSION['user']` exists
2. Verify session integrity using `$s->verify()`
3. Load user data and validate active status
4. Redirect to login if any validation fails

#### 2. Route-Based Access Control
```php
// Lines 94-103: Enforce authentication for protected routes
} elseif (
    !isset($user) && $modrewrite[0] != "login" &&
    !str_starts_with($modrewrite[0] ?? '', "dsa") &&
    !str_starts_with($modrewrite[0] ?? '', "cb") && $modrewrite[0] != "errorlic" &&
    $modrewrite[0] != "developer" && !in_array($modrewrite[0], PANELS_LIST)
) {
    if (isset($_REQUEST['rwr']) && !str_contains($_REQUEST['rwr'] ?? '', 'assets')) {
        $_SESSION['rwr'] = $_REQUEST['rwr'];
    }
    header("Location: " . WEBSITE_URL . "/login");
```

**Protected Routes Logic:**
- Redirect unauthenticated users to login
- Store original request URL in `$_SESSION['rwr']` for post-login redirect
- Allow access to public routes: login, dsa, cb, errorlic, developer, panels

### Login Process

#### 1. Login Form Processing
```php
// Lines 165-246: Handle login form submission
if (!isset($user) && isset($_POST['login'])) {
    $hooks->execute('login_post', $_POST);
    if (!isset($_POST['user']) || !isset($_POST['password'])) {
        $f_error = $l->r('login_post_error_nouserpass');
    } else {
        if ($_POST['panel']) {
            $user_id = $u->checkUserPin($_POST['user'], $_POST['password']);
        } else {
            $tryuser = strtolower($_POST['user'] ?? '');
            $trypass = trim($_POST['password'] ?? '');
            $user_id = $u->checkUserPassword($tryuser, $trypass);
        }
```

**Authentication Methods:**
- **Panel Authentication**: Uses `checkUserPin()` for touch panel access
- **Standard Authentication**: Uses `checkUserPassword()` for regular web access

#### 2. Advanced Security Validations
```php
// Lines 182-190: Session limit and IP validation
} elseif ($s->qtd_slots() >= $a->maxusers() && !$_POST['panel']) {
    $canmanagesessions = 'dsa' .  base64_encode('listsessions:' . $user_id . ':' . Carbon::now()->timestamp ?? '');
    $f_error = $l->r('login_post_error_inactiveuser');
} elseif ($u->IsActive()) {
    if (!$u->validateIP()) {
        $f_error = $l->r('login_post_error_novalidip');
    } elseif (!$u->validateTimeable()) {
        $f_error = $l->r('login_post_error_novalidtimeable');
```

**Security Features:**
- **Session Limits**: Prevent concurrent sessions exceeding system limits
- **IP Validation**: Restrict access based on allowed IP ranges
- **Time-Based Access**: Enforce time-based access restrictions
- **User Status**: Validate user active status

#### 3. Successful Login Actions
```php
// Lines 191-236: Post-authentication setup
$hooks->execute('login_ok', $u);
$_SESSION['user'] = $user_id;
$_SESSION['just_login'] = 1;
if (!empty($_POST['panel'])) {
    $_SESSION['panel'] = $_POST['panel'];
}
$s->create($u);
```

**Post-Login Process:**
1. Execute login success hooks
2. Set session variables
3. Create session record
4. Update last seen information
5. Handle password change requirements
6. Set recent technicians cookie

### Password Management

#### Force Password Change Logic
```php
// Lines 198-210: Password lifetime validation
$passwordlifetime = $u->getPasswordlifetime();
if (!empty($passwordlifetime)) {
    $datetochange = new Datetime($u->getDatepasswdalter());
    $datetochange->add(new DateInterval("P" . $u->getPasswordlifetime() . "D"));
    if (Carbon::now()->format("Y-m-d") > $datetochange->format("Y-m-d")) {
        $_SESSION['force_change_pass'] = 1;
    }
}
```

**Password Change Triggers:**
- First-time login (empty `lastseen_date`)
- Password lifetime expiration
- Administrative force flag

## API/AJAX Authentication (AjaxServer.php)

### Initialization and Security

#### 1. Deferred Bootstrap
```php
// Lines 12-13: Deferred initialization for performance
define('INDEXTOP', 1);
define("DEFERRED_INIT", true);
```

**Benefits:**
- Faster AJAX response times
- Resource optimization
- Selective component loading

#### 2. Action-Based Routing
```php
// Lines 16-26: Dynamic action determination
if (isset($_REQUEST['action']) && !empty(trim($_REQUEST['action'] ?? ''))) {
    $action = trim($_REQUEST['action'] ?? '');
} else {
    $url = Funcs::explode_verify_array('/', urldecode($_SERVER['REQUEST_URI']));
    if ($url[1] == "ajaxserver" && !empty($url[2])) {
        $action =  strtok($url[2], '?');
        unset($url);
    } else {
        AjaxServer::respond(false, "Params missing.");
    }
}
```

### Session Validation System

#### 1. Bypass List for Public Endpoints
```php
// Lines 35-43: Actions that bypass authentication
private $ignValidate = [
    'login',
    'login_panel',
    'smsAuthLogin',
    'newsslides',
    'DevNull',
    'ping',
    'oauthconnector'
];
```

#### 2. Session Validation Logic

```php
// Lines 134-154: Advanced session validation
private function validateSession()
{
    global $u;
    if (isset($_SESSION['isadmin']) && $_SESSION['isadmin'] == md5(Authentication-System-Guide.mdsession_id() . $_SERVER['REMOTE_ADDR'])) {
        if (!$u->isLogged()) {
            $u->loadUser($_SESSION['user'], true);
        }
        return true;
    }
    $s = new Session(new User());
    if (isset($_SESSION['user'])) {
        if ($s->verify($_SESSION['user'])) {
            if (!$u->isLogged()) {
                $u->loadUser($_SESSION['user'], true);
            }
            return true;
        }
        return false;
    }
    return false;
}
```

**Validation Hierarchy:**
1. **Admin Session**: Special admin session validation
2. **Regular Session**: Standard user session verification
3. **User Loading**: Lazy loading of user data if not already loaded

### AJAX Login Methods

#### 1. Standard Login (`login()`)
```php
// Lines 163-255: Comprehensive AJAX login
public function login()
{
    global $a, $u, $s, $hooks;
    $s->deleteOldSessions();
    $hooks->execute('login_post', $_POST);
    $_SESSION['logintrys'] = !isset($_SESSION['logintrys']) ? 1 : $_SESSION['logintrys'] + 1;
```

**Features:**
- **Login Attempt Tracking**: Progressive delays for failed attempts
- **Encoded Credentials**: Support for base64-encoded credential pairs
- **Session Cleanup**: Automatic cleanup of old sessions
- **Hook Integration**: Extensible through hook system

#### 2. Panel Login (`login_panel()`)
```php
// Lines 257-284: Simplified panel authentication
public function login_panel()
{
    global $u, $s;
    $s->deleteOldSessions();
    $_SESSION['logintrys_panel'] = !isset($_SESSION['logintrys_panel']) ? 1 : $_SESSION['logintrys_panel'] + 1;
```

**Differences from Standard Login:**
- Simplified validation process
- Separate attempt tracking
- Panel-specific session creation
- Reduced security checks (appropriate for internal panels)

#### 3. SMS Authentication (`smsAuthLogin()`)
```php
// Lines 285-340: Two-factor SMS authentication
public function smsAuthLogin()
{
    global $a, $u, $s, $hooks;
    $s->deleteOldSessions();
    if (!isset($_POST['id']) || !isset($_POST['pin']) || empty($_POST['id']) || empty($_POST['pin'])) {
        static::directrespond(['success' => false]);
    }
```

**SMS Auth Flow:**
1. Validate SMS ID and PIN
2. Verify against database records
3. Check expiration time
4. Set authentication cookie
5. Complete login process

## Security Features

### 1. Brute Force Protection

**Login Attempt Delays:**
```php
// Progressive delays for failed attempts
sleep($_SESSION['logintrys'] * 3);
```

**Features:**
- Exponential backoff for failed attempts
- Separate tracking for web and panel logins
- Session-based attempt counting

### 2. Session Security

**Session Limits:**
- Maximum concurrent user sessions
- Automatic cleanup of expired sessions
- Single session enforcement option

**Session Verification:**
```php
$s->verify($_SESSION['user'])
```
- Cryptographic session validation
- IP-based session binding
- Timestamp-based expiration

### 3. IP and Time Restrictions

**IP Validation:**
```php
if (!$u->validateIP()) {
    $f_error = $l->r('login_post_error_novalidip');
}
```

**Time-Based Access:**
```php
if (!$u->validateTimeable()) {
    $f_error = $l->r('login_post_error_novalidtimeable');
}
```

### 4. SMS Two-Factor Authentication

**Configuration Options:**
- SMS authentication requirement setting
- Cookie-based trusted device remembering
- Configurable cookie duration
- PIN expiration management

## Error Handling

### Web Authentication Errors
- **-1**: Missing credentials
- **-2**: Inactive user
- **-3**: Invalid credentials
- **-4**: Session limit exceeded
- **-5**: Invalid IP address
- **-6**: Time restriction violation

### AJAX Response Format
```php
// Standard response format
['success' => boolean, 'code' => integer, 'params' => array]
```

## Best Practices for Implementation

### 1. Security Considerations
- Always validate session before processing requests
- Implement proper logout procedures
- Use HTTPS in production environments
- Regularly clean up expired sessions
- Monitor failed login attempts

### 2. Performance Optimization
- Use deferred initialization for AJAX requests
- Implement proper caching strategies
- Minimize database queries during authentication
- Use session verification efficiently

### 3. Extensibility
- Leverage hook system for custom authentication logic
- Implement custom validation methods
- Use modular approach for different authentication types
- Support multiple authentication providers

## Configuration Parameters

### Key Settings
- `maxusers()`: Maximum concurrent sessions
- `LoginSMSAuth`: SMS authentication requirement
- `LoginSMSCookieDuration`: Trusted device cookie duration
- `database_country`: Localization settings
- IP restriction configurations
- Time-based access rules

## Troubleshooting Common Issues

### Session Issues
1. **Session not persisting**: Check session configuration and cookie settings
2. **Frequent logouts**: Verify session timeout settings and server configuration
3. **IP validation failures**: Review IP whitelist configuration

### Authentication Failures
1. **Login attempts blocked**: Check brute force protection settings
2. **SMS authentication not working**: Verify SMS service configuration
3. **Time restrictions**: Review user time access settings

This comprehensive authentication system provides enterprise-level security while maintaining flexibility and performance for the OfficeGest ERP platform.
