auth-framework 0.4.2

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# AuthFramework Python SDK


The official Python client library for AuthFramework authentication and authorization services.

## Features


- **Async/await support** with httpx for high-performance HTTP requests
- **Type safety** with Pydantic models and comprehensive type hints
- **Automatic token management** with refresh handling
- **Error handling** with custom exceptions and retry logic
- **Context manager support** for proper resource cleanup
- **Full API coverage** for all AuthFramework endpoints

## Installation


```bash
pip install authframework
```

Or from source:

```bash
cd sdks/python
pip install -e .
```

## Quick Start


### Basic Usage


```python
import asyncio
from authframework import AuthFrameworkClient

async def main():
    # Create client instance
    client = AuthFrameworkClient('http://localhost:8080')

    try:
        # Login
        login_response = await client.login('user@example.com', 'password')
        print(f"Logged in as: {login_response.user.username}")

        # Get user profile
        profile = await client.get_profile()
        print(f"User ID: {profile.user_id}")

        # Update profile
        await client.update_profile(display_name="New Name")

    finally:
        await client.close()

# Run the async function

asyncio.run(main())
```

### Using Context Manager (Recommended)


```python
import asyncio
from authframework import AuthFrameworkClient

async def main():
    async with AuthFrameworkClient('http://localhost:8080') as client:
        # Login
        await client.login('user@example.com', 'password')

        # All API calls are automatically authenticated
        profile = await client.get_profile()
        print(f"Welcome, {profile.display_name}!")

asyncio.run(main())
```

## Authentication


### Basic Login


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    # Login with username/password
    response = await client.login('user@example.com', 'password')

    # Access tokens are automatically managed
    print(f"Access token expires in: {response.expires_in} seconds")
```

### API Key Authentication


```python
# For server-to-server authentication

client = AuthFrameworkClient(
    'http://localhost:8080',
    api_key='your-api-key'
)
```

### Token Refresh


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    await client.login('user@example.com', 'password')

    # Tokens are automatically refreshed when needed
    # You can also manually refresh:
    new_tokens = await client.refresh_token()
```

## User Management


### Profile Management


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    await client.login('user@example.com', 'password')

    # Get current user profile
    profile = await client.get_profile()
    print(f"Email: {profile.email}")
    print(f"Display Name: {profile.display_name}")
    print(f"MFA Enabled: {profile.mfa_enabled}")

    # Update profile
    await client.update_profile(
        display_name="New Display Name",
        preferences={"theme": "dark", "language": "en"}
    )

    # Change password
    await client.change_password(
        current_password="old_password",
        new_password="new_password"
    )
```

## Multi-Factor Authentication (MFA)


### Setup MFA


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    await client.login('user@example.com', 'password')

    # Setup MFA
    mfa_setup = await client.setup_mfa()
    print(f"QR Code URL: {mfa_setup.qr_code}")
    print(f"Secret Key: {mfa_setup.secret}")
    print(f"Backup Codes: {mfa_setup.backup_codes}")

    # Verify MFA setup with code from authenticator app
    await client.verify_mfa("123456")
```

### Disable MFA


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    await client.login('user@example.com', 'password')

    # Disable MFA (requires password and current MFA code)
    await client.disable_mfa(
        password="current_password",
        code="123456"
    )
```

## OAuth 2.0 Integration


### Authorization Code Flow


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    # Generate authorization URL
    auth_url = client.get_oauth_authorize_url(
        response_type="code",
        client_id="your-app-id",
        redirect_uri="https://yourapp.com/callback",
        scope="read write",
        state="random-state-value"
    )

    print(f"Redirect user to: {auth_url}")

    # After user authorizes and you receive the code:
    token_response = await client.get_oauth_token(
        grant_type="authorization_code",
        code="authorization-code",
        client_id="your-app-id",
        client_secret="your-app-secret",
        redirect_uri="https://yourapp.com/callback"
    )

    print(f"Access Token: {token_response.access_token}")
```

### Client Credentials Flow


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    # Server-to-server authentication
    token_response = await client.get_oauth_token(
        grant_type="client_credentials",
        client_id="your-service-id",
        client_secret="your-service-secret",
        scope="admin"
    )

    # Use the access token for API calls
    client._access_token = token_response.access_token
```

## Administrative Functions


### User Management (Admin Only)


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    # Login as admin
    await client.login('admin@example.com', 'admin_password')

    # List users with pagination
    users = await client.list_users(page=1, limit=10, search="john")

    # Create new user
    new_user = await client.create_user(
        username="newuser@example.com",
        password="secure_password",
        email="newuser@example.com",
        display_name="New User",
        roles=["user"]
    )

    # Get user details
    user = await client.get_user(new_user.user_id)

    # Delete user
    await client.delete_user(user.user_id)

    # Get system statistics
    stats = await client.get_system_stats()
    print(f"Total Users: {stats.total_users}")
    print(f"Active Sessions: {stats.active_sessions}")
```

## Health Monitoring


### Basic Health Check


```python
async with AuthFrameworkClient('http://localhost:8080') as client:
    # Basic health status
    health = await client.get_health()
    print(f"Status: {health.status}")
    print(f"Version: {health.version}")

    # Detailed health information
    detailed_health = await client.get_detailed_health()
    print(f"Database: {detailed_health.database}")
    print(f"Redis: {detailed_health.redis}")
    print(f"Uptime: {detailed_health.uptime}")
```

## Error Handling


### Exception Types


```python
from authframework.exceptions import (
    AuthFrameworkError,     # Base exception
    AuthenticationError,    # 401 errors
    AuthorizationError,     # 403 errors
    ValidationError,        # 400 errors
    NotFoundError,         # 404 errors
    RateLimitError,        # 429 errors
    ServerError,           # 5xx errors
    NetworkError,          # Network issues
    TimeoutError           # Request timeouts
)

async with AuthFrameworkClient('http://localhost:8080') as client:
    try:
        await client.login('invalid@email.com', 'wrong_password')
    except AuthenticationError as e:
        print(f"Login failed: {e.message}")
    except ValidationError as e:
        print(f"Invalid input: {e.message}")
        print(f"Details: {e.details}")
    except RateLimitError as e:
        print(f"Rate limited. Retry after: {e.retry_after} seconds")
    except AuthFrameworkError as e:
        print(f"API error: {e.message} (Status: {e.status_code})")
```

### Retry Logic


```python
# Client automatically retries on transient errors

client = AuthFrameworkClient(
    'http://localhost:8080',
    retries=3,  # Number of retry attempts
    timeout=30.0  # Request timeout in seconds
)
```

## Configuration


### Client Options


```python
client = AuthFrameworkClient(
    base_url='http://localhost:8080',
    timeout=30.0,           # Request timeout in seconds
    retries=3,              # Number of retry attempts
    api_key='optional-key'  # For API key authentication
)
```

### Environment Variables


```bash
# You can set default values via environment variables

export AUTHFRAMEWORK_BASE_URL=http://localhost:8080
export AUTHFRAMEWORK_TIMEOUT=30
export AUTHFRAMEWORK_RETRIES=3
export AUTHFRAMEWORK_API_KEY=your-api-key
```

```python
import os
from authframework import AuthFrameworkClient

# Use environment variables as defaults

client = AuthFrameworkClient(
    base_url=os.getenv('AUTHFRAMEWORK_BASE_URL', 'http://localhost:8080'),
    timeout=float(os.getenv('AUTHFRAMEWORK_TIMEOUT', '30.0')),
    retries=int(os.getenv('AUTHFRAMEWORK_RETRIES', '3')),
    api_key=os.getenv('AUTHFRAMEWORK_API_KEY')
)
```

## Type Safety


The SDK is fully typed with Pydantic models:

```python
from authframework.models import UserInfo, LoginResponse

async with AuthFrameworkClient('http://localhost:8080') as client:
    # Return types are properly typed
    response: LoginResponse = await client.login('user@example.com', 'password')
    profile: UserInfo = await client.get_profile()

    # Access typed fields with IDE support
    print(f"User ID: {profile.user_id}")
    print(f"Email: {profile.email}")
    print(f"Created: {profile.created_at}")
```

## Advanced Usage


### Custom HTTP Client Configuration


```python
import httpx
from authframework import AuthFrameworkClient

# Create custom HTTP client

http_client = httpx.AsyncClient(
    limits=httpx.Limits(max_connections=100),
    verify=False,  # Disable SSL verification (not recommended for production)
    proxies={'http://': 'http://proxy:8080'}
)

client = AuthFrameworkClient('http://localhost:8080')
client._client = http_client
```

### Concurrent Requests


```python
import asyncio
from authframework import AuthFrameworkClient

async def process_users():
    async with AuthFrameworkClient('http://localhost:8080') as client:
        await client.login('admin@example.com', 'password')

        # Make concurrent requests
        tasks = [
            client.get_user(f"user_{i}")
            for i in range(10)
        ]

        users = await asyncio.gather(*tasks, return_exceptions=True)

        for user in users:
            if isinstance(user, Exception):
                print(f"Error: {user}")
            else:
                print(f"User: {user.username}")
```

## Testing


### Mock Client for Testing


```python
from unittest.mock import AsyncMock
from authframework import AuthFrameworkClient

# Mock the client for testing

async def test_user_login():
    client = AuthFrameworkClient('http://localhost:8080')
    client.login = AsyncMock(return_value=MockLoginResponse())

    # Test your code that uses the client
    result = await client.login('test@example.com', 'password')
    assert result.access_token == 'mock_token'
```

## Development


### Running Tests


```bash
cd sdks/python
pytest tests/
```

### Building


```bash
cd sdks/python
python -m build
```

### Installing in Development Mode


```bash
cd sdks/python
pip install -e .[dev]
```

## API Reference


### Models


All request and response models are available in `authframework.models`:

- `LoginRequest`, `LoginResponse`
- `UserInfo`, `UserProfile`
- `MFASetupResponse`, `MFAVerifyResponse`
- `OAuthTokenResponse`
- `HealthStatus`, `DetailedHealthStatus`
- `SystemStats`

### Exceptions


All custom exceptions are available in `authframework.exceptions`:

- `AuthFrameworkError` - Base exception class
- `AuthenticationError` - Authentication failures (401)
- `AuthorizationError` - Authorization failures (403)
- `ValidationError` - Validation errors (400)
- `NotFoundError` - Resource not found (404)
- `RateLimitError` - Rate limiting (429)
- `ServerError` - Server errors (5xx)
- `NetworkError` - Network connectivity issues
- `TimeoutError` - Request timeouts

## Support


- **Documentation**: [AuthFramework Docs]https://authframework.dev/docs
- **API Reference**: [API Documentation]https://authframework.dev/api
- **Issues**: [GitHub Issues]https://github.com/authframework/authframework/issues
- **Discussions**: [GitHub Discussions]https://github.com/authframework/authframework/discussions

## License


This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.