def update_cognito_user_attributes(self, attribute_dictionary): custom_attributes = ["partner_id", "language", 'camp_notice_period'] attribute_list = [] for key, value in attribute_dictionary.items(): if value is not None: if key not in custom_attributes: attribute_list.append({'Name': key, 'Value': value}) else: attribute_list.append({ 'Name': "custom:" + key, 'Value': value }) if len(attribute_list) == 0: raise ValidationError("error.update_user_attributes.failed") client = boto3.client("cognito-idp") try: client.admin_update_user_attributes(UserPoolId=cognito_userpool_id, Username=self.sub(), UserAttributes=attribute_list) except Exception as e: log.exception( "Failed to update_cognito_user_attributes, error.profile.update, AWS Exception: {}" .format(e)) raise ValidationError("error.update_user_attributes.failed")
def create_weeks(period): """ Values for since 1w - last week - timedelta(weeks=1) 2w - last two weeks - timedelta(weeks=12) 4w - last four weeks - timedelta(weeks=4) 1m - last month - timedelta(weeks=4) 1q - last quarter - timedelta(weeks=12) 1y - last year - timedelta(weeks=52) """ if period is None: raise ValidationError( "Invalid syntax for 'since': Expected number followed by w|m|q|y ") if period.endswith('w'): weeks = 1 elif period.endswith('m'): weeks = 4 elif period.endswith('q'): weeks = 12 elif period.endswith('y'): weeks = 52 else: raise ValidationError( "Invalid syntax for 'period': Expected number followed by w|m|q|y " ) return weeks
def create_user(username, password, name, group): """ Create user and add him to the specifed group """ if not username: raise ValidationError("error.create_user.invalid_user") if not password: raise ValidationError("error.create_user.invalid_password") if not name: raise ValidationError("error.create_user.invalid_name") if not group: raise ValidationError("error.create_user.invalid_group") client = boto3.client("cognito-idp") # check if group exists or through exception try: client.get_group(UserPoolId=cognito_userpool_id, GroupName=group) except Exception as e: log.exception( "Failed to get_group, error.create_user.invalid_group, AWS Exception: {}" .format(e)) raise ValidationError("error.create_user.invalid_group") # here I am using warrant library because I found it easier than boto3 cognito = Cognito(cognito_userpool_id, cognito_app_client_id) cognito.add_base_attributes(name=name) # Register the user using warrant try: register_res = cognito.register(username, password) except ClientError as e: if "Username should be an email." in e.response["Error"]['Message']: raise ValidationError("error.create_user.invalid_user") elif "An account with the given email already exists." in e.response[ "Error"]['Message']: raise ValidationError("error.create_user.already_exists") elif "Password did not conform with policy" in e.response["Error"][ 'Message']: raise ValidationError("error.create_user.invalid_password") else: log.exception( "Failed to register a user, error.create_user.failed, AWS Exception: {}" .format(e)) raise ValidationError("error.create_user.failed") # add user to the group using boto3 library try: client.admin_add_user_to_group(UserPoolId=cognito_userpool_id, Username=username, GroupName=group) except Exception as e: log.exception( "Failed to add to a group, error.create_user.addtogroup.failed, AWS Exception: {}" .format(e)) raise ValidationError("error.create_user.addtogroup.failed") return register_res
def confirm_user(username, con_code): if not username: raise ValidationError("error.confirm_user.invalid_username") if not con_code: raise ValidationError("error.confirm_user.invalid_confirmation_code") # here I am using warrant library because I found it easier than boto3 cognito = Cognito(cognito_userpool_id, cognito_app_client_id) try: cognito.confirm_sign_up(confirmation_code=con_code, username=username) except Exception as e: raise ValidationError("error.confirm_user.failed")
def __init__(self, jwt=None, partner_id=None, name=None, email=None, admin=False, username=None): if jwt is None: self._partner_id = partner_id self._name = name self._email = email self._admin = admin self._username = username else: self._jwt = jwt if 'email' in jwt: self._email = jwt['email'] else: self._email = None if 'name' in jwt: self._name = jwt['name'] else: self._name = None if 'username' in jwt: self._username = jwt['username'] else: self._username = None if 'sub' in jwt: self._sub = jwt['sub'] else: self._sub = None if GROUPS_KEY in jwt: groups = jwt[GROUPS_KEY] if len(groups) == 0: raise ValidationError( 'Invalid jwt, no group membership could be determined') if ADMIN_GROUP in groups: self._admin = True else: self._admin = False if len(groups) == 1: self._partner_id = groups[0] else: # in case we have an fd-admin associated with a partner group if ADMIN_GROUP in groups: groups.remove(ADMIN_GROUP) self._partner_id = groups[ 0] # don't allow more than one partner id else: raise ValidationError( 'Invalid jwt, no group membership could be determined')
def initiate_forgot_password(username): if not username: raise ValidationError( "error.initiate_forgot_password.invalid_username") user_cognito = Cognito(cognito_userpool_id, cognito_app_client_id, username=username) try: user_cognito.initiate_forgot_password() except Exception as e: raise ValidationError( "error.initiate_forgot_password.invalid_username")
def get_date_since(since): weeks = create_weeks(since) number_str = since[:-1] if not number_str.isdigit(): raise ValidationError( "Invalid syntax for 'since': Expected number followed by w|m|q|y ") total_weeks = weeks * int(number_str) return approx_date_time( datetime.now(timezone.utc) - timedelta(weeks=total_weeks))
def confirm_forgot_password(username, confirmation_code, new_password): if not username: raise ValidationError("error.confirm_forgot_password.invalid_user") if not confirmation_code: raise ValidationError( "error.confirm_forgot_password.invalid_confirmation_code") if not new_password: raise ValidationError( "error.confirm_forgot_password.invalid_new_password") user_cognito = Cognito(cognito_userpool_id, cognito_app_client_id, username=username) try: user_cognito.confirm_forgot_password(confirmation_code, new_password) except Exception as e: if "Password does not conform to policy" in str(e): raise ValidationError( "error.confirm_forgot_password.invalid_new_password") else: raise ValidationError("error.confirm_forgot_password.failed")
def fetch_cognito_user_attributes(self): client = boto3.client("cognito-idp") try: response = client.admin_get_user(UserPoolId=cognito_userpool_id, Username=self.sub()) except Exception as e: log.exception( "Failed to fetch_cognito_user_attributes, error.profile.fetch, AWS Exception: {}" .format(e)) raise ValidationError("error.fetch_user_attributes.failed") for attribute in response['UserAttributes']: if attribute['Name'].startswith('custom:'): setattr(self, "_" + attribute['Name'][7:], attribute['Value']) else: setattr(self, "_" + attribute['Name'], attribute['Value'])