PK!`YYmandate/__init__.pyimport aioboto3 import datetime import aiohttp import attr from envs import env from jose import jwt, JWTError from .aws_srp import AWSSRP from .exceptions import TokenVerificationException from .userobj import UserObj from .groupobj import GroupObj from .utils import dict_to_cognito __version__ = "0.2.4" @attr.s class Cognito(object): user_class = UserObj group_class = GroupObj user_pool_id = attr.ib() client_id = attr.ib() user_pool_region = attr.ib() username = attr.ib(default=None) id_token = attr.ib(default=None) access_token = attr.ib(default=None) refresh_token = attr.ib(default=None) client_secret = attr.ib(default=None) access_key = attr.ib(default=None) secret_key = attr.ib(default=None) loop = attr.ib(default=None) _client = None @user_pool_region.default def generate_region_from_pool(self): return self.user_pool_id.split('_')[0] def get_session(self): return aiohttp.ClientSession(loop=self.loop) def get_client(self): if self._client: return self._client boto3_client_kwargs = {} if self.access_key and self.secret_key: boto3_client_kwargs['aws_access_key_id'] = self.access_key boto3_client_kwargs['aws_secret_access_key'] = self.secret_key if self.user_pool_region: boto3_client_kwargs['region_name'] = self.user_pool_region self._client = aioboto3.client( 'cognito-idp', loop=self.loop, **boto3_client_kwargs) return self._client async def get_keys(self): try: return self.pool_jwk except AttributeError: # Check for the dictionary in environment variables. pool_jwk_env = env('COGNITO_JWKS', {}, var_type='dict') if len(pool_jwk_env.keys()) > 0: self.pool_jwk = pool_jwk_env return self.pool_jwk # If it is not there use the aiohttp library to get it async with self.get_session() as session: resp = await session.get( 'https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json'.format( # noqa self.user_pool_region, self.user_pool_id )) self.pool_jwk = await resp.json() return self.pool_jwk async def get_key(self, kid): keys = (await self.get_keys()).get('keys') key = list(filter(lambda x: x.get('kid') == kid, keys)) return key[0] async def verify_token(self, token, id_name, token_use): kid = jwt.get_unverified_header(token).get('kid') unverified_claims = jwt.get_unverified_claims(token) token_use_verified = unverified_claims.get('token_use') == token_use if not token_use_verified: raise TokenVerificationException( 'Your {} token use could not be verified.') hmac_key = await self.get_key(kid) try: verified = jwt.decode(token, hmac_key, algorithms=['RS256'], audience=unverified_claims.get('aud'), issuer=unverified_claims.get('iss')) except JWTError: raise TokenVerificationException( 'Your {} token could not be verified.') setattr(self, id_name, token) return verified def get_user_obj(self, username=None, attribute_list=None, metadata=None, attr_map=None): """ Returns the specified :param username: Username of the user :param attribute_list: List of tuples that represent the user's attributes as returned by the admin_get_user or get_user boto3 methods :param metadata: Metadata about the user :param attr_map: Dictionary that maps the Cognito attribute names to what we'd like to display to the users :return: """ return self.user_class(username=username, attribute_list=attribute_list, cognito_obj=self, metadata=metadata, attr_map=attr_map) def get_group_obj(self, group_data): """ Instantiates the self.group_class :param group_data: a dictionary with information about a group :return: an instance of the self.group_class """ return self.group_class(group_data=group_data, cognito_obj=self) def switch_session(self, session): """ Primarily used for unit testing so we can take advantage of the placebo library (https://githhub.com/garnaat/placebo) :param session: boto3 session :return: """ self.client = session.client('cognito-idp') async def check_token(self, renew=True): """ Checks the exp attribute of the access_token and either refreshes the tokens by calling the renew_access_tokens method or does nothing :param renew: bool indicating whether to refresh on expiration :return: bool indicating whether access_token has expired """ if not self.access_token: raise AttributeError('Access Token Required to Check Token') now = datetime.datetime.now() dec_access_token = jwt.get_unverified_claims(self.access_token) if now > datetime.datetime.fromtimestamp(dec_access_token['exp']): expired = True if renew: await self.renew_access_token() else: expired = False return expired def add_base_attributes(self, **kwargs): self.base_attributes = kwargs async def register(self, *, username, password, email, attrs={}): """ Register the user. :param username: User Pool username :param password: User Pool password :param email: User Email :param attrs: Other base attributes for AWS such as: address, birthdate, email, family_name (last name), gender, given_name (first name), locale, middle_name, name, nickname, phone_number, picture, preferred_username, profile, zoneinfo, updated at, website :return response: Response from Cognito Example response:: { 'UserConfirmed': True|False, 'CodeDeliveryDetails': { 'Destination': 'string', # This value will be obfuscated 'DeliveryMedium': 'SMS'|'EMAIL', 'AttributeName': 'string' } } """ attributes = attrs attributes['email'] = email cognito_attributes = dict_to_cognito(attributes) params = { 'ClientId': self.client_id, 'Username': username, 'Password': password, 'UserAttributes': cognito_attributes } self._add_secret_hash(params, 'SecretHash') async with self.get_client() as client: response = await client.sign_up(**params) attributes.update(username=username, password=password) self._set_attributes(response, attributes) response.pop('ResponseMetadata') return response async def admin_confirm_sign_up(self, username=None): """ Confirms user registration as an admin without using a confirmation code. Works on any user. :param username: User's username :return: """ if not username: username = self.username async with self.get_client() as client: await client.admin_confirm_sign_up( UserPoolId=self.user_pool_id, Username=username, ) async def confirm_sign_up(self, confirmation_code, username=None): """ Using the confirmation code that is either sent via email or text message. :param confirmation_code: Confirmation code sent via text or email :param username: User's username :return: """ if not username: username = self.username params = {'ClientId': self.client_id, 'Username': username, 'ConfirmationCode': confirmation_code} self._add_secret_hash(params, 'SecretHash') async with self.get_client() as client: await client.confirm_sign_up(**params) async def admin_authenticate(self, password): """ Authenticate the user using admin super privileges :param password: User's password :return: """ auth_params = { 'USERNAME': self.username, 'PASSWORD': password } self._add_secret_hash(auth_params, 'SECRET_HASH') async with self.get_client() as client: tokens = await client.admin_initiate_auth( UserPoolId=self.user_pool_id, ClientId=self.client_id, # AuthFlow='USER_SRP_AUTH'|'REFRESH_TOKEN_AUTH'|'REFRESH_TOKEN'|'CUSTOM_AUTH'|'ADMIN_NO_SRP_AUTH', AuthFlow='ADMIN_NO_SRP_AUTH', AuthParameters=auth_params, ) await self.verify_token( tokens['AuthenticationResult']['IdToken'], 'id_token', 'id') self.refresh_token = tokens['AuthenticationResult']['RefreshToken'] await self.verify_token( tokens['AuthenticationResult']['AccessToken'], 'access_token', 'access') self.token_type = tokens['AuthenticationResult']['TokenType'] async def authenticate(self, password): """ Authenticate the user using the SRP protocol :param password: The user's passsword :return: """ aws = AWSSRP(username=self.username, password=password, pool_id=self.user_pool_id, client_id=self.client_id, client=self.get_client(), client_secret=self.client_secret) tokens = await aws.authenticate_user() await self.verify_token(tokens['AuthenticationResult']['IdToken'], 'id_token', 'id') self.refresh_token = tokens['AuthenticationResult']['RefreshToken'] await self.verify_token(tokens['AuthenticationResult']['AccessToken'], 'access_token', 'access') self.token_type = tokens['AuthenticationResult']['TokenType'] async def new_password_challenge(self, password, new_password): """ Respond to the new password challenge using the SRP protocol :param password: The user's current passsword :param password: The user's new passsword """ aws = AWSSRP(username=self.username, password=password, pool_id=self.user_pool_id, client_id=self.client_id, client=self.get_client(), client_secret=self.client_secret) tokens = await aws.set_new_password_challenge(new_password) self.id_token = tokens['AuthenticationResult']['IdToken'] self.refresh_token = tokens['AuthenticationResult']['RefreshToken'] self.access_token = tokens['AuthenticationResult']['AccessToken'] self.token_type = tokens['AuthenticationResult']['TokenType'] async def logout(self): """ Logs the user out of all clients and removes the expires_in, expires_datetime, id_token, refresh_token, access_token, and token_type attributes :return: """ async with self.get_client() as client: await client.global_sign_out( AccessToken=self.access_token ) self.id_token = None self.refresh_token = None self.access_token = None self.token_type = None async def admin_update_profile(self, attrs, attr_map=None): user_attrs = dict_to_cognito(attrs, attr_map) async with self.get_client() as client: await client.admin_update_user_attributes( UserPoolId=self.user_pool_id, Username=self.username, UserAttributes=user_attrs ) async def update_profile(self, attrs, attr_map=None): """ Updates User attributes :param attrs: Dictionary of attribute name, values :param attr_map: Dictionary map from Cognito attributes to attribute names we would like to show to our users """ user_attrs = dict_to_cognito(attrs, attr_map) async with self.get_client() as client: await client.update_user_attributes( UserAttributes=user_attrs, AccessToken=self.access_token ) async def get_user(self, attr_map=None): """ Returns a UserObj (or whatever the self.user_class is) by using the user's access token. :param attr_map: Dictionary map from Cognito attributes to attribute names we would like to show to our users :return: """ async with self.get_client() as client: user = await client.get_user( AccessToken=self.access_token ) user_metadata = { 'username': user.get('Username'), 'id_token': self.id_token, 'access_token': self.access_token, 'refresh_token': self.refresh_token, } return self.get_user_obj(username=self.username, attribute_list=user.get('UserAttributes'), metadata=user_metadata, attr_map=attr_map) async def get_users(self, attr_map=None): """ Returns all users for a user pool. Returns instances of the self.user_class. :param attr_map: :return: """ kwargs = {"UserPoolId": self.user_pool_id} async with self.get_client() as client: response = await client.list_users(**kwargs) return [self.get_user_obj(user.get('Username'), attribute_list=user.get('Attributes'), metadata={ 'username': user.get('Username')}, attr_map=attr_map) for user in response.get('Users')] async def admin_get_user(self, attr_map=None): """ Get the user's details using admin super privileges. :param attr_map: Dictionary map from Cognito attributes to attribute names we would like to show to our users :return: UserObj object """ async with self.get_client() as client: user = await client.admin_get_user( UserPoolId=self.user_pool_id, Username=self.username) user_metadata = { 'enabled': user.get('Enabled'), 'user_status': user.get('UserStatus'), 'username': user.get('Username'), 'id_token': self.id_token, 'access_token': self.access_token, 'refresh_token': self.refresh_token } return self.get_user_obj(username=self.username, attribute_list=user.get('UserAttributes'), metadata=user_metadata, attr_map=attr_map) async def admin_create_user(self, username, temporary_password=None, attr_map=None, **kwargs): """ Create a user using admin super privileges. :param username: User Pool username :param temporary_password: The temporary password to give the user. Leave blank to make Cognito generate a temporary password for the user. :param attr_map: Attribute map to Cognito's attributes :param kwargs: Additional User Pool attributes :return response: Response from Cognito """ async with self.get_client() as client: if temporary_password: response = await client.admin_create_user( UserPoolId=self.user_pool_id, Username=username, UserAttributes=dict_to_cognito(kwargs, attr_map), TemporaryPassword=temporary_password, ) else: # don't @ me, i'm not the one who designed that API response = await client.admin_create_user( UserPoolId=self.user_pool_id, Username=username, UserAttributes=dict_to_cognito(kwargs, attr_map) ) kwargs.update(username=username) self._set_attributes(response, kwargs) response.pop('ResponseMetadata') return response async def send_verification(self, attribute='email'): """ Sends the user an attribute verification code for the specified attribute name. :param attribute: Attribute to confirm """ await self.check_token() async with self.get_client() as client: await client.get_user_attribute_verification_code( AccessToken=self.access_token, AttributeName=attribute ) async def validate_verification(self, confirmation_code, attribute='email'): """ Verifies the specified user attributes in the user pool. :param confirmation_code: Code sent to user upon intiating verification :param attribute: Attribute to confirm """ await self.check_token() async with self.get_client() as client: await client.verify_user_attribute( AccessToken=self.access_token, AttributeName=attribute, Code=confirmation_code ) async def renew_access_token(self): """ Sets a new access token on the User using the refresh token. """ auth_params = {'REFRESH_TOKEN': self.refresh_token} self._add_secret_hash(auth_params, 'SECRET_HASH') async with self.get_client() as client: refresh_response = await client.initiate_auth( ClientId=self.client_id, AuthFlow='REFRESH_TOKEN', AuthParameters=auth_params, ) self._set_attributes( refresh_response, { 'access_token': refresh_response['AuthenticationResult']['AccessToken'], 'id_token': refresh_response['AuthenticationResult']['IdToken'], 'token_type': refresh_response['AuthenticationResult']['TokenType'] } ) async def initiate_forgot_password(self): """ Sends a verification code to the user to use to change their password. """ params = { 'ClientId': self.client_id, 'Username': self.username } self._add_secret_hash(params, 'SecretHash') async with self.get_client() as client: await client.forgot_password(**params) async def delete_user(self): async with self.get_client() as client: await client.delete_user( AccessToken=self.access_token ) async def admin_delete_user(self): async with self.get_client() as client: await client.admin_delete_user( UserPoolId=self.user_pool_id, Username=self.username ) async def confirm_forgot_password(self, confirmation_code, password): """ Allows a user to enter a code provided when they reset their password to update their password. :param confirmation_code: Confirmation code sent by a user's request to retrieve a forgotten password :param password: New password """ params = {'ClientId': self.client_id, 'Username': self.username, 'ConfirmationCode': confirmation_code, 'Password': password } self._add_secret_hash(params, 'SecretHash') async with self.get_client() as client: response = await client.confirm_forgot_password(**params) self._set_attributes(response, {'password': password}) async def change_password(self, previous_password, proposed_password): """ Change the User password """ async with self.get_client() as client: await self.check_token() response = await client.change_password( PreviousPassword=previous_password, ProposedPassword=proposed_password, AccessToken=self.access_token ) self._set_attributes(response, {'password': proposed_password}) def _add_secret_hash(self, parameters, key): """ Helper function that computes SecretHash and adds it to a parameters dictionary at a specified key """ if self.client_secret is not None: secret_hash = AWSSRP.get_secret_hash(self.username, self.client_id, self.client_secret) parameters[key] = secret_hash def _set_attributes(self, response, attribute_dict): """ Set user attributes based on response code :param response: HTTP response from Cognito :attribute dict: Dictionary of attribute name and values """ status_code = response.get( 'HTTPStatusCode', response['ResponseMetadata']['HTTPStatusCode'] ) if status_code == 200: for k, v in attribute_dict.items(): setattr(self, k, v) async def get_group(self, group_name): """ Get a group by a name :param group_name: name of a group :return: instance of the self.group_class """ async with self.get_client() as client: response = await client.get_group(GroupName=group_name, UserPoolId=self.user_pool_id) return self.get_group_obj(response.get('Group')) async def get_groups(self): """ Returns all groups for a user pool. Returns instances of the self.group_class. :return: list of instances """ async with self.get_client() as client: response = await client.list_groups(UserPoolId=self.user_pool_id) return [self.get_group_obj(group_data) for group_data in response.get('Groups')] PK!..mandate/aws_srp.pyimport base64 import binascii import datetime import hashlib import hmac import re import aioboto3 import os import six from .exceptions import ForceChangePasswordException # https://github.com/aws/amazon-cognito-identity-js/blob/master/src/AuthenticationHelper.js#L22 n_hex = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + \ '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + \ 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + \ 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + \ 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + \ 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + \ '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + \ '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + \ 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + \ 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + \ '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + \ 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + \ 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + \ 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + \ 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + \ '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF' # https://github.com/aws/amazon-cognito-identity-js/blob/master/src/AuthenticationHelper.js#L49 g_hex = '2' info_bits = bytearray('Caldera Derived Key', 'utf-8') def hash_sha256(buf): """AuthenticationHelper.hash""" a = hashlib.sha256(buf).hexdigest() return (64 - len(a)) * '0' + a def hex_hash(hex_string): return hash_sha256(bytearray.fromhex(hex_string)) def hex_to_long(hex_string): return int(hex_string, 16) def long_to_hex(long_num): return '%x' % long_num def get_random(nbytes): random_hex = binascii.hexlify(os.urandom(nbytes)) return hex_to_long(random_hex) def pad_hex(long_int): """ Converts a Long integer (or hex string) to hex format padded with zeroes for hashing :param {Long integer|String} long_int Number or string to pad. :return {String} Padded hex string. """ if not isinstance(long_int, six.string_types): hash_str = long_to_hex(long_int) else: hash_str = long_int if len(hash_str) % 2 == 1: hash_str = '0%s' % hash_str elif hash_str[0] in '89ABCDEFabcdef': hash_str = '00%s' % hash_str return hash_str def compute_hkdf(ikm, salt): """ Standard hkdf algorithm :param {Buffer} ikm Input key material. :param {Buffer} salt Salt value. :return {Buffer} Strong key material. @private """ prk = hmac.new(salt, ikm, hashlib.sha256).digest() info_bits_update = info_bits + bytearray(chr(1), 'utf-8') hmac_hash = hmac.new(prk, info_bits_update, hashlib.sha256).digest() return hmac_hash[:16] def calculate_u(big_a, big_b): """ Calculate the client's value U which is the hash of A and B :param {Long integer} big_a Large A value. :param {Long integer} big_b Server B value. :return {Long integer} Computed U value. """ u_hex_hash = hex_hash(pad_hex(big_a) + pad_hex(big_b)) return hex_to_long(u_hex_hash) class AWSSRP(object): NEW_PASSWORD_REQUIRED_CHALLENGE = 'NEW_PASSWORD_REQUIRED' PASSWORD_VERIFIER_CHALLENGE = 'PASSWORD_VERIFIER' def __init__(self, username, password, pool_id, client_id, pool_region=None, client=None, client_secret=None): if pool_region is not None and client is not None: raise ValueError("pool_region & client shouldn't both be specified" " (region should be passed to the boto3 client" " instead)") self.username = username self.password = password self.pool_id = pool_id self.client_id = client_id self.client_secret = client_secret self.client = client if client else aioboto3.client( 'cognito-idp', region_name=pool_region ) self.big_n = hex_to_long(n_hex) self.g = hex_to_long(g_hex) self.k = hex_to_long(hex_hash('00' + n_hex + '0' + g_hex)) self.small_a_value = self.generate_random_small_a() self.large_a_value = self.calculate_a() def generate_random_small_a(self): """ helper function to generate a random big integer :return {Long integer} a random value. """ random_long_int = get_random(128) return random_long_int % self.big_n def calculate_a(self): """ Calculate the client's public value A = g^a%N with the generated random number a :param {Long integer} a Randomly generated small A. :return {Long integer} Computed large A. """ big_a = pow(self.g, self.small_a_value, self.big_n) # safety check if (big_a % self.big_n) == 0: raise ValueError('Safety check for A failed') return big_a def get_password_authentication_key(self, username, password, server_b_value, salt): """ Calculates the final hkdf based on computed S value, and computed U value and the key :param {String} username Username. :param {String} password Password. :param {Long integer} server_b_value Server B value. :param {Long integer} salt Generated salt. :return {Buffer} Computed HKDF value. """ u_value = calculate_u(self.large_a_value, server_b_value) if u_value == 0: raise ValueError('U cannot be zero.') username_password = '%s%s:%s' % (self.pool_id.split('_')[1], username, password) username_password_hash = hash_sha256(username_password.encode('utf-8')) x_value = hex_to_long(hex_hash(pad_hex(salt) + username_password_hash)) g_mod_pow_xn = pow(self.g, x_value, self.big_n) int_value2 = server_b_value - self.k * g_mod_pow_xn s_value = pow(int_value2, self.small_a_value + u_value * x_value, self.big_n) hkdf = compute_hkdf(bytearray.fromhex(pad_hex(s_value)), bytearray.fromhex(pad_hex(long_to_hex(u_value)))) return hkdf def get_auth_params(self): auth_params = {'USERNAME': self.username, 'SRP_A': long_to_hex(self.large_a_value)} if self.client_secret is not None: auth_params.update({ "SECRET_HASH": self.get_secret_hash( self.username, self.client_id, self.client_secret )}) return auth_params @staticmethod def get_secret_hash(username, client_id, client_secret): message = bytearray(username + client_id, 'utf-8') hmac_obj = hmac.new(bytearray(client_secret, 'utf-8'), message, hashlib.sha256) return base64.b64encode(hmac_obj.digest()).decode('utf-8') def process_challenge(self, challenge_parameters): user_id_for_srp = challenge_parameters['USER_ID_FOR_SRP'] salt_hex = challenge_parameters['SALT'] srp_b_hex = challenge_parameters['SRP_B'] secret_block_b64 = challenge_parameters['SECRET_BLOCK'] # re strips leading zero from a day number (required by AWS Cognito) timestamp = re.sub(r" 0(\d) ", r" \1 ", datetime.datetime.utcnow().strftime ("%a %b %d %H:%M:%S UTC %Y")) hkdf = self.get_password_authentication_key(user_id_for_srp, self.password, hex_to_long(srp_b_hex), salt_hex) secret_block_bytes = base64.standard_b64decode(secret_block_b64) msg = bytearray(self.pool_id.split('_')[1], 'utf-8') + \ bytearray(user_id_for_srp, 'utf-8') + \ bytearray(secret_block_bytes) + bytearray(timestamp, 'utf-8') hmac_obj = hmac.new(hkdf, msg, digestmod=hashlib.sha256) signature_string = base64.standard_b64encode(hmac_obj.digest()) response = {'TIMESTAMP': timestamp, 'USERNAME': user_id_for_srp, 'PASSWORD_CLAIM_SECRET_BLOCK': secret_block_b64, 'PASSWORD_CLAIM_SIGNATURE': signature_string.decode('utf-8')} if self.client_secret is not None: response.update({ "SECRET_HASH": self.get_secret_hash(self.username, self.client_id, self.client_secret)}) return response async def authenticate_user(self, client=None): boto_client = self.client or client auth_params = self.get_auth_params() async with boto_client as client: response = await client.initiate_auth( AuthFlow='USER_SRP_AUTH', AuthParameters=auth_params, ClientId=self.client_id ) if response['ChallengeName'] == self.PASSWORD_VERIFIER_CHALLENGE: challenge_response = self.process_challenge( response['ChallengeParameters']) tokens = await client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName=self.PASSWORD_VERIFIER_CHALLENGE, ChallengeResponses=challenge_response) if tokens.get('ChallengeName') == \ self.NEW_PASSWORD_REQUIRED_CHALLENGE: raise ForceChangePasswordException ('Change password before authenticating') return tokens else: raise NotImplementedError('The %s challenge is not supported' % response['ChallengeName']) async def set_new_password_challenge(self, new_password, client=None): boto_client = self.client or client auth_params = self.get_auth_params() async with boto_client as client: response = await client.initiate_auth( AuthFlow='USER_SRP_AUTH', AuthParameters=auth_params, ClientId=self.client_id ) if response['ChallengeName'] == self.PASSWORD_VERIFIER_CHALLENGE: challenge_response = self.process_challenge( response['ChallengeParameters']) tokens = await client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName=self.PASSWORD_VERIFIER_CHALLENGE, ChallengeResponses=challenge_response) if tokens['ChallengeName'] == \ self.NEW_PASSWORD_REQUIRED_CHALLENGE: challenge_response = { 'USERNAME': auth_params['USERNAME'], 'NEW_PASSWORD': new_password } new_password_response = await\ client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName=self.NEW_PASSWORD_REQUIRED_CHALLENGE, Session=tokens['Session'], ChallengeResponses=challenge_response) return new_password_response return tokens else: raise NotImplementedError('The %s challenge is not supported' % response['ChallengeName']) PK!N722mandate/exceptions.pyclass WarrantException(Exception): """Base class for all Warrant exceptions""" class ForceChangePasswordException(WarrantException): """Raised when the user is forced to change their password""" class TokenVerificationException(WarrantException): """Raised when token verification fails."""PK![rrmandate/groupobj/__init__.pyclass GroupObj(object): def __init__(self, group_data, cognito_obj): """ :param group_data: a dictionary with information about a group :param cognito_obj: an instance of the Cognito class """ self._data = group_data self._cognito = cognito_obj self.group_name = self._data.pop('GroupName', None) self.description = self._data.pop('Description', None) self.creation_date = self._data.pop('CreationDate', None) self.last_modified_date = self._data.pop('LastModifiedDate', None) self.role_arn = self._data.pop('RoleArn', None) self.precedence = self._data.pop('Precedence', None) def __unicode__(self): return self.group_name def __repr__(self): return '<{class_name}: {uni}>'.format( class_name=self.__class__.__name__, uni=self.__unicode__()) PK!n33mandate/userobj/__init__.pyfrom mandate.utils import cognito_to_dict class UserObj(object): def __init__(self, username, attribute_list, cognito_obj, metadata=None, attr_map=None): """ :param username: :param attribute_list: :param metadata: Dictionary of User metadata """ self.username = username self.pk = username self._cognito = cognito_obj self._attr_map = {} if attr_map is None else attr_map self._data = cognito_to_dict(attribute_list, self._attr_map) self.sub = self._data.pop('sub', None) self.email_verified = self._data.pop('email_verified', None) self.phone_number_verified = self._data.pop( 'phone_number_verified', None) self._metadata = {} if metadata is None else metadata def __repr__(self): return '<{class_name}: {uni}>'.format( class_name=self.__class__.__name__, uni=self.__unicode__()) def __unicode__(self): return self.username def __getattr__(self, name): if name in list(self.__dict__.get('_data', {}).keys()): return self._data.get(name) if name in list(self.__dict__.get('_metadata', {}).keys()): return self._metadata.get(name) def __setattr__(self, name, value): if name in list(self.__dict__.get('_data', {}).keys()): self._data[name] = value else: super(UserObj, self).__setattr__(name, value) def save(self, admin=False): if admin: self._cognito.admin_update_profile(self._data, self._attr_map) return self._cognito.update_profile(self._data, self._attr_map) def delete(self, admin=False): if admin: self._cognito.admin_delete_user() return self._cognito.delete_user() PK!&yymandate/utils/__init__.pyimport ast def cognito_to_dict(attr_list, attr_map=None): if attr_map is None: attr_map = {} attr_dict = dict() for a in attr_list: name = a.get('Name') value = a.get('Value') if value in ['true', 'false']: value = ast.literal_eval(value.capitalize()) name = attr_map.get(name, name) attr_dict[name] = value return attr_dict def dict_to_cognito(attributes, attr_map=None): """ :param attributes: Dictionary of User Pool attribute names/values :return: list of User Pool attribute formatted dicts: {'Name': , 'Value': } """ if attr_map is None: attr_map = {} for k, v in attr_map.items(): if v in attributes.keys(): attributes[k] = attributes.pop(v) return [{'Name': key, 'Value': value} for key, value in attributes.items()] PK!;U],],mandate-0.2.4.dist-info/LICENSE Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK!HڽTUmandate-0.2.4.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HJ0yv mandate-0.2.4.dist-info/METADATAVmo6_qC>,9K0AڵA4hC18tPFRva}wd9"3`["s^d‹N=B8Rhhu'Ϣ,]Oԭu ++ -,/W\Koxb)aFC**΍WZ}ΔW"n._|r})jG H xcD7 %ڍK!~=$%FZZtd)ӓ3{sr!ldʚ%y=<+8v/ɭ(Ks t^SPۜO'OO?Y> iƛ=#q$jS@`rz$Gq&Ud",k ?ǹE=ORSw@yDѥ<=5J8`@Ȍ 1_'%3[9Jຐ9 9L) $ѺPʬzOZvaCu8Vk+b[/;^m_%J8BIYt{{0%b% *cLfԎY/`q#ԼnK,F3>&09BSo6WBrF=ajO~ʘj?MS,1Iθ8.EuۚL426܊xdFP!g,eKRsGh<¦]H[•5nѴ9ppurva"sސ~ӮţFPs&JnwO)ЌS{hݾڐZ+[LZt`0C.+сk\uvꎕ`jg$_h,5ָ[ǘ{Ţ vA$/*G`Ek`kyZ w3hG@ !!mLH\Jܷ :sc*H\ Q$f5޲î3^cZhZgb j@Rw]p<*[#()88'^ ݛ .KpHZel,rbAc?5d.C.(YƮ ;ٛo)+ &Mkk~æ!.-3ڰYXt5a,Pb݆#nIņ_6/;k<6rEcWd})umLIjlA֥0Aa) v> š2.yv-4f;f?|x gB7iD:9۷\ٟfqFe[Aao \d u>:؝v?p)MwU7`a``rף0Qy 2RHDPK!Hsmandate-0.2.4.dist-info/RECORDuvPy 2@8AP@ LX4 M:>up5ֿwUiga+؇Y4Ur1O"cYKߓrڻ,k_VMReGJ%jyk`kil'A了8XٜdM Kq\,թ݌w& 5/co !1慝zh8kn~rlvxˌo蓹^`VcC8xCoȄ|#si֤3mUL<{)MiyX91{XtAn.z=Qv$!ᬅ[в<օV|b+bER(NNn' iP!<˵=-479C,Pٷ`dǀw*&,je< 봤̰"~跦AR%ވo|\  3V/|r!iy [@4, A>PK!`YYmandate/__init__.pyPK!..Ymandate/aws_srp.pyPK!N722mandate/exceptions.pyPK![rrmandate/groupobj/__init__.pyPK!n33.mandate/userobj/__init__.pyPK!&yymandate/utils/__init__.pyPK!;U],],Jmandate-0.2.4.dist-info/LICENSEPK!HڽTUmandate-0.2.4.dist-info/WHEELPK!HJ0yv smandate-0.2.4.dist-info/METADATAPK!Hs'mandate-0.2.4.dist-info/RECORDPK E