add auth middleware
This commit is contained in:
@@ -6,24 +6,29 @@ from aws_lambda_powertools.event_handler.middlewares import (
|
||||
BaseMiddlewareHandler,
|
||||
NextMiddleware,
|
||||
)
|
||||
from pydantic import UUID4, BaseModel, Field
|
||||
|
||||
|
||||
class CorrelationIdMiddleware(BaseMiddlewareHandler):
|
||||
def __init__(self, header: str):
|
||||
super().__init__()
|
||||
self.header = header
|
||||
|
||||
class AuthorizerMiddleware(BaseMiddlewareHandler):
|
||||
def handler(
|
||||
self, app: APIGatewayHttpResolver, next_middleware: NextMiddleware
|
||||
self,
|
||||
app: APIGatewayHttpResolver,
|
||||
next_middleware: NextMiddleware,
|
||||
) -> Response:
|
||||
# BEFORE logic
|
||||
request_id = app.current_event.request_context.request_id
|
||||
correlation_id = app.current_event.headers.get(self.header, request_id)
|
||||
# Gets the Lambda authorizer associated with the current API Gateway event.
|
||||
# You can check the file `auth.py` for more details.
|
||||
authorizer = app.current_event.request_context.authorizer.get_lambda
|
||||
|
||||
# Call next middleware or route handler ('/todos')
|
||||
response = next_middleware(app)
|
||||
if 'user' in authorizer:
|
||||
user = authorizer['user']
|
||||
app.append_context(user=AuthenticatedUser(**user))
|
||||
|
||||
# AFTER logic
|
||||
response.headers[self.header] = correlation_id
|
||||
return next_middleware(app)
|
||||
|
||||
return response
|
||||
|
||||
class AuthenticatedUser(BaseModel):
|
||||
id: str = Field(alias='custom:user_id')
|
||||
name: str
|
||||
email: str
|
||||
email_verified: bool
|
||||
sub: UUID4
|
||||
|
||||
Reference in New Issue
Block a user