# Security Workflow

This document describes how login, password, role, and access security should be wired in one consistent flow, with shared path and auth bootstrap.

## 1) File Flow and Responsibilities

Use this order on every request:

1. Include [app/bootstrap.php](../app/bootstrap.php).
2. Bootstrap includes shared paths file from system and loads app config.
3. Config loads environment values from system and app .env files.
4. DB connection is created.
5. Auth and middleware functions are loaded.
6. Route calls middleware guard such as require_login, require_admin, or require_access.

Primary files:

1. [app/bootstrap.php](../app/bootstrap.php): startup sequence, sessions, includes.
2. [app/config.php](../app/config.php): DB and app config from env.
3. [app/auth.php](../app/auth.php): user lookup, password verification, role and group checks.
4. [app/middleware.php](../app/middleware.php): route protection gates.
5. [sql/schema.sql](../sql/schema.sql): users, groups, apps, and mapping tables.

## 2) Paths and Env Setup

Current load order for DB env values is:

1. system .env
2. app .env

This is already implemented in [app/config.php](../app/config.php).

Required environment values:

1. DB_HOST
2. DB_NAME
3. DB_USER
4. DB_PASS
5. DB_CHARSET

Recommended additional security env values:

1. AUTH_REQUIRE_LOGIN=1
2. AUTH_REQUIRE_HTTPS=1
3. AUTH_SESSION_SECURE_COOKIE=1
4. AUTH_SESSION_SAMESITE=Lax

## 3) Central Login On or Off Switch

Requirement: login enforcement should be controlled in shared system auth logic, not per-page.

Target behavior:

1. AUTH_REQUIRE_LOGIN=1 means normal login enforcement.
2. AUTH_REQUIRE_LOGIN=0 means no-login mode for local/dev usage.
3. Middleware should call a single shared function to decide whether to enforce auth.

Implementation pattern in shared system auth file:

    function auth_login_required(): bool {
        $value = getenv('AUTH_REQUIRE_LOGIN');
        if ($value === false || $value === '') {
            return true;
        }
        return in_array(strtolower(trim((string)$value)), ['1','true','yes','on'], true);
    }

Then in middleware:

    if (!auth_login_required()) {
        return ['id' => 0, 'username' => 'guest'];
    }

Use this pattern in the shared system auth layer so all apps get the same behavior.

## 4) Login and Password Workflow

For [public/login.php](../public/login.php):

1. Read username or email plus password from POST.
2. Load user by username or email.
3. Verify using password_verify against users.password_hash.
4. Check active status.
5. Call session_regenerate_id(true).
6. Store user id in session.
7. Redirect to dashboard.

For [public/register.php](../public/register.php):

1. Validate username, email, password length and format.
2. Hash password with password_hash.
3. Insert into users with prepared statement.
4. Optionally assign default group.
5. Log registration event.

Password standards:

1. Never store plain password.
2. Keep users.password_hash as VARCHAR(255).
3. Rehash on login when algorithm parameters change.
4. Add reset tokens with expiration for forgot-password flow.

## 5) Roles, Groups, and Admin

Supported admin/role models in auth logic:

1. Group-based admin: user in group slug admin.
2. users.is_admin column when present.
3. users.role column when present and value is admin or superadmin.

Recommended operational model:

1. Keep groups as primary source of permission.
2. Reserve direct is_admin/role for compatibility and migration.
3. Manage group membership in [public/admin/users.php](../public/admin/users.php).
4. Manage groups and app mappings in [public/admin/groups.php](../public/admin/groups.php) and [public/admin/applications.php](../public/admin/applications.php).

## 6) Access Control Workflow

Enforcement order:

1. Route requires login unless AUTH_REQUIRE_LOGIN=0.
2. Route requiring admin calls require_admin.
3. App-specific route calls require_access with app slug.
4. If app has no mappings, system is default-open.
5. If app has mappings, only mapped groups are allowed.

This logic exists in [app/middleware.php](../app/middleware.php) and [app/auth.php](../app/auth.php).

## 7) Security Checklist

1. Prepared statements for all user input queries.
2. Server-side validation for auth and admin forms.
3. CSRF tokens on every state-changing form.
4. Login throttling and lockout policy.
5. Security audit logs for login, role, and access changes.
6. Session cookie secure and httponly in production.
7. HTTPS required in production.

## 8) Minimum SQL Requirements

Core tables are defined in [sql/schema.sql](../sql/schema.sql):

1. users
2. groups
3. applications
4. user_group
5. group_application

Optional compatibility columns:

1. users.is_admin
2. users.role
3. users.status

If you use status instead of is_active, treat active as allowed and all other values as blocked.

## 9) Sample Login-Required Test Apps

Two sample pages are included for testing login-required behavior:

1. [public/test_app_one.php](../public/test_app_one.php)
2. [public/test_app_two.php](../public/test_app_two.php)

Both pages call require_login and display:

1. Whether AUTH_REQUIRE_LOGIN is ON or OFF.
2. Current session user name or guest.

Test flow:

1. Set AUTH_REQUIRE_LOGIN=1 and open Test App One while logged out. Expected: redirect to login.
2. Login once, then open Test App One and Test App Two. Expected: both pages open with same session.
3. Set AUTH_REQUIRE_LOGIN=0 and open both pages while logged out. Expected: both pages open as guest.

## 10) Cross-App Re-Login Rules

Question: after login, can user open other apps without logging in again?

Answer: yes, but only when session settings are shared.

Required alignment across apps:

1. Same cookie domain and protocol policy.
2. Same session name.
3. Same readable session storage path.
4. Same auth bootstrap behavior.

If these are not aligned, login state will be isolated per app and re-login may be required.

## 11) Reusable App Security Template

Use these templates for new apps:

1. [app/secure_page_template.php](../app/secure_page_template.php)
2. [docs/APP_SECURITY_TEMPLATE.md](APP_SECURITY_TEMPLATE.md)

They provide a standard include order, middleware usage pattern, env controls, and rollout checklist.
