from aws_lambda_powertools.event_handler.api_gateway import ( APIGatewayHttpResolver, Response, ) from aws_lambda_powertools.event_handler.middlewares import ( BaseMiddlewareHandler, NextMiddleware, ) from pydantic import UUID4, BaseModel, EmailStr, Field class User(BaseModel): id: str | UUID4 = Field(alias='sub') name: str email: EmailStr email_verified: bool class AuthenticationMiddleware(BaseMiddlewareHandler): """This middleware extracts user authentication details from the `jwt_claim` authorizer context and makes them available in the application context. """ def handler( self, app: APIGatewayHttpResolver, next_middleware: NextMiddleware, ) -> Response: jwt_claim = app.current_event.request_context.authorizer.jwt_claim if jwt_claim: app.append_context(user=User.model_validate(jwt_claim)) return next_middleware(app)