|
| 1 | +from dataclasses import dataclass |
1 | 2 | from typing import Any, Dict, List, Optional, Tuple
|
2 | 3 |
|
3 | 4 | from fastapi import Depends, HTTPException, Request, Response, WebSocket, status
|
|
9 | 10 | from .config import _AuthFiefConfig
|
10 | 11 |
|
11 | 12 |
|
12 |
| -class Backend: |
13 |
| - def __init__(self, auth_fief_config: _AuthFiefConfig): |
14 |
| - class CustomFiefAuth(FiefAuth): |
15 |
| - client: FiefAsync |
| 13 | +class CustomFiefAuth(FiefAuth): |
| 14 | + client: FiefAsync |
16 | 15 |
|
17 |
| - async def get_unauthorized_response(self, request: Request, response: Response): |
18 |
| - redirect_uri = str(request.url_for("auth_callback")) |
19 |
| - auth_url = await self.client.auth_url(redirect_uri, scope=["openid"]) |
20 |
| - raise HTTPException( |
21 |
| - status_code=status.HTTP_307_TEMPORARY_REDIRECT, |
22 |
| - headers={"Location": auth_url}, |
23 |
| - ) |
24 |
| - |
25 |
| - self.fief = FiefAsync( |
26 |
| - auth_fief_config.base_url, |
27 |
| - auth_fief_config.client_id, |
28 |
| - auth_fief_config.client_secret, |
| 16 | + async def get_unauthorized_response(self, request: Request, response: Response): |
| 17 | + redirect_uri = str(request.url_for("auth_callback")) |
| 18 | + auth_url = await self.client.auth_url(redirect_uri, scope=["openid"]) |
| 19 | + raise HTTPException( |
| 20 | + status_code=status.HTTP_307_TEMPORARY_REDIRECT, |
| 21 | + headers={"Location": auth_url}, |
29 | 22 | )
|
30 | 23 |
|
31 |
| - self.SESSION_COOKIE_NAME = "fps_auth_fief_user_session" |
32 |
| - scheme = APIKeyCookie(name=self.SESSION_COOKIE_NAME, auto_error=False) |
33 |
| - self.auth = CustomFiefAuth(self.fief, scheme) |
34 | 24 |
|
35 |
| - async def update_user( |
36 |
| - user: FiefUserInfo = Depends(self.auth.current_user()), |
37 |
| - access_token_info: FiefAccessTokenInfo = Depends(self.auth.authenticated()), |
38 |
| - ): |
39 |
| - async def _(data: Dict[str, Any]) -> FiefUserInfo: |
40 |
| - user = await self.fief.update_profile( |
41 |
| - access_token_info["access_token"], {"fields": data} |
42 |
| - ) |
43 |
| - return user |
44 |
| - |
45 |
| - return _ |
46 |
| - |
47 |
| - def websocket_auth(permissions: Optional[Dict[str, List[str]]] = None): |
48 |
| - async def _( |
49 |
| - websocket: WebSocket, |
50 |
| - ) -> Optional[Tuple[WebSocket, Optional[Dict[str, List[str]]]]]: |
51 |
| - accept_websocket = False |
52 |
| - checked_permissions: Optional[Dict[str, List[str]]] = None |
53 |
| - if self.SESSION_COOKIE_NAME in websocket._cookies: |
54 |
| - access_token = websocket._cookies[self.SESSION_COOKIE_NAME] |
55 |
| - if permissions is None: |
56 |
| - accept_websocket = True |
57 |
| - else: |
58 |
| - checked_permissions = {} |
59 |
| - for resource, actions in permissions.items(): |
60 |
| - allowed = checked_permissions[resource] = [] |
61 |
| - for action in actions: |
62 |
| - try: |
63 |
| - await self.fief.validate_access_token( |
64 |
| - access_token, required_permissions=[f"{resource}:{action}"] |
65 |
| - ) |
66 |
| - except BaseException: |
67 |
| - pass |
68 |
| - else: |
69 |
| - allowed.append(action) |
70 |
| - accept_websocket = True |
71 |
| - if accept_websocket: |
72 |
| - return websocket, checked_permissions |
| 25 | +@dataclass |
| 26 | +class Res: |
| 27 | + fief: FiefAsync |
| 28 | + session_cookie_name: str |
| 29 | + auth: CustomFiefAuth |
| 30 | + current_user: Any |
| 31 | + update_user: Any |
| 32 | + websocket_auth: Any |
| 33 | + |
| 34 | + |
| 35 | +def get_backend(auth_fief_config: _AuthFiefConfig) -> Res: |
| 36 | + fief = FiefAsync( |
| 37 | + auth_fief_config.base_url, |
| 38 | + auth_fief_config.client_id, |
| 39 | + auth_fief_config.client_secret, |
| 40 | + ) |
| 41 | + |
| 42 | + session_cookie_name = "fps_auth_fief_user_session" |
| 43 | + scheme = APIKeyCookie(name=session_cookie_name, auto_error=False) |
| 44 | + auth = CustomFiefAuth(fief, scheme) |
| 45 | + |
| 46 | + async def update_user( |
| 47 | + user: FiefUserInfo = Depends(auth.current_user()), |
| 48 | + access_token_info: FiefAccessTokenInfo = Depends(auth.authenticated()), |
| 49 | + ): |
| 50 | + async def _(data: Dict[str, Any]) -> FiefUserInfo: |
| 51 | + user = await fief.update_profile(access_token_info["access_token"], {"fields": data}) |
| 52 | + return user |
| 53 | + |
| 54 | + return _ |
| 55 | + |
| 56 | + def websocket_auth(permissions: Optional[Dict[str, List[str]]] = None): |
| 57 | + async def _( |
| 58 | + websocket: WebSocket, |
| 59 | + ) -> Optional[Tuple[WebSocket, Optional[Dict[str, List[str]]]]]: |
| 60 | + accept_websocket = False |
| 61 | + checked_permissions: Optional[Dict[str, List[str]]] = None |
| 62 | + if session_cookie_name in websocket._cookies: |
| 63 | + access_token = websocket._cookies[session_cookie_name] |
| 64 | + if permissions is None: |
| 65 | + accept_websocket = True |
73 | 66 | else:
|
74 |
| - await websocket.close(code=status.WS_1008_POLICY_VIOLATION) |
75 |
| - return None |
| 67 | + checked_permissions = {} |
| 68 | + for resource, actions in permissions.items(): |
| 69 | + allowed = checked_permissions[resource] = [] |
| 70 | + for action in actions: |
| 71 | + try: |
| 72 | + await fief.validate_access_token( |
| 73 | + access_token, required_permissions=[f"{resource}:{action}"] |
| 74 | + ) |
| 75 | + except BaseException: |
| 76 | + pass |
| 77 | + else: |
| 78 | + allowed.append(action) |
| 79 | + accept_websocket = True |
| 80 | + if accept_websocket: |
| 81 | + return websocket, checked_permissions |
| 82 | + else: |
| 83 | + await websocket.close(code=status.WS_1008_POLICY_VIOLATION) |
| 84 | + return None |
76 | 85 |
|
77 |
| - return _ |
| 86 | + return _ |
78 | 87 |
|
79 |
| - def current_user(permissions=None): |
80 |
| - if permissions is not None: |
81 |
| - permissions = [ |
82 |
| - f"{resource}:{action}" |
83 |
| - for resource, actions in permissions.items() |
84 |
| - for action in actions |
85 |
| - ] |
| 88 | + def current_user(permissions=None): |
| 89 | + if permissions is not None: |
| 90 | + permissions = [ |
| 91 | + f"{resource}:{action}" |
| 92 | + for resource, actions in permissions.items() |
| 93 | + for action in actions |
| 94 | + ] |
86 | 95 |
|
87 |
| - async def _( |
88 |
| - user: FiefUserInfo = Depends(self.auth.current_user(permissions=permissions)), |
89 |
| - ): |
90 |
| - return User(**user["fields"]) |
| 96 | + async def _( |
| 97 | + user: FiefUserInfo = Depends(auth.current_user(permissions=permissions)), |
| 98 | + ): |
| 99 | + return User(**user["fields"]) |
91 | 100 |
|
92 |
| - return _ |
| 101 | + return _ |
93 | 102 |
|
94 |
| - self.current_user = current_user |
95 |
| - self.update_user = update_user |
96 |
| - self.websocket_auth = websocket_auth |
| 103 | + return Res( |
| 104 | + fief=fief, |
| 105 | + session_cookie_name=session_cookie_name, |
| 106 | + auth=auth, |
| 107 | + current_user=current_user, |
| 108 | + update_user=update_user, |
| 109 | + websocket_auth=websocket_auth, |
| 110 | + ) |
0 commit comments