# Authentication System Documentation

## Overview

The Aumentum Document System now includes a complete JWT-based authentication system integrated with the existing Alfresco authority framework.

## Components

### 1. Authentication Service (`auth_service.py`)
- JWT token generation and verification
- User authentication against Alfresco authority database
- Role and group management
- Password hashing with bcrypt

### 2. API Endpoints (`aumentum_api.py`)
- **POST /auth/login** - User login, returns JWT token
- **GET /auth/me** - Get current user information
- **POST /auth/logout** - Logout (client-side token removal)
- **GET /auth/users** - Get all users (admin only)
- **GET /auth/roles** - Get all roles (admin only)
- **GET /auth/groups** - Get all groups (admin only)

### 3. Frontend (`web_frontend/login.html`)
- Modern, responsive login page
- Automatic token management
- Redirect to main app after successful login

## Installation

### Required Dependencies

Install the new dependencies:

```bash
./venv/bin/pip install python-jose[cryptography] passlib[bcrypt] python-multipart
```

Or install from updated requirements.txt:

```bash
./venv/bin/pip install -r requirements.txt
```

## User Database Structure

### Users Table: `alf_authority`
- **Total Users:** ~160 active users
- **System Users:** admin, guest
- **Named Roles:** Surveyor General, Deeds Registrar, Records Clerk, etc.

### Example Users:
- `admin` - Administrator
- `uezekiel` - Regular user
- `erangnaan` - Regular user

### Roles:
- `ROLE_ADMINISTRATOR` - System admin role
- `ROLE_OWNER` - Owner permissions
- Named functional roles (Surveyor General, Deeds Registrar, etc.)

### Groups:
- `GROUP_EVERYONE` - All users
- `GROUP_LRS` - Land Registry System
- `GROUP_Survey Department`
- `GROUP_Scanning Operator`
- And 20+ more groups

## Usage

### 1. Start the API Server

```bash
./venv/bin/python3 aumentum_api.py
```

### 2. Access the Login Page

Open your browser to:
```
http://localhost:8001/login.html
```

or (from web_frontend directory):
```
file:///path/to/web_frontend/login.html
```

### 3. Login

Use any valid Alfresco username:
- **Username:** Any user from `alf_authority` table (e.g., `admin`, `uezekiel`)
- **Password:** Currently allowing any password (see note below)

### 4. API Authentication

Once logged in, the frontend automatically includes the JWT token in requests:

```javascript
const response = await fetch(`${API_BASE_URL}/documents/...`, {
    headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
    }
});
```

## Security Notes

### ⚠️ Password Authentication

**Current Implementation:**
- The system currently allows login for any existing user without strict password verification
- This is because Alfresco's password storage mechanism needs further investigation

**For Production:**
1. Implement proper password verification in `auth_service.py`
2. The password hashing infrastructure is already in place using bcrypt
3. Update the `authenticate_user()` method to verify passwords properly

### JWT Token Configuration

**Default Settings:**
- Token expiration: 8 hours (480 minutes)
- Algorithm: HS256
- Secret key: Auto-generated on startup (change for production)

**For Production:**
- Set a fixed `SECRET_KEY` in environment variables
- Consider shorter token expiration times
- Implement token refresh mechanism

## API Authorization

### Public Endpoints
- POST /auth/login
- GET / (root)

### Authenticated Endpoints
Use `current_user: UserInfo = Depends(require_auth)` parameter:

```python
@app.get("/documents/my-documents")
async def get_my_documents(current_user: UserInfo = Depends(require_auth)):
    # Only accessible with valid JWT token
    return {"user": current_user.username}
```

### Admin-Only Endpoints
Use `current_user: UserInfo = Depends(require_admin)` parameter:

```python
@app.get("/admin/users")
async def admin_panel(current_user: UserInfo = Depends(require_admin)):
    # Only accessible by admins
    return {"admin": current_user.username}
```

## User Information Structure

```python
class UserInfo(BaseModel):
    id: int                    # User ID from alf_authority
    username: str              # Username
    roles: List[str]           # List of roles (e.g., ['ROLE_ADMINISTRATOR'])
    groups: List[str]          # List of groups (e.g., ['GROUP_EVERYONE'])
    is_admin: bool             # True if user is admin
```

## Testing

### Test Login Endpoint

```bash
curl -X POST "http://localhost:8001/auth/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin&password=anypassword"
```

Response:
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "user": {
    "id": 3,
    "username": "admin",
    "roles": ["ROLE_ADMINISTRATOR"],
    "groups": ["GROUP_EVERYONE"],
    "is_admin": true
  }
}
```

### Test Protected Endpoint

```bash
TOKEN="your_jwt_token_here"

curl -X GET "http://localhost:8001/auth/me" \
  -H "Authorization: Bearer $TOKEN"
```

## Frontend Integration

### Check Authentication

```javascript
// Check if user is logged in
const token = localStorage.getItem('access_token');
if (!token) {
    window.location.href = 'login.html';
}
```

### Make Authenticated Requests

```javascript
const response = await fetch(`${API_BASE_URL}/documents/...`, {
    headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
    }
});
```

### Logout

```javascript
async function logout() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('user_info');
    window.location.href = 'login.html';
}
```

## Troubleshooting

### "Not authenticated" error
- Check if token is present in localStorage
- Token may have expired (8 hour default)
- Re-login to get a new token

### "Admin access required" error
- User doesn't have admin privileges
- Check user roles in database
- Admin users have `ROLE_ADMINISTRATOR` or username='admin'

### Database connection errors
- Ensure FreeTDS driver is configured
- Check database credentials in `DEFAULT_DB_CONFIG`
- Verify database is accessible

## Future Enhancements

1. **Password Management**
   - Implement proper password hashing/verification
   - Add password reset functionality
   - Add password change endpoint

2. **Token Refresh**
   - Implement refresh tokens
   - Auto-refresh before expiration

3. **Session Management**
   - Track active sessions
   - Force logout capability
   - Session timeout handling

4. **Audit Logging**
   - Log authentication attempts
   - Track user actions
   - Security event monitoring

5. **Two-Factor Authentication**
   - Optional 2FA support
   - SMS or authenticator app integration

## API Documentation

Once the server is running, visit:
- **Swagger UI:** http://localhost:8001/docs
- **ReDoc:** http://localhost:8001/redoc

These provide interactive API documentation with authentication support.

