Coverage for src/lexigram/auth/web/middleware/session_validator.py: 53%
17 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-26 00:58 +0800
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-26 00:58 +0800
1"""Session validation utilities for authentication middleware."""
3from __future__ import annotations
5from typing import TYPE_CHECKING, Any
7if TYPE_CHECKING:
8 from lexigram.auth.models.user import User
11class SessionValidator:
12 """Handles session validation and authorization checks."""
14 def __init__(self, config: Any, auth_provider: Any) -> None:
15 """Initialize with configuration and auth provider.
17 Args:
18 config: AuthMiddlewareConfig
19 auth_provider: AuthProviderProtocol instance
20 """
21 self.config = config
22 self.auth_provider = auth_provider
24 def check_authorization(self, user: User) -> bool:
25 """Check if user is authorized based on roles/permissions.
27 Args:
28 user: Authenticated user
30 Returns:
31 True if authorized, False otherwise
32 """
33 if not user or not user.is_active:
34 return False
36 # Check required roles
37 if self.config.roles_required and not self.auth_provider.has_any_role(
38 user,
39 self.config.roles_required,
40 ):
41 return False
43 # Check required permissions
44 return not (
45 self.config.permissions_required
46 and not self.auth_provider.has_any_permission(
47 user, self.config.permissions_required
48 )
49 )
51 def should_skip_auth(self, path: str) -> bool:
52 """Check if authentication should be skipped for this path.
54 Args:
55 path: Request path
57 Returns:
58 True if auth should be skipped
59 """
60 # Check exact path matches
61 if path in self.config.exclude_paths:
62 return True
64 # Check path prefixes
65 return any(path.startswith(prefix) for prefix in self.config.exclude_prefixes)
68__all__ = ["SessionValidator"]