Skip to main content

SDK em Python para integrar com o Gates para autenticação via Cognito e gestão de usuários

Project description

Gates SDK (Python)

PyPI version Python versions License: MIT Code style: black

Python SDK for authenticating users with AWS Cognito JWT tokens and managing users via the Gates backend API.

Features

  • JWT verification against AWS Cognito (access tokens and id tokens)
  • Group-based authorization middleware
  • Automatic JWKS public key caching (1-hour TTL)
  • Admin user management (create, update, list users)
  • Framework-agnostic middleware (FastAPI, Flask, etc.)
  • Full type hints and strict mypy compliance
  • Comprehensive test suite

Installation

pip install gates-sdk

Quick Start

Token Verification

from gates_sdk import AuthService

auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
    client_id="your-cognito-client-id",
)

user = auth.verify_token(token)
print(user.user_id, user.groups)

Middleware

from gates_sdk import AuthService, HandleAuthConfig, handle_auth

auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
    client_id="your-cognito-client-id",
)

# Composable functions
from gates_sdk import extract_token, authenticate, authorize

token = extract_token(request.headers.get("Authorization"))
user = authenticate(token, auth)
authorize(user, ["GAIA", "RECAPE"])  # accepts str or list

# Or all-in-one
user = handle_auth(
    request.headers.get("Authorization"),
    HandleAuthConfig(service=auth, required_groups=["GAIA"]),
)

Admin Operations

from gates_sdk import GatesAdminService

admin = GatesAdminService(base_url="https://api-gateway-url/stage")

# Create a user and add them to a client group
result = admin.create_user(
    id_token,
    email="user@example.com",
    name="User Name",
    role="CLIENT_USER",
    client="GAIA",
)
print(result["sub"])  # new user's Cognito sub

# Update user group membership
admin.update_user(
    id_token,
    user_id="user-sub-id",
    clients_to_add=["RECAPE"],
    clients_to_remove=["GAIA"],
)

# List all users for a client
response = admin.get_all_users(
    id_token,
    client="GAIA",
    page_size=20,
    name_filter="Alice",
    enabled_filter=True,
)
for user in response.users:
    print(user.user_id, user.name, user.email)
print(response.next_pagination_token, response.has_more, response.total_count)

API Reference

AuthService(region, user_pool_id, client_id)

Verifies JWT tokens issued by AWS Cognito.

Parameter Type Description
region str AWS region (e.g. "sa-east-1")
user_pool_id str Cognito User Pool ID
client_id str Cognito App Client ID

Methods:

  • verify_token(token: str) -> GatesUser — verifies the JWT and returns a GatesUser

GatesAdminService(base_url)

Calls the Gates API Gateway for user management. All methods receive an id_token per call (admin's Cognito id_token).

Methods:

  • create_user(id_token, *, email, name, role, client) -> dict — creates user and adds to client group
  • update_user(id_token, *, user_id, clients_to_add?, clients_to_remove?) -> None
  • get_all_users(id_token, *, client, pagination_token?, page_size?, name_filter?, email_filter?, role_filter?, enabled_filter?) -> GetAllUsersResponse

Middleware Functions

  • extract_token(authorization_header) -> str — extracts Bearer token; raises MissingAuthorizationError if not Bearer scheme
  • authenticate(token, service) -> GatesUser — verifies token
  • authorize(user, required_groups: str | List[str]) -> None — checks group membership
  • handle_auth(authorization_header, config: HandleAuthConfig) -> GatesUser — composes all three

GatesUser

Field Type Description
user_id str Cognito sub
groups List[str] cognito:groups claim (default [])
token_use "access" | "id" token type
exp int | None expiration timestamp
iat int | None issued-at timestamp
email str | None id_token only
name str | None id_token only
role str | None custom:general_role claim

GetAllUsersResponse

Field Type
users List[UserDetails]
next_pagination_token str | None
has_more bool
total_count int

Error Hierarchy

GatesError
├── AuthenticationError
│   ├── TokenExpiredError          (code: TOKEN_EXPIRED)
│   ├── InvalidTokenError          (code: INVALID_TOKEN)
│   ├── MissingAuthorizationError  (code: MISSING_AUTHORIZATION)
│   └── UnauthorizedGroupError     (code: UNAUTHORIZED_GROUP)
├── ApiError
│   └── ApiRequestError            (code: API_REQUEST_ERROR, has .status_code)
├── MissingParameterError          (code: MISSING_PARAMETER)
└── InvalidParameterError          (code: INVALID_PARAMETER)

Valid roles: INTERNAL_ADMIN, INTERNAL_USER, CLIENT_ADMIN, CLIENT_USER

Development

# Clone and set up
git clone https://github.com/intelicity/gates-python-sdk.git
cd gates-python-sdk
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install -e ".[dev]"

# Run tests
pytest

# Format
black src tests && isort src tests

# Lint + type check
flake8 src tests
mypy src

# All checks at once
make check

Requirements

  • Python ≥ 3.9
  • pyjwt[crypto] ≥ 2.8
  • httpx ≥ 0.27, < 1.0

License

MIT — see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gates_sdk-0.2.0.tar.gz (19.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gates_sdk-0.2.0-py3-none-any.whl (14.4 kB view details)

Uploaded Python 3

File details

Details for the file gates_sdk-0.2.0.tar.gz.

File metadata

  • Download URL: gates_sdk-0.2.0.tar.gz
  • Upload date:
  • Size: 19.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.5

File hashes

Hashes for gates_sdk-0.2.0.tar.gz
Algorithm Hash digest
SHA256 b654c3145b4b166bfd5981ef307b0543737d82fe3eb0a5addab38da0eaee314f
MD5 64357ed69f0f6ef95f6c1bf2c2807eb1
BLAKE2b-256 6d6d7d130f1324a4e0f630d2f987b133a354511084b53ace00cc4efe514cdbd9

See more details on using hashes here.

File details

Details for the file gates_sdk-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: gates_sdk-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 14.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.5

File hashes

Hashes for gates_sdk-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b7124f3bc300c5766d364329646ecb8bd186f9e67d8561f5e723e84d8acd25cb
MD5 381aece086154c6fcb7837cc9488c738
BLAKE2b-256 6d4044c5c63ffcfcd9afa070a0e38192ab71e7a56078d578c321ced6da0036d1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page