Coverage for fastblocks / adapters / auth / _base.py: 78%

27 statements  

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

1import typing as t 

2from contextvars import ContextVar 

3 

4# Oneiric imports 

5from oneiric.core.config import OneiricSettings 

6from pydantic import UUID4, EmailStr, SecretStr 

7from starlette.authentication import UnauthenticatedUser 

8from fastblocks.htmx import HtmxRequest 

9 

10 

11class AuthBaseSettings(OneiricSettings): 

12 """Auth base settings using OneiricSettings.""" 

13 

14 token_id: str | None = None 

15 

16 def __init__(self, **data: t.Any) -> None: 

17 super().__init__(**data) 

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

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

20 self.token_id = self.token_id or "_fb_" 

21 

22 

23class CurrentUser(t.Protocol): 

24 def has_role(self, _: str) -> str: ... 

25 

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

27 

28 @property 

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

30 

31 @property 

32 def display_name(self) -> str: ... 

33 

34 @property 

35 def email(self) -> EmailStr | None: ... 

36 

37 def is_authenticated( 

38 self, 

39 request: HtmxRequest | None = None, 

40 config: t.Any = None, 

41 ) -> bool | int | str: ... 

42 

43 

44class AuthProtocol(t.Protocol): 

45 _current_user: ContextVar[t.Any] 

46 

47 @property 

48 def current_user(self) -> t.Any: ... 

49 

50 async def authenticate(self, request: HtmxRequest) -> bool: ... 

51 

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

53 

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

55 

56 

57class AuthBase: 

58 """Auth base adapter using Oneiric.""" 

59 

60 _current_user: ContextVar[t.Any] = ContextVar( 

61 "current_user", 

62 default=UnauthenticatedUser(), 

63 ) 

64 

65 @property 

66 def current_user(self) -> t.Any: 

67 return self._current_user.get() 

68 

69 @property 

70 def token_id(self) -> str: 

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

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

73 return "_fb_" 

74 

75 @staticmethod 

76 async def authenticate(request: HtmxRequest) -> bool: 

77 raise NotImplementedError 

78 

79 def __init__( 

80 self, secret_key: SecretStr, user_model: t.Any, **kwargs: t.Any 

81 ) -> None: 

82 self.secret_key = secret_key 

83 self.user_model = user_model 

84 

85 async def init(self) -> None: 

86 raise NotImplementedError 

87 

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

89 raise NotImplementedError 

90 

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

92 raise NotImplementedError