|
| 1 | +from collections.abc import Awaitable, Callable |
| 2 | +from inspect import iscoroutinefunction |
| 3 | +from typing import TypeVar |
| 4 | + |
| 5 | +import jwt |
| 6 | +from fastapi import ( |
| 7 | + Depends, |
| 8 | + HTTPException, |
| 9 | + status, |
| 10 | +) |
| 11 | +from fastapi.security import ( |
| 12 | + HTTPAuthorizationCredentials, |
| 13 | + SecurityScopes, |
| 14 | +) |
| 15 | +from jwt import PyJWTError |
| 16 | + |
| 17 | +from fastapi_toolkit.exceptions import Error, exc_detail |
| 18 | +from fastapi_toolkit.schemas.user import DecodedUserModel |
| 19 | +from fastapi_toolkit.security import HTTPBearer |
| 20 | + |
| 21 | +T = TypeVar('T', bound=DecodedUserModel) |
| 22 | + |
| 23 | + |
| 24 | +def get_user_dependency( |
| 25 | + jwt_secret_dependency: Callable[..., str | Awaitable[str]], |
| 26 | + alg_dependency: Callable[..., str | Awaitable[str]], |
| 27 | + project_dependency: Callable[..., str | Awaitable[str]], |
| 28 | + user_model: type[T], |
| 29 | + token_validator: Callable[[T], None | Awaitable[None]] | None = None, |
| 30 | +) -> Callable[..., Awaitable[T]]: |
| 31 | + async def get_user( |
| 32 | + security_scopes: SecurityScopes, |
| 33 | + auth: HTTPAuthorizationCredentials = Depends(HTTPBearer( |
| 34 | + auto_error=True |
| 35 | + )), |
| 36 | + jwt_secret: str = Depends(jwt_secret_dependency), |
| 37 | + alg: str = Depends(alg_dependency), |
| 38 | + project: str = Depends(project_dependency), |
| 39 | + ) -> T: |
| 40 | + try: |
| 41 | + decoded_token = jwt.decode(auth.credentials, jwt_secret, algorithms=[alg]) |
| 42 | + except PyJWTError as exc: |
| 43 | + raise HTTPException( |
| 44 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 45 | + detail=exc_detail( |
| 46 | + code=Error.jwt_validation_error, |
| 47 | + error=str(exc) |
| 48 | + ) |
| 49 | + ) from exc |
| 50 | + else: |
| 51 | + decoded_token = user_model.model_validate(decoded_token) |
| 52 | + |
| 53 | + if token_validator is not None: |
| 54 | + if iscoroutinefunction(token_validator): |
| 55 | + await token_validator(decoded_token) |
| 56 | + else: |
| 57 | + token_validator(decoded_token) |
| 58 | + |
| 59 | + user_permissions = decoded_token.permissions.get(project, 0) |
| 60 | + for scope in (security_scopes.scopes or []): |
| 61 | + scope = int(scope) |
| 62 | + if not (user_permissions & scope == scope): |
| 63 | + raise HTTPException( |
| 64 | + status_code=status.HTTP_403_FORBIDDEN, |
| 65 | + detail=exc_detail( |
| 66 | + code=Error.permissions_error, |
| 67 | + error='Permissions required', |
| 68 | + info={ |
| 69 | + 'project': project, |
| 70 | + 'required_permission': scope, |
| 71 | + 'user_permissions': user_permissions |
| 72 | + } |
| 73 | + ) |
| 74 | + ) |
| 75 | + return decoded_token |
| 76 | + return get_user |
0 commit comments