# Example: Before/After README Section Update

This example shows how to properly update README documentation when adding new features or making changes.

## Scenario: Adding JWT Authentication to a Web Application

A developer adds JWT-based authentication to an existing web application. Here's how the README should be updated.

---

## ❌ BEFORE: Incomplete README (Missing Feature Documentation)

```markdown
# Web Application

A simple web application built with Flask.

## Installation

```bash
pip install -r requirements.txt
```

## Running the Application

```bash
python app.py
```

Visit http://localhost:5000

## Configuration

Create a `.env` file:

```bash
DEBUG=True
```

## Features

- User registration
- Dashboard view
- Data export

## License

MIT
```

**Problems:**
- ❌ No mention of authentication (new feature)
- ❌ No JWT configuration documented
- ❌ No API endpoint documentation
- ❌ No security configuration explained
- ❌ Incomplete feature list

---

## ✅ AFTER: Complete README (With New Feature Documentation)

```markdown
# Web Application

A simple web application built with Flask with JWT-based authentication.

## Features

- 🔐 **JWT Authentication** - Secure token-based authentication
- 👤 User registration and profile management
- 📊 Dashboard view with user-specific data
- 📥 Data export functionality
- 🔒 Role-based access control (User, Admin)

## Installation

### Prerequisites

- Python 3.9 or higher
- pip
- Virtual environment (recommended)

### Setup

1. Clone the repository:
   ```bash
   git clone https://github.com/example/web-app.git
   cd web-app
   ```

2. Create and activate virtual environment:
   ```bash
   python -m venv .venv
   source .venv/bin/activate  # On Windows: .venv\Scripts\activate
   ```

3. Install dependencies:
   ```bash
   pip install -r requirements.txt
   ```

4. Configure environment variables (see [Configuration](#configuration))

5. Initialize the database:
   ```bash
   python -m flask db upgrade
   ```

## Configuration

Create a `.env` file in the project root:

```bash
# Application
DEBUG=True                              # Enable debug mode (disable in production!)
SECRET_KEY=your-secret-key-here        # Generate with: python -c "import secrets; print(secrets.token_hex(32))"
DATABASE_URL=sqlite:///app.db          # Database connection string

# JWT Configuration
JWT_SECRET_KEY=your-jwt-secret-key     # Generate with: python -c "import secrets; print(secrets.token_hex(32))"
JWT_ACCESS_TOKEN_EXPIRES=3600          # Access token lifetime in seconds (1 hour)
JWT_REFRESH_TOKEN_EXPIRES=604800       # Refresh token lifetime in seconds (7 days)

# Security
BCRYPT_LOG_ROUNDS=12                   # Password hashing rounds (higher = more secure but slower)
CORS_ORIGINS=http://localhost:3000     # Allowed CORS origins (comma-separated)

# Rate Limiting
RATELIMIT_ENABLED=True                 # Enable rate limiting
RATELIMIT_DEFAULT=100/hour            # Default rate limit
```

### Environment-Specific Configuration

**Development:**
```bash
DEBUG=True
JWT_ACCESS_TOKEN_EXPIRES=3600
```

**Production:**
```bash
DEBUG=False
JWT_ACCESS_TOKEN_EXPIRES=900           # Shorter token lifetime for security
BCRYPT_LOG_ROUNDS=14                   # Higher security
```

⚠️ **Security Note:** Never commit `.env` files to version control. Use `.env.example` as a template.

## Running the Application

### Development Server

```bash
python app.py
```

The application will start at http://localhost:5000

### Production Server

Use a production WSGI server like Gunicorn:

```bash
gunicorn -w 4 -b 0.0.0.0:8000 app:app
```

Or with Docker:

```bash
docker build -t web-app .
docker run -p 8000:8000 --env-file .env web-app
```

## API Documentation

### Authentication Endpoints

#### POST /api/auth/register

Register a new user account.

**Request:**
```json
{
  "email": "user@example.com",
  "password": "securePassword123!",
  "name": "John Doe"
}
```

**Response (201 Created):**
```json
{
  "message": "User created successfully",
  "user": {
    "id": 1,
    "email": "user@example.com",
    "name": "John Doe"
  }
}
```

#### POST /api/auth/login

Authenticate and receive JWT tokens.

**Request:**
```json
{
  "email": "user@example.com",
  "password": "securePassword123!"
}
```

**Response (200 OK):**
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": 1,
    "email": "user@example.com",
    "name": "John Doe",
    "role": "user"
  }
}
```

#### POST /api/auth/refresh

Refresh access token using refresh token.

**Request:**
```json
{
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

**Response (200 OK):**
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

### Protected Endpoints

All protected endpoints require an Authorization header:

```http
Authorization: Bearer <access_token>
```

#### GET /api/dashboard

Get user dashboard data.

**Response (200 OK):**
```json
{
  "user": {
    "id": 1,
    "name": "John Doe",
    "email": "user@example.com"
  },
  "stats": {
    "total_exports": 15,
    "last_login": "2026-01-07T10:30:00Z"
  }
}
```

### Error Responses

All endpoints return errors in this format:

```json
{
  "error": "error_code",
  "message": "Human-readable error message"
}
```

Common error codes:
- `invalid_credentials` (401): Email or password incorrect
- `token_expired` (401): JWT token has expired
- `unauthorized` (401): Missing or invalid token
- `forbidden` (403): Insufficient permissions
- `validation_error` (400): Request validation failed

## Usage Examples

### Python Client

```python
import requests

# Register a new user
response = requests.post(
    "http://localhost:5000/api/auth/register",
    json={
        "email": "user@example.com",
        "password": "securePassword123!",
        "name": "John Doe"
    }
)
print(response.json())

# Login
response = requests.post(
    "http://localhost:5000/api/auth/login",
    json={
        "email": "user@example.com",
        "password": "securePassword123!"
    }
)
tokens = response.json()
access_token = tokens["access_token"]

# Access protected endpoint
response = requests.get(
    "http://localhost:5000/api/dashboard",
    headers={"Authorization": f"Bearer {access_token}"}
)
print(response.json())
```

### JavaScript Client

```javascript
// Login
const loginResponse = await fetch('http://localhost:5000/api/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'securePassword123!'
  })
});

const { access_token } = await loginResponse.json();

// Access protected endpoint
const dashboardResponse = await fetch('http://localhost:5000/api/dashboard', {
  headers: { 'Authorization': `Bearer ${access_token}` }
});

const data = await dashboardResponse.json();
console.log(data);
```

### cURL

```bash
# Register
curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"securePassword123!","name":"John Doe"}'

# Login
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"securePassword123!"}'

# Access protected endpoint (replace TOKEN with actual token)
curl http://localhost:5000/api/dashboard \
  -H "Authorization: Bearer TOKEN"
```

## Security

### Password Requirements

- Minimum 8 characters
- Must contain: uppercase letter, lowercase letter, number, special character
- Passwords are hashed using bcrypt with configurable rounds

### Token Security

- Access tokens expire after 1 hour (configurable)
- Refresh tokens expire after 7 days (configurable)
- Tokens are signed using HS256 algorithm
- Tokens include user ID and role claims

### Best Practices

- ✅ Always use HTTPS in production
- ✅ Store tokens securely (httpOnly cookies recommended for web)
- ✅ Implement token refresh before expiration
- ✅ Use strong, randomly generated JWT secrets
- ✅ Enable rate limiting to prevent brute force attacks
- ✅ Regularly rotate JWT secrets
- ❌ Never store tokens in localStorage (XSS risk)
- ❌ Never commit secrets to version control
- ❌ Never use weak or default secret keys

## Testing

Run the test suite:

```bash
# All tests
pytest

# With coverage
pytest --cov=app --cov-report=html

# Authentication tests only
pytest tests/test_auth.py
```

### Manual Testing

```bash
# Health check
curl http://localhost:5000/health

# Should return: {"status": "healthy"}
```

## Troubleshooting

### "Invalid token" errors

- **Cause:** Token expired or invalid signature
- **Solution:** Obtain a new token via `/api/auth/login` or `/api/auth/refresh`

### "401 Unauthorized" on protected endpoints

- **Cause:** Missing or malformed Authorization header
- **Solution:** Ensure header format is `Authorization: Bearer <token>`

### Database initialization fails

- **Cause:** Missing migrations or database file
- **Solution:** Run `python -m flask db upgrade`

### Rate limit exceeded

- **Cause:** Too many requests from the same IP
- **Solution:** Wait for rate limit window to reset or disable in development

## Development

### Project Structure

```
.
├── app.py                  # Application entry point
├── config.py              # Configuration management
├── requirements.txt       # Python dependencies
├── .env.example          # Environment variables template
├── src/
│   ├── auth/             # Authentication module
│   │   ├── routes.py     # Auth endpoints
│   │   ├── models.py     # User model
│   │   └── utils.py      # JWT utilities
│   ├── dashboard/        # Dashboard module
│   └── middleware/       # Custom middleware
├── tests/
│   ├── test_auth.py      # Authentication tests
│   └── test_dashboard.py # Dashboard tests
└── docs/
    └── API.md            # Full API documentation
```

### Adding New Features

1. Create feature branch: `git checkout -b feature/my-feature`
2. Implement feature with tests
3. Update relevant documentation (README, API docs, docstrings)
4. Run tests: `pytest`
5. Submit pull request

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- **Documentation:** https://docs.example.com
- **Issues:** https://github.com/example/web-app/issues
- **Email:** support@example.com

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history and updates.

---

**Note:** This is a demonstration application. For production use, implement additional security measures including:
- HTTPS enforcement
- CSRF protection
- Input sanitization
- SQL injection prevention
- Regular security audits
```

---

## What Changed: Before vs. After Comparison

| Section | Before | After | Why |
|---------|--------|-------|-----|
| **Title/Description** | Basic description | Mentions JWT authentication | Users know main feature |
| **Features** | Bullet list | Detailed list with emojis | Highlights new auth feature |
| **Installation** | Basic steps | Detailed with prerequisites | Complete setup guide |
| **Configuration** | One variable | Complete .env with comments | All JWT config documented |
| **API Docs** | ❌ Missing | ✅ Complete endpoints | Users know how to use API |
| **Usage Examples** | ❌ Missing | ✅ Python, JS, cURL | Multiple language examples |
| **Security** | ❌ Missing | ✅ Comprehensive | Critical for auth features |
| **Testing** | ❌ Missing | ✅ Test commands | Helps developers verify |
| **Troubleshooting** | ❌ Missing | ✅ Common issues | Reduces support burden |

---

## Key Principles for README Updates

### 1. **Update All Relevant Sections**

When adding a feature, update:
- ✅ Features list
- ✅ Installation steps (if dependencies added)
- ✅ Configuration (new environment variables)
- ✅ API documentation (new endpoints)
- ✅ Usage examples
- ✅ Security considerations (if applicable)
- ✅ Testing instructions

### 2. **Provide Complete Examples**

Don't just list endpoints—show:
- Request format with real examples
- Response format with real data
- Error responses
- Multiple client languages (Python, JS, cURL)

### 3. **Document Configuration**

For every new config option:
- Explain what it does
- Show valid values/ranges
- Provide sensible defaults
- Include security notes
- Show environment-specific differences

### 4. **Include Security Information**

For security-related features:
- Document security best practices
- Explain threat model
- Show secure usage patterns
- Warn about common pitfalls
- Link to detailed security docs

### 5. **Keep It Organized**

Use clear structure:
- Table of contents for long READMEs
- Consistent heading hierarchy
- Code blocks with syntax highlighting
- Tables for structured data
- Visual separators (horizontal rules)

---

## README Update Checklist

When adding a feature, ensure you've updated:

- [ ] **Title/description** - Reflects new capabilities
- [ ] **Features section** - Lists new feature prominently
- [ ] **Installation** - Any new dependencies or setup steps
- [ ] **Configuration** - All new environment variables/settings
- [ ] **Usage section** - How to use the new feature
- [ ] **API documentation** - New endpoints, requests, responses
- [ ] **Examples** - Code examples in multiple languages
- [ ] **Security** - Security implications and best practices
- [ ] **Testing** - How to test the new feature
- [ ] **Troubleshooting** - Common issues and solutions
- [ ] **Project structure** - New files/directories
- [ ] **Changelog** - Version and change notes

---

## Related Documentation

- **PR template**: `.github/PULL_REQUEST_TEMPLATE.md`
- **README prompt template**: `prompts/documentation/update-readme.md`
- **Good PR example**: `examples/documentation/good-pr-example.md`
- **Engineering standards**: `.claude/standards/ENGINEERING_STANDARDS.md#documentation-requirements`
