Session Management API Reference¶
The CRUDAdmin session management system provides secure, scalable session handling with multiple backend options and comprehensive security features including CSRF protection, session expiration, and device tracking.
Core Components¶
Session Manager¶
The main session management class that handles all session operations.
Session manager for handling secure authentication sessions in crudadmin.
This class implements a comprehensive session-based authentication system with the following features:
- Secure session creation and validation
- CSRF protection with token generation and validation
- Session expiration and automatic cleanup
- Device fingerprinting and user agent tracking
- Multi-device support with configurable session limits per user
- IP address tracking for security monitoring
- Session metadata for storing additional authentication context
- Rate limiting for login attempts with IP and username tracking
Authentication Flow: 1. When a user logs in successfully, create_session() generates a new session and CSRF token 2. Session cookies are set via set_session_cookies() - a httpOnly session_id and a non-httpOnly csrf_token 3. On subsequent requests, validate_session() confirms the session is valid and not expired 4. For state-changing operations, validate_csrf_token() provides protection against CSRF attacks 5. Sessions automatically expire after inactivity, or can be manually terminated 6. Periodic cleanup_expired_sessions() removes stale sessions
Security Features: - Sessions are stored server-side with only the ID transmitted to clients - CSRF protection through synchronized tokens - Session hijacking protection via IP and user agent tracking - Automatic session expiration after configurable timeout - Forced logout of oldest sessions when session limit is reached - Different SameSite cookie settings for development and production - Rate limiting for login attempts to prevent brute force attacks
Usage: Sessions should be validated on each authenticated request, with CSRF tokens validated for any state-changing operations. The cleanup method should be called periodically to remove expired sessions.
Source code in crudadmin/session/manager.py
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 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 |
|
__init__(session_storage=None, max_sessions_per_user=5, session_timeout_minutes=30, cleanup_interval_minutes=15, csrf_token_bytes=32, rate_limiter=None, login_max_attempts=5, login_window_minutes=15, session_backend='memory', **backend_kwargs)
¶
Initialize the session manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_storage
|
Optional[AbstractSessionStorage[SessionData]]
|
Storage backend for sessions (if None, will be created) |
None
|
max_sessions_per_user
|
int
|
Maximum number of active sessions per user |
5
|
session_timeout_minutes
|
int
|
Session timeout in minutes |
30
|
cleanup_interval_minutes
|
int
|
Interval for cleaning up expired sessions |
15
|
csrf_token_bytes
|
int
|
Number of bytes to use for CSRF tokens |
32
|
rate_limiter
|
Optional[SimpleRateLimiter]
|
Optional rate limiter implementation for login attempts |
None
|
login_max_attempts
|
int
|
Maximum failed login attempts before rate limiting |
5
|
login_window_minutes
|
int
|
Time window for tracking failed login attempts |
15
|
session_backend
|
str
|
Backend type if creating storage automatically |
'memory'
|
**backend_kwargs
|
Any
|
Additional arguments for backend creation |
{}
|
Source code in crudadmin/session/manager.py
cleanup_expired_sessions()
async
¶
Cleanup expired and inactive sessions.
This should be called periodically.
Source code in crudadmin/session/manager.py
cleanup_rate_limits()
async
¶
Clean up expired rate limit records.
This should be called periodically along with session cleanup.
Source code in crudadmin/session/manager.py
clear_session_cookies(response, path='/')
¶
Clear session cookies from the response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response
|
Response
|
The response object |
required |
path
|
str
|
Cookie path |
'/'
|
Source code in crudadmin/session/manager.py
create_session(request, user_id, metadata=None)
async
¶
Create a new session for a user and generate a CSRF token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The request object |
required |
user_id
|
int
|
The user ID |
required |
metadata
|
Optional[dict[str, Any]]
|
Optional session metadata |
None
|
Returns:
Type | Description |
---|---|
tuple[str, str]
|
Tuple of (session_id, csrf_token) |
Raises:
Type | Description |
---|---|
ValueError
|
If the request client is invalid |
Source code in crudadmin/session/manager.py
parse_user_agent(user_agent_string)
¶
Parse User-Agent string into structured information.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_agent_string
|
str
|
Raw User-Agent header |
required |
Returns:
Type | Description |
---|---|
UserAgentInfo
|
Structured UserAgentInfo |
Source code in crudadmin/session/manager.py
regenerate_csrf_token(user_id, session_id)
async
¶
Regenerate a CSRF token for an existing session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
str
|
The new CSRF token |
Source code in crudadmin/session/manager.py
set_session_cookies(response, session_id, csrf_token, max_age=None, path='/', secure=True)
¶
Set session cookies in the response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response
|
Response
|
The response object |
required |
session_id
|
str
|
The session ID |
required |
csrf_token
|
str
|
The CSRF token |
required |
max_age
|
Optional[int]
|
Cookie max age in seconds |
None
|
path
|
str
|
Cookie path |
'/'
|
secure
|
bool
|
Whether to set the Secure flag |
True
|
Source code in crudadmin/session/manager.py
terminate_session(session_id)
async
¶
Terminate a specific session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was terminated, False otherwise |
Source code in crudadmin/session/manager.py
track_login_attempt(ip_address, username, success=False)
async
¶
Track login attempts and apply rate limiting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ip_address
|
str
|
Client IP address |
required |
username
|
str
|
Username being used for login |
required |
success
|
bool
|
Whether the login attempt was successful |
False
|
Returns:
Type | Description |
---|---|
tuple[bool, Optional[int]]
|
Tuple of (is_allowed, attempts_remaining) |
If rate limiting is not configured, this will always return (True, None) but log a warning about missing rate limiting.
Source code in crudadmin/session/manager.py
validate_csrf_token(session_id, csrf_token)
async
¶
Validate a CSRF token for a session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
csrf_token
|
str
|
The CSRF token to validate |
required |
Returns:
Type | Description |
---|---|
bool
|
True if valid, False otherwise |
Source code in crudadmin/session/manager.py
validate_session(session_id, update_activity=True)
async
¶
Validate if a session is active and not timed out.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
update_activity
|
bool
|
Whether to update the last activity timestamp |
True
|
Returns:
Type | Description |
---|---|
Optional[SessionData]
|
The session data if valid, None otherwise |
Source code in crudadmin/session/manager.py
Session Storage Backends¶
Abstract Base Class¶
Bases: Generic[T]
, ABC
Abstract base class for session storage implementations.
Source code in crudadmin/session/storage.py
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 |
|
__init__(prefix='session:', expiration=1800)
¶
Initialize the session storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix
|
str
|
Prefix for all session keys |
'session:'
|
expiration
|
int
|
Default session expiration in seconds |
1800
|
Source code in crudadmin/session/storage.py
close()
abstractmethod
async
¶
create(data, session_id=None, expiration=None)
abstractmethod
async
¶
Create a new session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
Session data (must be a Pydantic model) |
required |
session_id
|
Optional[str]
|
Optional session ID. If not provided, one will be generated |
None
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
str
|
The session ID |
Source code in crudadmin/session/storage.py
delete(session_id)
abstractmethod
async
¶
Delete a session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was deleted, False if it didn't exist |
exists(session_id)
abstractmethod
async
¶
Check if a session exists.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session exists, False otherwise |
extend(session_id, expiration=None)
abstractmethod
async
¶
Extend the expiration of a session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was extended, False if it didn't exist |
Source code in crudadmin/session/storage.py
generate_session_id()
¶
get(session_id, model_class)
abstractmethod
async
¶
Get session data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
model_class
|
Type[T]
|
The Pydantic model class to decode the data into |
required |
Returns:
Type | Description |
---|---|
Optional[T]
|
The session data or None if session doesn't exist |
Source code in crudadmin/session/storage.py
get_key(session_id)
¶
Generate the full key for a session ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
str
|
The full storage key |
update(session_id, data, reset_expiration=True, expiration=None)
abstractmethod
async
¶
Update session data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
data
|
T
|
New session data |
required |
reset_expiration
|
bool
|
Whether to reset the expiration |
True
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was updated, False if it didn't exist |
Source code in crudadmin/session/storage.py
Storage Factory¶
Get the appropriate session storage backend.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backend
|
str
|
The backend to use ("redis", "memcached", "memory", "database", "hybrid") |
required |
model_type
|
Type[BaseModel]
|
The pydantic model type for type checking |
required |
**kwargs
|
Any
|
Additional arguments to pass to the backend |
{}
|
Returns:
Type | Description |
---|---|
AbstractSessionStorage[T]
|
An initialized storage backend |
Source code in crudadmin/session/storage.py
Session Storage Implementations¶
Memory Storage¶
Bases: AbstractSessionStorage[T]
In-memory implementation of session storage for testing.
Source code in crudadmin/session/backends/memory.py
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 |
|
__init__(prefix='session:', expiration=1800)
¶
Initialize the in-memory session storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix
|
str
|
Prefix for all session keys |
'session:'
|
expiration
|
int
|
Default session expiration in seconds |
1800
|
Source code in crudadmin/session/backends/memory.py
close()
async
¶
create(data, session_id=None, expiration=None)
async
¶
Create a new session in memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
Session data (must be a Pydantic model) |
required |
session_id
|
Optional[str]
|
Optional session ID. If not provided, one will be generated |
None
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
str
|
The session ID |
Source code in crudadmin/session/backends/memory.py
delete(session_id)
async
¶
Delete a session from memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was deleted, False if it didn't exist |
Source code in crudadmin/session/backends/memory.py
delete_pattern(pattern)
async
¶
Delete all keys matching a pattern.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
The pattern to match keys (e.g., "login:*") |
required |
Returns:
Type | Description |
---|---|
int
|
Number of keys deleted |
Source code in crudadmin/session/backends/memory.py
exists(session_id)
async
¶
Check if a session exists in memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session exists, False otherwise |
Source code in crudadmin/session/backends/memory.py
extend(session_id, expiration=None)
async
¶
Extend the expiration of a session in memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was extended, False if it didn't exist |
Source code in crudadmin/session/backends/memory.py
get(session_id, model_class)
async
¶
Get session data from memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
model_class
|
type[T]
|
The Pydantic model class to decode the data into |
required |
Returns:
Type | Description |
---|---|
Optional[T]
|
The session data or None if session doesn't exist |
Source code in crudadmin/session/backends/memory.py
update(session_id, data, reset_expiration=True, expiration=None)
async
¶
Update session data in memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
data
|
T
|
New session data |
required |
reset_expiration
|
bool
|
Whether to reset the expiration |
True
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was updated, False if it didn't exist |
Source code in crudadmin/session/backends/memory.py
Redis Storage¶
Bases: AbstractSessionStorage[T]
Redis implementation of session storage.
Source code in crudadmin/session/backends/redis.py
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 |
|
__init__(prefix='session:', expiration=1800, host='localhost', port=6379, db=0, password=None, pool_size=10, connect_timeout=10)
¶
Initialize the Redis session storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix
|
str
|
Prefix for all session keys |
'session:'
|
expiration
|
int
|
Default session expiration in seconds |
1800
|
host
|
str
|
Redis host |
'localhost'
|
port
|
int
|
Redis port |
6379
|
db
|
int
|
Redis database number |
0
|
password
|
Optional[str]
|
Redis password |
None
|
pool_size
|
int
|
Redis connection pool size |
10
|
connect_timeout
|
int
|
Redis connection timeout |
10
|
Source code in crudadmin/session/backends/redis.py
close()
async
¶
Close the Redis connection.
Source code in crudadmin/session/backends/redis.py
create(data, session_id=None, expiration=None)
async
¶
Create a new session in Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
Session data (must be a Pydantic model) |
required |
session_id
|
Optional[str]
|
Optional session ID. If not provided, one will be generated |
None
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
str
|
The session ID |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
delete(session_id)
async
¶
Delete a session from Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was deleted, False if it didn't exist |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
delete_pattern(pattern)
async
¶
Delete all Redis keys matching a pattern.
This method is useful for bulk cleanup operations like clearing expired rate limiting keys or other grouped data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
The pattern to match keys (e.g., "login:*") |
required |
Returns:
Type | Description |
---|---|
int
|
Number of keys deleted |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
exists(session_id)
async
¶
Check if a session exists in Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session exists, False otherwise |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
extend(session_id, expiration=None)
async
¶
Extend the expiration of a session in Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was extended, False if it didn't exist |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
get(session_id, model_class)
async
¶
Get session data from Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
model_class
|
type[T]
|
The Pydantic model class to decode the data into |
required |
Returns:
Type | Description |
---|---|
Optional[T]
|
The session data or None if session doesn't exist |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
ValueError
|
If the data cannot be parsed |
Source code in crudadmin/session/backends/redis.py
get_user_sessions(user_id)
async
¶
Get all session IDs for a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
Returns:
Type | Description |
---|---|
list[str]
|
List of session IDs for the user |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
get_user_sessions_key(user_id)
¶
Get the key for a user's sessions set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
Returns:
Type | Description |
---|---|
str
|
The Redis key for the user's sessions set |
Source code in crudadmin/session/backends/redis.py
update(session_id, data, reset_expiration=True, expiration=None)
async
¶
Update session data in Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
data
|
T
|
New session data |
required |
reset_expiration
|
bool
|
Whether to reset the expiration |
True
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was updated, False if it didn't exist |
Raises:
Type | Description |
---|---|
RedisError
|
If there is an error with Redis |
Source code in crudadmin/session/backends/redis.py
Memcached Storage¶
Bases: AbstractSessionStorage[T]
Memcached implementation of session storage.
Source code in crudadmin/session/backends/memcached.py
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 |
|
__init__(prefix='session:', expiration=1800, host='localhost', port=11211, pool_size=10)
¶
Initialize the Memcached session storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix
|
str
|
Prefix for all session keys |
'session:'
|
expiration
|
int
|
Default session expiration in seconds |
1800
|
host
|
str
|
Memcached host |
'localhost'
|
port
|
int
|
Memcached port |
11211
|
pool_size
|
int
|
Memcached connection pool size |
10
|
Source code in crudadmin/session/backends/memcached.py
close()
async
¶
create(data, session_id=None, expiration=None)
async
¶
Create a new session in Memcached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
Session data (must be a Pydantic model) |
required |
session_id
|
Optional[str]
|
Optional session ID. If not provided, one will be generated |
None
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
str
|
The session ID |
Source code in crudadmin/session/backends/memcached.py
delete(session_id)
async
¶
Delete a session from Memcached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was deleted, False if it didn't exist |
Source code in crudadmin/session/backends/memcached.py
exists(session_id)
async
¶
Check if a session exists in Memcached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session exists, False otherwise |
Source code in crudadmin/session/backends/memcached.py
extend(session_id, expiration=None)
async
¶
Extend the expiration of a session in Memcached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was extended, False if it didn't exist |
Note
Memcached doesn't allow extending expiration without updating the value. We need to get, then set the value again with a new expiration.
Source code in crudadmin/session/backends/memcached.py
get(session_id, model_class)
async
¶
Get session data from Memcached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
model_class
|
type[T]
|
The Pydantic model class to decode the data into |
required |
Returns:
Type | Description |
---|---|
Optional[T]
|
The session data or None if session doesn't exist |
Source code in crudadmin/session/backends/memcached.py
get_user_sessions(user_id)
async
¶
Get all session IDs for a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
Returns:
Type | Description |
---|---|
list[str]
|
List of session IDs for the user |
Source code in crudadmin/session/backends/memcached.py
get_user_sessions_key(user_id)
¶
Get the key for a user's sessions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
Returns:
Type | Description |
---|---|
str
|
The Memcached key for the user's sessions |
Source code in crudadmin/session/backends/memcached.py
update(session_id, data, reset_expiration=True, expiration=None)
async
¶
Update session data in Memcached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
data
|
T
|
New session data |
required |
reset_expiration
|
bool
|
Whether to reset the expiration |
True
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was updated, False if it didn't exist |
Source code in crudadmin/session/backends/memcached.py
Database Storage¶
Bases: AbstractSessionStorage[T]
Database implementation of session storage using AdminSession table.
Source code in crudadmin/session/backends/database.py
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 |
|
__init__(db_config, prefix='session:', expiration=1800)
¶
Initialize the Database session storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db_config
|
DatabaseConfig
|
Database configuration instance |
required |
prefix
|
str
|
Prefix for all session keys (kept for compatibility) |
'session:'
|
expiration
|
int
|
Default session expiration in seconds (used for cleanup) |
1800
|
Source code in crudadmin/session/backends/database.py
close()
async
¶
create(data, session_id=None, expiration=None)
async
¶
Create a new session in the database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
Session data (must be a SessionData-compatible model) |
required |
session_id
|
Optional[str]
|
Optional session ID. If not provided, one will be generated |
None
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds (stored but not enforced) |
None
|
Returns:
Type | Description |
---|---|
str
|
The session ID |
Source code in crudadmin/session/backends/database.py
delete(session_id)
async
¶
Delete a session from the database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was deleted, False if it didn't exist |
Source code in crudadmin/session/backends/database.py
exists(session_id)
async
¶
Check if a session exists in the database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session exists, False otherwise |
Source code in crudadmin/session/backends/database.py
extend(session_id, expiration=None)
async
¶
Extend the expiration of a session.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
expiration
|
Optional[int]
|
Optional custom expiration in seconds (ignored for database) |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was extended, False if it didn't exist |
Source code in crudadmin/session/backends/database.py
get(session_id, model_class)
async
¶
Get session data from the database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
model_class
|
type[T]
|
The Pydantic model class to decode the data into |
required |
Returns:
Type | Description |
---|---|
Optional[T]
|
The session data or None if session doesn't exist |
Source code in crudadmin/session/backends/database.py
get_user_sessions(user_id)
async
¶
Get all active session IDs for a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
Returns:
Type | Description |
---|---|
list[str]
|
List of session IDs for the user |
Source code in crudadmin/session/backends/database.py
update(session_id, data, reset_expiration=True, expiration=None)
async
¶
Update session data in the database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
data
|
T
|
New session data |
required |
reset_expiration
|
bool
|
Whether to reset the expiration (updates last_activity) |
True
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds (ignored for database) |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was updated, False if it didn't exist |
Source code in crudadmin/session/backends/database.py
Hybrid Storage¶
Bases: AbstractSessionStorage[T]
Hybrid storage: Redis for active sessions + Database for audit trail.
Source code in crudadmin/session/backends/hybrid.py
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 |
|
__init__(redis_storage, database_storage, prefix='session:', expiration=1800)
¶
Initialize the Hybrid session storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
redis_storage
|
AbstractSessionStorage[T]
|
Redis storage instance for active sessions |
required |
database_storage
|
AbstractSessionStorage[T]
|
Database storage instance for audit trail |
required |
prefix
|
str
|
Prefix for all session keys (inherited from redis_storage) |
'session:'
|
expiration
|
int
|
Default session expiration in seconds |
1800
|
Source code in crudadmin/session/backends/hybrid.py
close()
async
¶
create(data, session_id=None, expiration=None)
async
¶
Create a new session in both Redis and Database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
Session data (must be a Pydantic model) |
required |
session_id
|
Optional[str]
|
Optional session ID. If not provided, one will be generated |
None
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
str
|
The session ID |
Source code in crudadmin/session/backends/hybrid.py
delete(session_id)
async
¶
Delete session from Redis and mark as inactive in Database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session was deleted from Redis, False if it didn't exist |
Source code in crudadmin/session/backends/hybrid.py
exists(session_id)
async
¶
Check if a session exists in Redis (active sessions only).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the session exists in Redis, False otherwise |
Source code in crudadmin/session/backends/hybrid.py
extend(session_id, expiration=None)
async
¶
Extend the expiration of a session in Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was extended in Redis, False if it didn't exist |
Source code in crudadmin/session/backends/hybrid.py
get(session_id, model_class)
async
¶
Get session data from Redis (active sessions only).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
model_class
|
type[T]
|
The Pydantic model class to decode the data into |
required |
Returns:
Type | Description |
---|---|
Optional[T]
|
The session data or None if session doesn't exist or expired |
Source code in crudadmin/session/backends/hybrid.py
get_user_sessions(user_id)
async
¶
Get all active session IDs for a user from Redis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int
|
The user ID |
required |
Returns:
Type | Description |
---|---|
list[str]
|
List of active session IDs for the user |
Source code in crudadmin/session/backends/hybrid.py
update(session_id, data, reset_expiration=True, expiration=None)
async
¶
Update session data in both Redis and Database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session_id
|
str
|
The session ID |
required |
data
|
T
|
New session data |
required |
reset_expiration
|
bool
|
Whether to reset the expiration |
True
|
expiration
|
Optional[int]
|
Optional custom expiration in seconds |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the session was updated in Redis, False if it didn't exist |
Source code in crudadmin/session/backends/hybrid.py
Session Schemas¶
Core Session Data¶
Bases: BaseSession
Common session data for any user session.
Source code in crudadmin/session/schemas.py
CSRF Protection¶
User Agent Information¶
Bases: BaseModel
User agent information parsed from the User-Agent header.
Source code in crudadmin/session/schemas.py
Database Session Models¶
Bases: BaseSession
Schema for creating AdminSession in database.
Source code in crudadmin/session/schemas.py
Bases: BaseSession
Schema for reading AdminSession data.
Source code in crudadmin/session/schemas.py
Usage Examples¶
Basic Session Management¶
from crudadmin.session.manager import SessionManager
from crudadmin.session.storage import get_session_storage
# Create session manager with memory backend
session_manager = SessionManager(
session_backend="memory",
max_sessions_per_user=5,
session_timeout_minutes=30
)
# Create a new session
session_id, csrf_token = await session_manager.create_session(
request=request,
user_id=user.id,
metadata={"role": "admin", "permissions": ["read", "write"]}
)
# Validate session
session_data = await session_manager.validate_session(session_id)
if session_data:
print(f"Valid session for user {session_data.user_id}")
Redis Backend Configuration¶
# Configure with Redis for production
session_manager = SessionManager(
session_backend="redis",
redis_host="localhost",
redis_port=6379,
redis_db=0,
redis_password="your-redis-password",
max_sessions_per_user=10,
session_timeout_minutes=60
)
Database Backend for Audit Trail¶
from your_app.database import DatabaseConfig
# Configure with database backend for admin visibility
db_config = DatabaseConfig(...) # Your database configuration
session_manager = SessionManager(
session_backend="database",
db_config=db_config,
max_sessions_per_user=5,
session_timeout_minutes=30
)
Hybrid Backend (Best of Both Worlds)¶
# Hybrid: Redis for performance + Database for audit
session_manager = SessionManager(
session_backend="hybrid",
db_config=db_config,
redis_host="localhost",
redis_port=6379,
max_sessions_per_user=10,
session_timeout_minutes=60
)
CSRF Protection¶
# Validate CSRF token for state-changing operations
is_valid = await session_manager.validate_csrf_token(
csrf_token=request.headers.get("X-CSRF-Token"),
session_id=session_id,
user_id=current_user.id
)
if not is_valid:
raise HTTPException(status_code=403, detail="Invalid CSRF token")
Session Cleanup¶
# Cleanup expired sessions (should be called periodically)
await session_manager.cleanup_expired_sessions()
# Terminate specific session
await session_manager.terminate_session(session_id)
# Terminate all user sessions
await session_manager.terminate_user_sessions(user_id)
Backend Comparison¶
Backend | Performance | Scalability | Persistence | Admin Visibility | Use Case |
---|---|---|---|---|---|
Memory | Excellent | Single node | No | No | Development, testing |
Redis | Excellent | Horizontal | Yes* | No | Production, high traffic |
Memcached | Excellent | Horizontal | No | No | High performance caching |
Database | Good | Vertical | Yes | Yes | Audit requirements |
Hybrid | Excellent | Horizontal | Yes | Yes | Best of all worlds |
*Redis persistence depends on configuration
Security Features¶
Session Security¶
# Session manager provides multiple security layers
session_manager = SessionManager(
# Limit concurrent sessions per user
max_sessions_per_user=5,
# Automatic session expiration
session_timeout_minutes=30,
# CSRF protection
csrf_token_bytes=32,
# Login rate limiting
login_max_attempts=5,
login_window_minutes=15
)
Device Tracking¶
Sessions automatically track device information:
# Device info is automatically parsed and stored
session_data = await session_manager.validate_session(session_id)
device_info = session_data.device_info
print(f"Browser: {device_info['browser']}")
print(f"OS: {device_info['os']}")
print(f"Mobile: {device_info['is_mobile']}")
IP Address Monitoring¶
# Sessions track IP addresses for security monitoring
session_data = await session_manager.validate_session(session_id)
print(f"Session from IP: {session_data.ip_address}")
# Detect IP changes (potential session hijacking)
if session_data.ip_address != request.client.host:
# Handle potential security issue
await session_manager.terminate_session(session_id)
Configuration Options¶
Session Manager Settings¶
session_manager = SessionManager(
# Storage configuration
session_backend="redis",
redis_host="localhost",
redis_port=6379,
redis_db=0,
redis_password=None,
# Session limits
max_sessions_per_user=5,
session_timeout_minutes=30,
# Cleanup
cleanup_interval_minutes=15,
# CSRF
csrf_token_bytes=32,
# Rate limiting
login_max_attempts=5,
login_window_minutes=15
)
Backend-Specific Options¶
Redis Configuration¶
redis_storage = get_session_storage(
backend="redis",
model_type=SessionData,
host="localhost",
port=6379,
db=0,
password="your-password",
pool_size=10,
connect_timeout=10,
prefix="session:",
expiration=1800 # 30 minutes
)
Database Configuration¶
database_storage = get_session_storage(
backend="database",
model_type=SessionData,
db_config=your_db_config,
prefix="session:",
expiration=1800
)
Integration with CRUDAdmin¶
Automatic Session Management¶
from crudadmin import CRUDAdmin
# CRUDAdmin automatically creates and manages sessions
crud_admin = CRUDAdmin(
# Session backend configuration
session_backend="redis",
redis_url="redis://localhost:6379",
# Session settings
session_timeout=30, # minutes
max_sessions_per_user=5,
# Security
secret_key="your-secret-key",
csrf_protection=True
)
Custom Session Storage¶
# Use custom session storage
custom_storage = YourCustomSessionStorage()
crud_admin = CRUDAdmin(
session_storage=custom_storage,
secret_key="your-secret-key"
)
Session Data Structure¶
SessionData Fields¶
Field | Type | Description |
---|---|---|
user_id |
int | ID of the authenticated user |
session_id |
str | Unique session identifier |
ip_address |
str | IP address when session was created |
user_agent |
str | User agent string from browser |
device_info |
dict | Parsed device/browser information |
created_at |
datetime | When the session was created |
last_activity |
datetime | Last time session was validated |
is_active |
bool | Whether the session is active |
metadata |
dict | Additional session-specific data |
Device Information¶
device_info = {
"browser": "Chrome",
"browser_version": "120.0.0.0",
"os": "Windows",
"device": "PC",
"is_mobile": False,
"is_tablet": False,
"is_pc": True
}
Error Handling¶
Session Validation Errors¶
try:
session_data = await session_manager.validate_session(session_id)
if not session_data:
# Session not found, expired, or inactive
raise HTTPException(status_code=401, detail="Invalid session")
except Exception as e:
logger.error(f"Session validation error: {e}")
raise HTTPException(status_code=500, detail="Session validation failed")
Backend Connection Errors¶
try:
await session_manager.create_session(request, user_id)
except ConnectionError:
# Backend (Redis/Memcached) unavailable
# Fallback to memory storage or return error
pass
except Exception as e:
logger.error(f"Session creation failed: {e}")
raise
Performance Considerations¶
Session Cleanup¶
import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
# Schedule periodic cleanup
scheduler = AsyncIOScheduler()
scheduler.add_job(
session_manager.cleanup_expired_sessions,
'interval',
minutes=15,
id='session_cleanup'
)
scheduler.start()
Connection Pooling¶
# Redis with connection pooling
redis_storage = get_session_storage(
backend="redis",
model_type=SessionData,
host="localhost",
port=6379,
pool_size=20, # Increase pool size for high traffic
connect_timeout=10
)
Session Limits¶
# Prevent memory exhaustion
session_manager = SessionManager(
max_sessions_per_user=10, # Limit per user
session_timeout_minutes=30, # Auto-expire
cleanup_interval_minutes=15 # Regular cleanup
)
Monitoring and Debugging¶
Session Metrics¶
# Get active session count for user
user_sessions = await session_manager.get_user_sessions(user_id)
print(f"User has {len(user_sessions)} active sessions")
# Monitor session activity
session_data = await session_manager.validate_session(session_id)
if session_data:
session_age = datetime.now(UTC) - session_data.last_activity
print(f"Session last active {session_age} ago")
Debug Information¶
# Enable detailed logging
import logging
logging.getLogger('crudadmin.session').setLevel(logging.DEBUG)
# Session data includes debug information
print(f"Session metadata: {session_data.metadata}")
print(f"Device info: {session_data.device_info}")
The session management system provides a robust, secure foundation for authentication in CRUDAdmin with flexibility to scale from development to production environments.