SDK em Python para integrar com o Gates para autenticação via Cognito e gestão de usuários
Project description
Gates SDK (Python)
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
# With a single client ID
auth = AuthService(
region="sa-east-1",
user_pool_id="sa-east-1_xxxxxxxxx",
client_id="your-cognito-client-id",
)
# With multiple client IDs (accepts tokens from any of them)
auth = AuthService(
region="sa-east-1",
user_pool_id="sa-east-1_xxxxxxxxx",
client_id=["client-id-1", "client-id-2"],
)
# Without client ID (skips client validation entirely)
auth = AuthService(
region="sa-east-1",
user_pool_id="sa-east-1_xxxxxxxxx",
)
user = auth.verify_token(token)
print(user.user_id, user.groups)
Supports both access_token (validates client_id claim) and id_token (validates aud claim). The token_use field on the returned user indicates which type was verified.
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=None)
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 | List[str] | None |
Cognito App Client ID(s). Omit to skip client validation. |
Methods:
verify_token(token: str) -> GatesUser— verifies the JWT and returns aGatesUser
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 groupupdate_user(id_token, *, user_id, clients_to_add?, clients_to_remove?) -> Noneget_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; raisesMissingAuthorizationErrorif not Bearer schemeauthenticate(token, service) -> GatesUser— verifies tokenauthorize(user, required_groups: str | List[str]) -> None— checks group membershiphandle_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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gates_sdk-0.2.1.tar.gz.
File metadata
- Download URL: gates_sdk-0.2.1.tar.gz
- Upload date:
- Size: 20.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2570b08c1ba4176b4cadf43eaabfdcd48ccd023381f8909d5d09e8ade46b10d9
|
|
| MD5 |
193b6e8e646e80e4dc2e85154e5d8793
|
|
| BLAKE2b-256 |
e7f11b5eada36c0d69449a67991c047274710609cdaa5b0936096c127aaca943
|
File details
Details for the file gates_sdk-0.2.1-py3-none-any.whl.
File metadata
- Download URL: gates_sdk-0.2.1-py3-none-any.whl
- Upload date:
- Size: 14.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c65f2968e8a0685c423fd50e00f1b7d91a141f13b45ff001c4042dac1d2eb279
|
|
| MD5 |
af0c52912cd775e0e947269040f4299c
|
|
| BLAKE2b-256 |
65c40aa8fd74e8ccc8e70a534678a3038ee5e4a136280d7a5d9a2450433c0f3b
|