Ejemplo n.º 1
0
def authenticate_user(username: str, password: str):
    user = get_user_by_name_db(username)
    if not user:
        return False
    if not verify_password(password, user.password):
        return False
    return user
Ejemplo n.º 2
0
def create_testing_keys():
    """
    Creates API keys for usage in test cases. These keys should NEVER be used for actual microservices.
    """

    # Only create an API key testing account if it doesn't exist already
    if not get_user_by_name_db('api_key_testing'):
        password = str(uuid.uuid4())
        u = User(
            username='******',
            password=get_password_hash(
                password),  # Random unguessable password
            email='*****@*****.**',
            roles=['admin'],
        )
        add_user_db(u)
    else:
        u = get_user_by_name_db('api_key_testing')

    # If keys do not already exist, create them
    if not get_api_keys_by_user_db(u):

        prediction_key_value = str(uuid.uuid4())
        training_key_value = str(uuid.uuid4())

        prediction_key = APIKeyData(
            **{
                'key': prediction_key_value,
                'type': ExternalServices.predict_microservice.name,
                'user': '******',
                'detail': 'Key For Testing ONLY',
                'enabled': True
            })

        training_key = APIKeyData(
            **{
                'key': training_key_value,
                'type': ExternalServices.train_microservice.name,
                'user': '******',
                'detail': 'Key For Testing ONLY',
                'enabled': True
            })

        add_api_key_db(prediction_key)
        add_api_key_db(training_key)
Ejemplo n.º 3
0
def add_api_key(key_owner_username: str, service: str, detail: str = ""):
    """
    Creates a new API key belonging to a user and associated with a service. This key is only able to be
    used on this specific service, and will be immediately enabled upon creation. The unique API Key string
    that is returned is used for all authentication between external services and the server.

    :param key_owner_username: Username of user who 'owns' this API Key
    :param service: dependency.ExternalService object name of microservice this key is associated with
    :param detail: (optional) A brief description of what the key is used for
    :return: {'status': 'success'} with key data if created, else {'status': 'failure'}
    """

    user = get_user_by_name_db(key_owner_username)

    if not user:
        return {
            'status': 'failure',
            'detail':
            'Desired Key owner username does not exist. Unable to create API key.',
            'username': key_owner_username
        }

    # Ensure that the service name for the key is valid
    if service not in list(ExternalServices.__members__):
        return {
            'status': 'failure',
            'detail':
            'Service specified does not exist. Unable to create API key.',
            'service': service
        }

    api_key_string = str(uuid.uuid4())

    api_key_object = APIKeyData(
        **{
            'key': api_key_string,
            'type': service,
            'user': key_owner_username,
            'detail': detail,
            'enabled': True
        })

    result = add_api_key_db(api_key_object)

    # If successful, return success message and the API key object
    if result['status'] == 'success':
        return {'status': 'success', **api_key_object.dict()}

    return {
        'status':
        'failure',
        'detail':
        'API Key Creation Database Error. Please contact an administrator.'
    }
Ejemplo n.º 4
0
def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise CredentialException()
        token_data = TokenData(username=username)
    except JWTError:
        raise CredentialException()
    user = get_user_by_name_db(username=token_data.username)
    if user is None:
        raise CredentialException()
    return user
Ejemplo n.º 5
0
def create_testing_account():
    """
    Creates an account for usage in tests. This account should never be logged into, and is only accessed by
    username in test cases
    """

    # Only create a testing account if it doesn't exist already
    if not get_user_by_name_db('testing'):
        password = str(uuid.uuid4())
        u = User(
            username='******',
            password=get_password_hash(
                password),  # Random unguessable password
            email='*****@*****.**',
            roles=['admin'],
            agency=password)

        add_user_db(u)
Ejemplo n.º 6
0
def remove_permission_from_user(username: str, role: str):
    """
    Allows administrators to remove permissions from a user account. Permissions allow for a user to access certain
    endpoints and features that are not available to the general user base.

    :param username: Username of account to modify
    :param role: dependency.Roles to remove from account, as a string
    :return: {'status': 'success'} if role modification successful, else {'status': 'failure'}
    """

    user = get_user_by_name_db(username)
    if not user:
        return {
            'status': 'failure',
            'detail': 'User does not exist. Unable to modify permissions.'
        }

    # Ensure that the role name is valid
    if role not in list(Roles.__members__):
        return {
            'status':
            'failure',
            'detail':
            'Role specified does not exist. Unable to modify permissions.'
        }

    if role not in user.roles:
        return {
            'status':
            'success',
            'detail':
            'User ' + str(username) + ' does not have role ' + str(role) +
            '. No changes made.'
        }

    user_new_role_list = user.roles.copy()
    user_new_role_list.remove(role)
    set_user_roles_db(username, user_new_role_list)
    return {
        'status': 'success',
        'detail':
        'User ' + str(username) + ' removed from role ' + str(role) + '.'
    }
Ejemplo n.º 7
0
def create_admin_account_testing():

    if get_user_by_name_db('admin'):
        return {
            'status': 'failure',
            'detail': 'Admin account already exists.',
            'account': 'Username: "******", Password: "******"'
        }

    u = User(username='******',
             password=get_password_hash('password'),
             email='*****@*****.**',
             roles=['admin'])

    add_user_db(u)

    return {
        'status': 'success',
        'detail': 'Admin account has been created.',
        'account': 'Username: "******", Password: "******"'
    }
Ejemplo n.º 8
0
def test_login():
    testing_account_password = get_user_by_name_db('testing').agency  # We store the pass in the agency ONLY for testing
    login_response = client.post("/auth/login", data={'username': '******', 'password': testing_account_password})
    assert login_response.status_code == 200
Ejemplo n.º 9
0
def override_logged_in_user():
    return get_user_by_name_db("testing")
Ejemplo n.º 10
0
def override_api_key_training():
    return get_api_keys_by_user_db(get_user_by_name_db('api_key_testing'))[1]
Ejemplo n.º 11
0
def override_api_key_prediction():
    return get_api_keys_by_user_db(get_user_by_name_db('api_key_testing'))[0]