# Token Auth Behavior

This document describes token/session behavior as implemented in this repo.

## Source of truth

- `common/functions.php`
- `config/<env>/config.php`

## Current flow

1. Login creates a raw token via `generateToken($userId, $qry)`.
2. Protected API calls validate token through `checkAuthToken($token, $qry)`.
3. `checkAuthToken()` calls `verifyToken($rawToken, $qry)`.
4. Logout path uses `logoutUser($rawToken)` (function near the end of `functions.php`).

## SESSIONEXPIRETIME behavior

- Unit: minutes
- Used by `verifyToken()` only
- Rule:
  - if `SESSIONEXPIRETIME > 0`, use it
  - else fallback to `1440` minutes

`verifyToken()` enforces an idle timeout using token file `mtime`:

- if `time() - filemtime(tokenFile) > SESSIONEXPIRETIME * 60` => token expires and file is deleted
- else token is valid and file `mtime` is refreshed using `touch()` (sliding timeout)

## Important implementation notes

- `generateToken()` currently writes token JSON with:
  - `user_id`
  - `expiry` (fixed 24h at creation time)
- Runtime validity is checked by `verifyToken()` using `mtime` sliding timeout, not the stored `expiry` field.

## Token file location

- Base path: `DOI_UPLOAD_TOKEN_PATH`
- Portal folder from `X-Portal` header (default `frontend`)

`verifyToken()` and `logoutUser()` resolve files with user-prefix subfolder:

- `DOI_UPLOAD_TOKEN_PATH/<portal>/<first-5-digits-of-token>/<token>.json`

## Current config in local

- `DOI_UPLOAD_TOKEN_PATH=/var/www/doi_public_pages_api/public/api_token/`
- `SESSIONEXPIRETIME=4320`

## Quick validation checklist

- Login returns token and creates token file.
- Protected APIs succeed with valid token.
- Inactivity beyond `SESSIONEXPIRETIME` causes auth failure.
- On expiry, token file is removed.
- Active requests keep session alive (sliding timeout via `touch()`).

