def create_user_account(user=None): """Create a new user account. :param user: A dictionary with the arguments to be passed to the Django's create_user helper function. """ if user is None: email = f'{uuid4()}@example.com' user = create_user_account({ 'email': email, 'password': gen_password(), 'username': email, }) else: user = copy.deepcopy(user) return user
def test_create_with_email(): """Ensure user accounts can be created with username, email and password. :id: 003ac47f-9946-4ffe-b49d-732dbffe1cfc :description: Ensure an user account can be created by an super user account with username, email and password. :steps: With an authenticated superuser, send a post request to /auth/user/create/ with an username, email and password. :expectedresults: The server returns a 201 response with the information of the created user. The information should include the information passed as payload to the create request and also an ID should be created. """ create_user_account({ 'email': '*****@*****.**', 'username': uuid4(), 'password': gen_password() })
def test_create(): """Ensure user accounts can be created with username and password. :id: 5099a61d-7aa6-4c1b-8408-d030f210cd08 :description: Ensure an user account can be created by an super user account with only username and password. :steps: With an authenticated superuser, send a post request to /auth/user/create/ with an username and password. :expectedresults: The server returns a 201 response with the information of the created user. The information should include the information passed as payload to the create request and also an ID should be created. """ create_user_account({ 'email': '', 'password': gen_password(), 'username': uuid4(), })
def get_auth(user=None): """Get authentication for given user to use with requests. For example:: usr = create_user_account({ 'email': '', 'password': gen_password(), 'username': uuid4(), }) auth = get_auth(username, pwd) client = api.Client(authenticate=False) client.get(urls.AUTH_ME, auth=auth) If no user is provided, a new user is created. This is useful when you need to make authenticated requests as a regular user, but never need to use the user information for anything else. Example:: from integrade.tests import urls client = api.client(authenticate=False) auth1 = get_auth() client.get(urls.CLOUD_ACCOUNT, auth=auth1) :returns: instance of api.TokenAuth """ if not user: email = f'{uuid4()}@example.com' password = gen_password() user = create_user_account({ 'email': email, 'password': password, 'username': email, }) print(f'USER {email} {password}') client = api.Client(authenticate=False) response = client.post(urls.AUTH_TOKEN_CREATE, user) assert response.status_code == 200 json_response = response.json() assert 'auth_token' in json_response return api.TokenAuth(json_response['auth_token'])
def create_user_account(user=None): """Create a new user account. :param user: A dictionary with the arguments to be passed to the Django's create_user helper function. """ if user is None: email = f'{uuid4()}@example.com' user = create_user_account({ 'email': email, 'password': gen_password(), 'username': email, }) else: user = copy.deepcopy(user) user['id'] = injector.run_remote_python( """ from django.contrib.auth.models import User return User.objects.create_user(**user).id """, **locals()) return user
def test_gen_password(): """Test gen_password generates password with printable string chars.""" password = gen_password(30) assert len(password) == 30 assert set(password).issubset(string.printable)
def get_config(create_superuser=True, need_base_url=True): """Return a copy of the global config dictionary. This method makes use of a cache. If the cache is empty, the configuration file is parsed and the cache is populated. Otherwise, a copy of the cached configuration object is returned. :returns: A copy of the global integrade configuration object. """ global _CONFIG # pylint:disable=global-statement if _CONFIG is None: _CONFIG = {} _CONFIG['api_version'] = os.getenv('CLOUDIGRADE_API_VERSION', 'v1') _CONFIG['cloudigrade_s3_bucket'] = os.getenv('AWS_S3_BUCKET_NAME') ref_slug = os.environ.get('CI_COMMIT_REF_SLUG', '') cloudtrail_prefix = os.getenv('CLOUDTRAIL_PREFIX', f'review-{ref_slug}') # The location of the API endpoints and UI may be configured directly # with `CLOUDIGRADE_BASE_URL` -OR- we can determine a location based # on `CI_COMMIT_REF_SLUG` which comes from Gitlab CI and is our # current branch name. _CONFIG['base_url'] = os.getenv( 'CLOUDIGRADE_BASE_URL', f'review-{ref_slug}.5a9f.insights-dev.openshiftapps.com', ) _CONFIG['openshift_prefix'] = os.getenv( 'OPENSHIFT_PREFIX', f'c-review-{ref_slug[:29]}-', ) # pull all customer roles out of environ def is_role(string): return string.startswith('CLOUDIGRADE_ROLE_') def profile_name(string): return string.replace( 'CLOUDIGRADE_ROLE_', '') profiles = [{'arn': os.environ.get(role), 'name': profile_name(role)} for role in filter(is_role, os.environ.keys()) ] profiles.sort(key=lambda p: p['name']) _CONFIG['aws_profiles'] = profiles missing_config_errors = [] try: aws_image_config = get_aws_image_config() except exceptions.ConfigFileNotFoundError: aws_image_config = {} for i, profile in enumerate(_CONFIG['aws_profiles']): profile_name = profile['name'].upper() acct_arn = profile['arn'] acct_num = [ num for num in filter( str.isdigit, acct_arn.split(':'))][0] profile['account_number'] = acct_num profile['cloudtrail_name'] = f'{cloudtrail_prefix}{acct_num}' profile['access_key_id'] = os.environ.get( f'AWS_ACCESS_KEY_ID_{profile_name}') profile['images'] = aws_image_config.get('profiles', {}).get( profile_name, {}).get('images', []) if i == 0: if not profile['access_key_id']: missing_config_errors.append( f'Could not find AWS access key id for {profile_name}') if _CONFIG['base_url'] == '' and need_base_url: missing_config_errors.append( 'Could not find $CLOUDIGRADE_BASE_URL set in in' ' your environment.' ) if os.environ.get('USE_HTTPS', 'false').lower() == 'true': _CONFIG['scheme'] = 'https' else: _CONFIG['scheme'] = 'http' if os.environ.get('SSL_VERIFY', 'false').lower() == 'true': _CONFIG['ssl-verify'] = True else: _CONFIG['ssl-verify'] = False if missing_config_errors: raise exceptions.MissingConfigurationError( '\n'.join(missing_config_errors) ) super_username = os.environ.get( 'CLOUDIGRADE_USER', utils.uuid4() ) _CONFIG['super_user_name'] = super_username super_password = os.environ.get( 'CLOUDIGRADE_PASSWORD', utils.gen_password() ) _CONFIG['super_user_password'] = super_password token = os.environ.get('CLOUDIGRADE_TOKEN', False) if not token and create_superuser: try: token = injector.make_super_user( super_username, super_password) except RuntimeError as e: raise exceptions.MissingConfigurationError( 'Could not create a super user or token, error:\n' f'{repr(e)}' ) _CONFIG['superuser_token'] = token return deepcopy(_CONFIG)