kal-middleware


Namekal-middleware JSON
Version 1.0.2 PyPI version JSON
download
home_pageNone
SummaryKaleidoo middleware package
upload_time2024-06-18 13:21:18
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT License
keywords kal-middleware
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # kal-middleware


[![image](https://img.shields.io/pypi/v/kal-middleware.svg)](https://pypi.python.org/pypi/kal-middleware)

`kal-middleware` is a Python package designed for FastAPI applications to provide robust JWT and Service-to-Service (STS) authentication using Firebase and Google Identity Platform.

## Features

- **JWT Authentication**: Ensures that the JWTs are valid and checks user roles against provided configurations.
- **STS Authentication**: Validates tokens for service-to-service communication ensuring that only verified services can communicate.

## Installation

Install `kal-middleware` using pip:

```bash
pip install kal-middleware
```

# Usage

## JWT Authentication

To add JWT authentication to your FastAPI endpoints, you can use the `jwt_authenticated` decorator provided by `kal-middleware`. This decorator checks if the JWT token in the `Authorization` header is valid and whether the user has the appropriate role based on a configuration map.

Here's an example of how to apply the `firebase_jwt_authenticated` decorator:

**Notice:** After the JWT is processed, the `request.state` holds:
1. `user_uid` - The Firebase unique ID.
2. `user_capabilities` - A list of capabilities for later use in the request processing, if needed.
3. `user` - If `check_access` is used, the user object will be attached to the request, so the entire process does not need to call the request again.

```python
from kal_middleware.jwt import firebase_jwt_authenticated
from typing import List
from utils import get_org, get_user_by_fb_uid, get_capability_by_service_action

async def get_user(firebase_uid):
    user = await get_user_by_fb_uid(firebase_uid)
    return user

# if there is specific variable in the body that needed checks of who access its data only
async def check_access(user: dict, body: dict):
    # check in the db the user and his parameters
    # for example:
    capabilities = user.get("capabilities")
    if "capability_id" in body:
        access =  any(capability for capability in capabilities if capability.get("id") == body["capability_id"] )
        if not access:
            return False, f"User can't access the request."
    if "org_id" in body:
        org = get_org(body["org_id"])
        if not org:
            return False, f"Org not found"
        return True, {"org": org}
    return False, f"User {user.get('id')} from another organization then the one that was requested."


async def get_capability(service, action):
    capability = await get_capability_by_service_action(service, action)
    return capability

@app.get("/your-route/<service>/<action>")
@firebase_jwt_authenticated(get_user, check_access)
async def your_route_function(
        request: Request = None,
        service: Union[str, None] = None,
        action: Union[str, None] = None
):
    # Your route logic
    return {"message": "This is a protected route"}

# Or - if there is no need to check for specific data in the body
@app.get("/your-route-without-check-access/<service>/<action>")
@firebase_jwt_authenticated(get_user)
async def your_route_function_without_check_access(
        request: Request = None,
        service: Union[str, None] = None,
        action: Union[str, None] = None
):
    # Your route logic
    return {"message": "This is a protected route"}
```

## STS Authentication
For service-to-service (STS) authentication using Google's Identity Platform, you can use the `sts_authenticated` decorator. This ensures that the calling service's token is verified to enable secure interactions between services.

Here's how to use the `sts_authenticated` decorator in your FastAPI app:
- Make sure first you have env variable named `ALLOWED_SERVICE_ACCOUNTS` with the following structure: `example1@gserviceaccount.com, example2@gserviceaccount.com`
```python
from kal_middleware.sts import sts_authenticated

@app.get("/secure-service")
@sts_authenticated
async def secure_service_function():
    # Logic that requires service-to-service authentication
    return {"message": "Service-to-service call is authenticated"}
```
This configuration will parse and verify the Authorization header, ensuring that only requests with a verified bearer token can access the endpoint.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "kal-middleware",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "kal-middleware",
    "author": null,
    "author_email": "Bar Lander <barh@kaleidoo.ai>",
    "download_url": "https://files.pythonhosted.org/packages/0d/60/649b68c8f9fea5efe3f1b385dfa6eb64eaceb5a2474fdf3349011a2d81fd/kal_middleware-1.0.2.tar.gz",
    "platform": null,
    "description": "# kal-middleware\n\n\n[![image](https://img.shields.io/pypi/v/kal-middleware.svg)](https://pypi.python.org/pypi/kal-middleware)\n\n`kal-middleware` is a Python package designed for FastAPI applications to provide robust JWT and Service-to-Service (STS) authentication using Firebase and Google Identity Platform.\n\n## Features\n\n- **JWT Authentication**: Ensures that the JWTs are valid and checks user roles against provided configurations.\n- **STS Authentication**: Validates tokens for service-to-service communication ensuring that only verified services can communicate.\n\n## Installation\n\nInstall `kal-middleware` using pip:\n\n```bash\npip install kal-middleware\n```\n\n# Usage\n\n## JWT Authentication\n\nTo add JWT authentication to your FastAPI endpoints, you can use the `jwt_authenticated` decorator provided by `kal-middleware`. This decorator checks if the JWT token in the `Authorization` header is valid and whether the user has the appropriate role based on a configuration map.\n\nHere's an example of how to apply the `firebase_jwt_authenticated` decorator:\n\n**Notice:** After the JWT is processed, the `request.state` holds:\n1. `user_uid` - The Firebase unique ID.\n2. `user_capabilities` - A list of capabilities for later use in the request processing, if needed.\n3. `user` - If `check_access` is used, the user object will be attached to the request, so the entire process does not need to call the request again.\n\n```python\nfrom kal_middleware.jwt import firebase_jwt_authenticated\nfrom typing import List\nfrom utils import get_org, get_user_by_fb_uid, get_capability_by_service_action\n\nasync def get_user(firebase_uid):\n    user = await get_user_by_fb_uid(firebase_uid)\n    return user\n\n# if there is specific variable in the body that needed checks of who access its data only\nasync def check_access(user: dict, body: dict):\n    # check in the db the user and his parameters\n    # for example:\n    capabilities = user.get(\"capabilities\")\n    if \"capability_id\" in body:\n        access =  any(capability for capability in capabilities if capability.get(\"id\") == body[\"capability_id\"] )\n        if not access:\n            return False, f\"User can't access the request.\"\n    if \"org_id\" in body:\n        org = get_org(body[\"org_id\"])\n        if not org:\n            return False, f\"Org not found\"\n        return True, {\"org\": org}\n    return False, f\"User {user.get('id')} from another organization then the one that was requested.\"\n\n\nasync def get_capability(service, action):\n    capability = await get_capability_by_service_action(service, action)\n    return capability\n\n@app.get(\"/your-route/<service>/<action>\")\n@firebase_jwt_authenticated(get_user, check_access)\nasync def your_route_function(\n        request: Request = None,\n        service: Union[str, None] = None,\n        action: Union[str, None] = None\n):\n    # Your route logic\n    return {\"message\": \"This is a protected route\"}\n\n# Or - if there is no need to check for specific data in the body\n@app.get(\"/your-route-without-check-access/<service>/<action>\")\n@firebase_jwt_authenticated(get_user)\nasync def your_route_function_without_check_access(\n        request: Request = None,\n        service: Union[str, None] = None,\n        action: Union[str, None] = None\n):\n    # Your route logic\n    return {\"message\": \"This is a protected route\"}\n```\n\n## STS Authentication\nFor service-to-service (STS) authentication using Google's Identity Platform, you can use the `sts_authenticated` decorator. This ensures that the calling service's token is verified to enable secure interactions between services.\n\nHere's how to use the `sts_authenticated` decorator in your FastAPI app:\n- Make sure first you have env variable named `ALLOWED_SERVICE_ACCOUNTS` with the following structure: `example1@gserviceaccount.com, example2@gserviceaccount.com`\n```python\nfrom kal_middleware.sts import sts_authenticated\n\n@app.get(\"/secure-service\")\n@sts_authenticated\nasync def secure_service_function():\n    # Logic that requires service-to-service authentication\n    return {\"message\": \"Service-to-service call is authenticated\"}\n```\nThis configuration will parse and verify the Authorization header, ensuring that only requests with a verified bearer token can access the endpoint.\n\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Kaleidoo middleware package",
    "version": "1.0.2",
    "project_urls": {
        "Homepage": "https://github.com/BarLanderK/kal-middleware"
    },
    "split_keywords": [
        "kal-middleware"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e9f1f4947a696f7fe4886068dd0360b6bc00c6ed9781a419066aebfa0e3cc454",
                "md5": "0941d1ce261d8c68fbdda49da0926c5c",
                "sha256": "076517509a9394d19b07825cd62716f334a2fb9cdbf05573b2f93c0d2d2ab8dd"
            },
            "downloads": -1,
            "filename": "kal_middleware-1.0.2-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0941d1ce261d8c68fbdda49da0926c5c",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.8",
            "size": 6639,
            "upload_time": "2024-06-18T13:21:16",
            "upload_time_iso_8601": "2024-06-18T13:21:16.084362Z",
            "url": "https://files.pythonhosted.org/packages/e9/f1/f4947a696f7fe4886068dd0360b6bc00c6ed9781a419066aebfa0e3cc454/kal_middleware-1.0.2-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0d60649b68c8f9fea5efe3f1b385dfa6eb64eaceb5a2474fdf3349011a2d81fd",
                "md5": "d4153e1a1bd553013f18afd468ac2837",
                "sha256": "753d9a680143ae989b5bd05989b11bd5a3cc6ee141e6cce0cc20ef3bc900aa72"
            },
            "downloads": -1,
            "filename": "kal_middleware-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "d4153e1a1bd553013f18afd468ac2837",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 14940,
            "upload_time": "2024-06-18T13:21:18",
            "upload_time_iso_8601": "2024-06-18T13:21:18.806811Z",
            "url": "https://files.pythonhosted.org/packages/0d/60/649b68c8f9fea5efe3f1b385dfa6eb64eaceb5a2474fdf3349011a2d81fd/kal_middleware-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-18 13:21:18",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "BarLanderK",
    "github_project": "kal-middleware",
    "github_not_found": true,
    "lcname": "kal-middleware"
}
        
Elapsed time: 0.52642s