docs(auth): document 7-day session authentication with constants

- Add comprehensive authentication overview.md explaining:
  - 7-day session duration for JWT and refresh tokens
  - Constants-based implementation (no hardcoded values)
  - Complete authentication flow (register/login/refresh/logout)
  - Session expiration handling (HTML redirect vs JSON error)
  - Security features (HTTP-only cookies, token rotation)
  - Token storage recommendations
- Update login.md with 7-day expires_in field and cookie MaxAge
- Update register.md with 7-day session duration details
- Update refresh_token.md with expires_in: 604800

Documentation provides complete reference for authentication
endpoints with examples and security considerations.
This commit is contained in:
2026-02-16 16:50:43 -05:00
parent 586f293e09
commit 8a6ea39ed2
4 changed files with 207 additions and 11 deletions
+15 -3
View File
@@ -4,20 +4,20 @@ Authenticate with email and password.
**Endpoint**: `POST /api/auth/login` **Endpoint**: `POST /api/auth/login`
**Auth**: Not required **Auth**: Not required
**Content-Type**: `application/json` **Content-Type**: `application/json` or `application/x-www-form-urlencoded`
## Request Body ## Request Body
| Field | Type | Required | Description | | Field | Type | Required | Description |
|--------|------|-----------|-------------| |--------|------|-----------|-------------|
| email | string | Yes | User's email address | | login | string | Yes | User's email address or username |
| password | string | Yes | User's password | | password | string | Yes | User's password |
### Example Request ### Example Request
```json ```json
{ {
"email": "user@example.com", "login": "user@example.com",
"password": "SecureP@ss123!" "password": "SecureP@ss123!"
} }
``` ```
@@ -28,18 +28,30 @@ Authenticate with email and password.
{ {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "d4f5g6h7...", "refresh_token": "d4f5g6h7...",
"token_type": "Bearer",
"expires_in": 604800,
"user": { "user": {
"id": "uuid-here", "id": "uuid-here",
"email": "user@example.com", "email": "user@example.com",
"username": "john", "username": "john",
"first_name": "John",
"last_name": "Doe",
"role": "user" "role": "user"
} }
} }
``` ```
**Set-Cookie Header**:
```
Set-Cookie: token=eyJhbG...; Max-Age=604800; Path=/; HttpOnly
```
**Session Duration**: 7 days (604800 seconds)
## Error Responses ## Error Responses
| Code | Description | | Code | Description |
|------|-------------| |------|-------------|
| 401 | Invalid email or password | | 401 | Invalid email or password |
| 400 | Missing required fields | | 400 | Missing required fields |
| 429 | Too many login attempts |
@@ -0,0 +1,166 @@
# Authentication Overview
Bookhoard uses **JWT-based authentication** with **7-day persistent sessions** and **refresh tokens** for security.
## Session Duration
All JWT tokens and refresh tokens are valid for **7 days** from creation. This provides a Google-like persistent session experience.
- **JWT Access Token**: Valid for 7 days
- **Refresh Token**: Valid for 7 days
- **HTTP-only Cookie**: Max-Age of 7 days (604800 seconds)
### Implementation Details
Session durations are defined using **constants** to maintain a single source of truth:
```go
// internal/handlers/auth.go
const (
SessionDuration = 7 * 24 * time.Hour // 7 days
)
// SessionDurationSec is computed from SessionDuration
var SessionDurationSec = int(SessionDuration.Seconds()) // 604800 seconds
```
**No hardcoded values** exist in the codebase. All timeout values use these constants:
- JWT token `exp` claim: `time.Now().Add(SessionDuration).Unix()`
- Cookie `MaxAge`: `SessionDurationSec`
- API response `expires_in`: `SessionDurationSec`
## Authentication Flow
### 1. Registration/Login
When a user registers or logs in:
1. Server generates a JWT access token (valid for 7 days)
2. Server creates a refresh token in the database (valid for 7 days)
3. Server sets an HTTP-only cookie with the JWT token
4. Server returns JSON response with both tokens and user profile
**Request**:
```json
POST /api/auth/login
{
"login": "user@example.com",
"password": "SecureP@ss123!"
}
```
**Response**:
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "uuid-refresh-token",
"token_type": "Bearer",
"expires_in": 604800,
"user": {
"id": "uuid",
"email": "user@example.com",
"username": "john",
"role": "user"
}
}
```
**Set-Cookie Header**:
```
Set-Cookie: token=eyJhbG...; Max-Age=604800; Path=/; HttpOnly
```
### 2. Making Authenticated Requests
Include the JWT token in the `Authorization` header:
```bash
curl -H "Authorization: Bearer <token>" \
https://api.example.com/api/libraries
```
The server also checks for the token in the HTTP-only cookie automatically.
### 3. Token Refresh
When your access token expires (after 7 days), use the refresh token to get a new one:
```json
POST /api/auth/refresh
{
"refresh_token": "uuid-refresh-token"
}
```
**Response**:
```json
{
"access_token": "new-jwt-token",
"token_type": "Bearer",
"expires_in": 604800
}
```
### 4. Logout
Revokes the refresh token on the server:
```json
POST /api/auth/logout
{
"refresh_token": "uuid-refresh-token"
}
```
## Session Expiration Handling
### Web Browser Requests
When a user's session expires during page navigation:
1. Server redirects to `/login?session=expired`
2. Login page displays: "Your session has expired. Please log in again to continue."
3. User re-authenticates and is redirected to their intended destination
### API Requests
When an API call receives a 401 Unauthorized response:
```json
{
"error": "session_expired",
"message": "Your session has expired. Please log in again."
}
```
The frontend toast.js interceptor:
1. Clears invalid tokens from localStorage
2. Shows an error toast notification
3. Allows user to re-authenticate
## Security Features
- **HTTP-only Cookies**: Prevents XSS attacks on token cookies
- **Refresh Token Rotation**: New refresh tokens issued on each refresh
- **7-Day Expiration**: Reasonable balance between security and convenience
- **Constants-Based Configuration**: Single source of truth for session duration
## Token Storage Recommendations
### Browser Applications
- **Backend**: Automatically manages HTTP-only cookie
- **Frontend**: Store tokens in localStorage for API calls
### Mobile Applications
- Store access token in secure storage (Keychain/Keystore)
- Store refresh token in secure storage
- Handle 401 responses by prompting user to re-authenticate
## Constants Reference
All session durations use constants defined in:
- `internal/handlers/auth.go` - SessionDuration, SessionDurationSec
- `internal/handlers/refresh_token.go` - SessionDurationSec (mirrored)
**Total value**: 604800 seconds (7 days × 24 hours × 60 minutes × 60 seconds)
@@ -1,6 +1,6 @@
# Refresh Token # Refresh Token
Obtain a new JWT token using a refresh token. Obtain a new JWT access token using a refresh token.
**Endpoint**: `POST /api/auth/refresh` **Endpoint**: `POST /api/auth/refresh`
**Auth**: Not required (uses refresh token) **Auth**: Not required (uses refresh token)
@@ -10,7 +10,7 @@ Obtain a new JWT token using a refresh token.
| Field | Type | Required | Description | | Field | Type | Required | Description |
|--------|------|-----------|-------------| |--------|------|-----------|-------------|
| refresh_token | string | Yes | Valid refresh token | | refresh_token | string | Yes | Valid refresh token (UUID) |
### Example Request ### Example Request
@@ -24,14 +24,19 @@ Obtain a new JWT token using a refresh token.
```json ```json
{ {
"token": "new-jwt-token", "access_token": "new-jwt-token",
"refresh_token": "new-refresh-token" "token_type": "Bearer",
"expires_in": 604800
} }
``` ```
**Session Duration**: 7 days (604800 seconds)
The new access token is valid for 7 days from the time of refresh.
## Error Responses ## Error Responses
| Code | Description | | Code | Description |
|------|-------------| |------|-------------|
| 401 | Invalid or expired refresh token | | 401 | Invalid or expired refresh token |
| 400 | Missing refresh token | | 400 | Missing refresh token or invalid format |
+16 -3
View File
@@ -4,15 +4,15 @@ Create a new user account.
**Endpoint**: `POST /api/auth/register` **Endpoint**: `POST /api/auth/register`
**Auth**: Not required **Auth**: Not required
**Content-Type**: `application/json` **Content-Type**: `application/json` or `application/x-www-form-urlencoded`
## Request Body ## Request Body
| Field | Type | Required | Description | | Field | Type | Required | Description |
|--------|------|-----------|-------------| |--------|------|-----------|-------------|
| email | string | Yes | User's email address | | email | string | Yes | User's email address |
| username | string | Yes | Desired username | | username | string | Yes | Desired username (3-50 chars) |
| password | string | Yes | Password (min 8 chars) | | password | string | Yes | Password (min 8 chars, must meet complexity requirements) |
| first_name | string | No | User's first name | | first_name | string | No | User's first name |
| last_name | string | No | User's last name | | last_name | string | No | User's last name |
@@ -34,10 +34,14 @@ Create a new user account.
{ {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "d4f5g6h7...", "refresh_token": "d4f5g6h7...",
"token_type": "Bearer",
"expires_in": 604800,
"user": { "user": {
"id": "uuid-here", "id": "uuid-here",
"email": "user@example.com", "email": "user@example.com",
"username": "john", "username": "john",
"first_name": "John",
"last_name": "Doe",
"role": "user", "role": "user",
"theme": "tokyo-night", "theme": "tokyo-night",
"created_at": "2026-01-31T10:00:00Z" "created_at": "2026-01-31T10:00:00Z"
@@ -45,6 +49,15 @@ Create a new user account.
} }
``` ```
**Set-Cookie Header**:
```
Set-Cookie: token=eyJhbG...; Max-Age=604800; Path=/; HttpOnly
```
**Session Duration**: 7 days (604800 seconds)
**First User**: The first user registered automatically becomes an admin.
## Error Responses ## Error Responses
| Code | Description | | Code | Description |