def test_deliverability_fails(): # No MX record. domain = 'xkxufoekjvjfjeodlfmdfjcu.com' with pytest.raises(EmailUndeliverableError, match='The domain name {} does not exist'.format(domain)): validate_email_deliverability(domain, domain) # Null MX record. domain = 'example.com' with pytest.raises(EmailUndeliverableError, match='The domain name {} does not accept email'.format(domain)): validate_email_deliverability(domain, domain)
def test_deliverability_dns_timeout(): validate_email_deliverability.TEST_CHECK_TIMEOUT = True response = validate_email_deliverability('gmail.com', 'gmail.com') assert "mx" not in response assert response.get("unknown-deliverability") == "timeout" validate_email('*****@*****.**') del validate_email_deliverability.TEST_CHECK_TIMEOUT
def test_deliverability_found(): response = validate_email_deliverability('gmail.com', 'gmail.com') assert response.keys() == {'mx', 'mx-fallback'} assert response['mx-fallback'] is None assert len(response['mx']) > 1 assert len(response['mx'][0]) == 2 assert isinstance(response['mx'][0][0], int) assert response['mx'][0][1].endswith('.com')
def test_deliverability_fails(): domain = 'xkxufoekjvjfjeodlfmdfjcu.com' with pytest.raises(EmailUndeliverableError, match='The domain name {} does not exist'.format(domain)): validate_email_deliverability(domain, domain)
def test_deliverability_no_records(): assert validate_email_deliverability('example.com', 'example.com') == {'mx': [(0, '')], 'mx-fallback': None}
def create_user( # noqa: C901 password: str = None, user_roles: Union[Dict[str, str], List[Dict[str, str]], str, List[str]] = None, check_email_deliverability: bool = True, account_name: Optional[str] = None, **kwargs, ) -> User: """ Convenience wrapper to create a new User object. It hashes the password. In addition to the user, this function can create - new Role objects (if user roles do not already exist) - an Account object (if it does not exist yet) - a new DataSource object that corresponds to the user Remember to commit the session after calling this function! """ # Check necessary input explicitly before anything happens if password is None or password == "": raise InvalidFlexMeasuresUser("No password provided.") if "email" not in kwargs: raise InvalidFlexMeasuresUser("No email address provided.") email = kwargs.pop("email").strip() try: email_info = validate_email(email, check_deliverability=False) # The mx check talks to the SMTP server. During testing, we skip it because it # takes a bit of time and without internet connection it fails. if check_email_deliverability and not current_app.testing: try: validate_email_deliverability(email_info.domain, email_info["domain_i18n"]) except EmailUndeliverableError as eue: raise InvalidFlexMeasuresUser( "The email address %s does not seem to be deliverable: %s" % (email, str(eue))) except EmailNotValidError as enve: raise InvalidFlexMeasuresUser("%s is not a valid email address: %s" % (email, str(enve))) if "username" not in kwargs: username = email.split("@")[0] else: username = kwargs.pop("username").strip() # Check integrity explicitly before anything happens existing_user_by_email = User.query.filter_by(email=email).one_or_none() if existing_user_by_email is not None: raise InvalidFlexMeasuresUser("User with email %s already exists." % email) existing_user_by_username = User.query.filter_by( username=username).one_or_none() if existing_user_by_username is not None: raise InvalidFlexMeasuresUser("User with username %s already exists." % username) # check if we can link/create an account if account_name is None: raise InvalidFlexMeasuresUser( "Cannot create user without knowing the name of the account which this user is associated with." ) account = db.session.query(Account).filter_by( name=account_name).one_or_none() if account is None: print(f"Creating account {account_name} ...") account = Account(name=account_name) db.session.add(account) user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role) kwargs.update(password=hash_password(password), email=email, username=username) user = user_datastore.create_user(**kwargs) user.account = account # add roles to user (creating new roles if necessary) if user_roles: if not isinstance(user_roles, list): user_roles = [user_roles] # type: ignore for user_role in user_roles: if isinstance(user_role, dict): role = user_datastore.find_role(user_role["name"]) else: role = user_datastore.find_role(user_role) if role is None: if isinstance(user_role, dict): role = user_datastore.create_role(**user_role) else: role = user_datastore.create_role(name=user_role) user_datastore.add_role_to_user(user, role) # create data source db.session.add(DataSource(user=user)) return user
def create_user( # noqa: C901 user_roles: Union[Dict[str, str], List[Dict[str, str]], str, List[str]] = None, check_deliverability: bool = True, **kwargs) -> User: """ Convenience wrapper to create a new User object and new Role objects (if user roles do not already exist), and new DataSource object that corresponds to the user. Remember to commit the session after calling this function! """ # Check necessary input explicitly before anything happens if "email" not in kwargs: raise InvalidFlexMeasuresUser("No email address provided.") email = kwargs.pop("email").strip() try: email_info = validate_email(email, check_deliverability=False) # The mx check talks to the SMTP server. During testing, we skip it because it # takes a bit of time and without internet connection it fails. if check_deliverability and not current_app.testing: try: validate_email_deliverability(email_info.domain, email_info["domain_i18n"]) except EmailUndeliverableError as eue: raise InvalidFlexMeasuresUser( "The email address %s does not seem to be deliverable: %s" % (email, str(eue))) except EmailNotValidError as enve: raise InvalidFlexMeasuresUser("%s is not a valid email address: %s" % (email, str(enve))) if "username" not in kwargs: username = email.split("@")[0] else: username = kwargs.pop("username").strip() # Check integrity explicitly before anything happens existing_user_by_email = User.query.filter_by(email=email).one_or_none() if existing_user_by_email is not None: raise InvalidFlexMeasuresUser("User with email %s already exists." % email) existing_user_by_username = User.query.filter_by( username=username).one_or_none() if existing_user_by_username is not None: raise InvalidFlexMeasuresUser("User with username %s already exists." % username) user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role) kwargs.update(email=email, username=username) user = user_datastore.create_user(**kwargs) if user.password is None: set_random_password(user) # add roles to user (creating new roles if necessary) if user_roles: if not isinstance(user_roles, list): user_roles = [user_roles] # type: ignore for user_role in user_roles: if isinstance(user_role, dict): role = user_datastore.find_role(user_role["name"]) else: role = user_datastore.find_role(user_role) if role is None: if isinstance(user_role, dict): role = user_datastore.create_role(**user_role) else: role = user_datastore.create_role(name=user_role) user_datastore.add_role_to_user(user, role) # create data source db.session.add(DataSource(user=user)) return user