add apikey
This commit is contained in:
@@ -23,7 +23,7 @@ Example
|
||||
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
import boto3
|
||||
from aws_lambda_powertools import Logger, Tracer
|
||||
@@ -34,14 +34,19 @@ from aws_lambda_powertools.utilities.data_classes.api_gateway_authorizer_event i
|
||||
)
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
from botocore.endpoint_provider import Enum
|
||||
from layercake.dynamodb import DynamoDBCollection, DynamoDBPersistenceLayer, KeyPair
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from cognito import get_user
|
||||
from settings import USER_TABLE
|
||||
|
||||
APIKEY_PREFIX = 'sk-'
|
||||
|
||||
tracer = Tracer()
|
||||
logger = Logger(__name__)
|
||||
idp_client = boto3.client('cognito-idp')
|
||||
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
|
||||
collect = DynamoDBCollection(user_layer)
|
||||
|
||||
|
||||
@tracer.capture_lambda_handler
|
||||
@@ -53,16 +58,8 @@ def lambda_handler(event: APIGatewayAuthorizerEventV2, context: LambdaContext):
|
||||
if not bearer:
|
||||
return APIGatewayAuthorizerResponseV2(authorize=False).asdict()
|
||||
|
||||
if bearer.auth_type == TokenType.USER_TOKEN:
|
||||
user = get_user(bearer.token, idp_client=idp_client)
|
||||
|
||||
if user:
|
||||
return APIGatewayAuthorizerResponseV2(
|
||||
authorize=True,
|
||||
context=dict(user=user),
|
||||
).asdict()
|
||||
|
||||
return APIGatewayAuthorizerResponseV2(authorize=False).asdict()
|
||||
kwargs = asdict(_authorizer(bearer))
|
||||
return APIGatewayAuthorizerResponseV2(**kwargs).asdict()
|
||||
|
||||
|
||||
class TokenType(str, Enum):
|
||||
@@ -76,6 +73,25 @@ class BearerToken:
|
||||
token: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Authorizer:
|
||||
authorize: bool = False
|
||||
context: dict | None = None
|
||||
|
||||
|
||||
def _authorizer(bearer: BearerToken) -> Authorizer:
|
||||
try:
|
||||
match bearer.auth_type:
|
||||
case TokenType.USER_TOKEN:
|
||||
user = get_user(bearer.token, idp_client=idp_client)
|
||||
return Authorizer(True, {'user': user})
|
||||
case TokenType.API_KEY:
|
||||
apikey = collect.get_item(KeyPair('apikey', bearer.token))
|
||||
return Authorizer(True, {'tenant': apikey['tenant']})
|
||||
except Exception:
|
||||
return Authorizer()
|
||||
|
||||
|
||||
def _parse_bearer_token(s: str) -> BearerToken | None:
|
||||
"""Parses and identifies a bearer token as either an API key or a user token."""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user