Coverage for fastblocks / adapters / auth / basic.py: 55%

58 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Basic Authentication Adapter for FastBlocks. 

2 

3Provides HTTP Basic Authentication with session management for FastBlocks applications. 

4Includes secure credential validation, session middleware integration, and user model support. 

5 

6Features: 

7- HTTP Basic Authentication with base64 credential encoding 

8- Session-based authentication state management 

9- Configurable secret key for session security 

10- HTTPS-only cookies in production environments 

11- Integration with Starlette authentication middleware 

12- Custom user model support for extended user data 

13 

14Requirements: 

15- starlette>=0.47.1 

16- pydantic>=2.11.7 

17 

18Usage: 

19```python 

20# Updated for Oneiric 

21from fastblocks.adapters.auth.basic import Auth 

22 

23auth = Auth(secret_key="your-secret-key") 

24 

25auth_middleware = await auth.init() 

26``` 

27 

28Author: lesleslie <les@wedgwoodwebworks.com> 

29Created: 2025-01-12 

30""" 

31 

32import base64 

33import binascii 

34import typing as t 

35from uuid import UUID 

36 

37# Oneiric imports 

38from pydantic import UUID4, EmailStr, SecretStr 

39from starlette.authentication import AuthCredentials, AuthenticationError, SimpleUser 

40from starlette.middleware import Middleware 

41from starlette.middleware.sessions import SessionMiddleware 

42from starlette.requests import Request 

43from fastblocks.htmx import HtmxRequest 

44 

45from ._base import AuthBase, AuthBaseSettings 

46 

47 

48class AuthSettings(AuthBaseSettings): 

49 pass 

50 

51 

52class CurrentUser: 

53 def has_role(self, _: str) -> str: 

54 raise NotImplementedError 

55 

56 def set_role(self, _: str) -> str | bool | None: 

57 raise NotImplementedError 

58 

59 @property 

60 def identity(self) -> UUID4 | str | int: 

61 raise NotImplementedError 

62 

63 @property 

64 def display_name(self) -> str: 

65 raise NotImplementedError 

66 

67 @property 

68 def email(self) -> EmailStr | None: 

69 raise NotImplementedError 

70 

71 def is_authenticated( 

72 self, 

73 request: HtmxRequest | None = None, 

74 config: t.Any = None, 

75 ) -> bool | int | str: 

76 raise NotImplementedError 

77 

78 

79class Auth(AuthBase): 

80 secret_key: SecretStr 

81 

82 @staticmethod 

83 async def authenticate(request: HtmxRequest | Request) -> bool: 

84 headers = getattr(request, "headers", {}) 

85 if "Authorization" not in headers: 

86 return False 

87 auth = headers["Authorization"] 

88 try: 

89 scheme, credentials = auth.split() 

90 if scheme.lower() != "basic": 

91 return False 

92 decoded = base64.b64decode(credentials).decode("ascii") 

93 except (ValueError, UnicodeDecodeError, binascii.Error): 

94 msg = "Invalid basic auth credentials" 

95 raise AuthenticationError(msg) 

96 username, _, _ = decoded.partition(":") 

97 state = getattr(request, "state", None) 

98 if state: 

99 state.auth_credentials = ( 

100 AuthCredentials(["authenticated"]), 

101 SimpleUser(username), 

102 ) 

103 return True 

104 

105 def __init__( 

106 self, 

107 secret_key: SecretStr | None = None, 

108 user_model: t.Any | None = None, 

109 ) -> None: 

110 # For Oneiric, we'll use a simpler approach 

111 # In practice, this would be replaced with actual config resolution 

112 if secret_key is None: 

113 raise ValueError("secret_key must be provided directly (Oneiric migration)") 

114 

115 super().__init__(secret_key, user_model) 

116 self.secret_key = secret_key 

117 if not self.secret_key: 

118 raise ValueError("secret_key must be provided via parameter") 

119 self.name = "basic" 

120 self.user_model = user_model 

121 

122 async def init(self) -> None: 

123 self.middlewares = [ 

124 Middleware( 

125 SessionMiddleware, 

126 secret_key=self.secret_key.get_secret_value(), 

127 session_cookie=f"{self.token_id}_admin", 

128 https_only=bool(self.config.deployed), 

129 ), 

130 ] 

131 

132 async def login(self, request: HtmxRequest) -> bool: 

133 raise NotImplementedError 

134 

135 async def logout(self, request: HtmxRequest) -> bool: 

136 raise NotImplementedError 

137 

138 

139MODULE_ID = UUID("01937d86-5f3b-7c4d-9e0f-2345678901bc") 

140MODULE_STATUS = "STABLE" # Oneiric-compatible status