39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
from aws_lambda_powertools import Logger
|
|
|
|
logger = Logger(__name__)
|
|
|
|
|
|
class UnauthorizedError(Exception):
|
|
pass
|
|
|
|
|
|
def get_user(access_token: str, /, idp_client) -> dict[str, str]:
|
|
"""Gets the user attributes and metadata for a user."""
|
|
try:
|
|
user = idp_client.get_user(AccessToken=access_token)
|
|
except idp_client.exceptions.ClientError:
|
|
raise UnauthorizedError()
|
|
else:
|
|
return {attr['Name']: attr['Value'] for attr in user['UserAttributes']}
|
|
|
|
|
|
def admin_get_user(
|
|
sub: str,
|
|
user_pool_id: str,
|
|
*,
|
|
idp_client,
|
|
) -> dict[str, str] | None:
|
|
"""Gets the specified user by user name in a user pool as an administrator.
|
|
Works on any user.
|
|
|
|
- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp/client/admin_get_user.html
|
|
- https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetUser.html
|
|
"""
|
|
try:
|
|
user = idp_client.admin_get_user(Username=sub, UserPoolId=user_pool_id)
|
|
except idp_client.exceptions as err:
|
|
logger.exception(err)
|
|
return None
|
|
else:
|
|
return user
|