add http-api
This commit is contained in:
35
http-api/auth.py
Normal file
35
http-api/auth.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import boto3
|
||||
from aws_lambda_powertools import Logger, Tracer
|
||||
from aws_lambda_powertools.utilities.data_classes import event_source
|
||||
from aws_lambda_powertools.utilities.data_classes.api_gateway_authorizer_event import (
|
||||
APIGatewayAuthorizerEventV2,
|
||||
APIGatewayAuthorizerResponseV2,
|
||||
)
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
|
||||
from cognito import get_user
|
||||
|
||||
tracer = Tracer()
|
||||
logger = Logger(__name__)
|
||||
idp_client = boto3.client('cognito-idp')
|
||||
|
||||
|
||||
@tracer.capture_lambda_handler
|
||||
@logger.inject_lambda_context
|
||||
@event_source(data_class=APIGatewayAuthorizerEventV2)
|
||||
def lambda_handler(event: APIGatewayAuthorizerEventV2, context: LambdaContext):
|
||||
auth_header = event.get_header_value('authorization', default_value='')
|
||||
|
||||
try:
|
||||
_, bearer_token = auth_header.split(' ')
|
||||
user = get_user(bearer_token, idp_client=idp_client)
|
||||
except ValueError:
|
||||
return APIGatewayAuthorizerResponseV2(authorize=False).asdict()
|
||||
|
||||
if not user:
|
||||
return APIGatewayAuthorizerResponseV2(authorize=False).asdict()
|
||||
|
||||
return APIGatewayAuthorizerResponseV2(
|
||||
authorize=True,
|
||||
context=dict(user=user),
|
||||
).asdict()
|
||||
Reference in New Issue
Block a user