Пример #1
0
def create_user():
    from api_gateway.serverdb import add_user, User, Role, initialize_default_resources_admin, \
        initialize_default_resources_guest
    from sqlalchemy_utils import database_exists, create_database

    if not database_exists(db.engine.url):
        create_database(db.engine.url)
    db.create_all()

    # alembic_cfg = Config(api_gateway.config.Config.ALEMBIC_CONFIG, ini_section="walkoff",
    #                      attributes={'configure_logger': False})
    #
    # # This is necessary for a flask database
    # connection = db.engine.connect()
    # context = MigrationContext.configure(connection)
    # script = ScriptDirectory.from_config(alembic_cfg)
    # context.stamp(script, "head")

    # Setup admin and guest roles
    initialize_default_resources_admin()
    initialize_default_resources_guest()

    # Setup admin user
    admin_role = Role.query.filter_by(id=1).first()
    admin_user = User.query.filter_by(username="******").first()
    if not admin_user:
        add_user(username='******', password='******', roles=[1])
    elif admin_role not in admin_user.roles:
        admin_user.roles.append(admin_role)

    db.session.commit()
Пример #2
0
def test_refresh_with_blacklisted_token(api_gateway, serverdb):
    user = add_user(username='******', password='******')
    header = {'content-type': "application/json"}
    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username='******', password='******')),
                                headers=header)

    key = json.loads(response.get_data(as_text=True))
    token = key['refresh_token']
    serverdb.session.delete(user)
    serverdb.session.commit()

    headers = {'Authorization': 'Bearer {}'.format(token)}
    api_gateway.post('/api/auth/refresh',
                     content_type="application/json",
                     headers=headers)
    # first api post places user on Blacklist, second one used for failure verification
    refresh = api_gateway.post('/api/auth/refresh',
                               content_type="application/json",
                               headers=headers)
    response = json.loads(refresh.get_data(as_text=True))

    assert refresh.status_code == 401
    assert response == {'error': 'Token is revoked'}
Пример #3
0
def test_update_active_with_admin_user(api_gateway, token, serverdb):
    user = add_user('guest', 'guest', ['guest'])
    data = {'id': user.id, 'active': False}
    headers = {'Authorization': 'Bearer {}'.format(token['access_token'])}
    response = api_gateway.put(f'/api/users/{user.id}', headers=headers, content_type='application/json',
                               data=json.dumps(data))
    assert response.status_code == 200
    assert user.active is False
Пример #4
0
def create_user():
    from api_gateway.serverdb import add_user, User, Role, initialize_default_resources_admin, \
        initialize_default_resources_internal_user, \
        initialize_default_resources_workflow_developer, \
        initialize_default_resources_workflow_operator
    from sqlalchemy_utils import database_exists, create_database

    if not database_exists(db.engine.url):
        create_database(db.engine.url)
    db.create_all()

    # alembic_cfg = Config(api_gateway.config.Config.ALEMBIC_CONFIG, ini_section="walkoff",
    #                      attributes={'configure_logger': False})
    #
    # # This is necessary for a flask database
    # connection = db.engine.connect()
    # context = MigrationContext.configure(connection)
    # script = ScriptDirectory.from_config(alembic_cfg)
    # context.stamp(script, "head")

    # Setup admin, internal, workflow_developer, and workflow_operator roles
    initialize_default_resources_admin()
    initialize_default_resources_internal_user()
    initialize_default_resources_workflow_developer()
    initialize_default_resources_workflow_operator()

    # Setup admin user
    admin_role = Role.query.filter_by(id=1).first()
    admin_user = User.query.filter_by(username="******").first()
    if not admin_user:
        add_user(username='******', password='******', roles=[1])
    elif admin_role not in admin_user.roles:
        admin_user.roles.append(admin_role)

    # Setup internal user
    internal_role = Role.query.filter(Role.id == 2).first()
    internal_user = User.query.filter_by(username="******").first()
    if not internal_user:
        with open(config.INTERNAL_KEY_PATH, 'rb') as f:
            key = f.read()
            internal_pass = str(key)
        add_user(username='******', password=internal_pass, roles=[2])
    elif internal_role not in internal_user.roles:
        internal_user.roles.append(internal_role)

    db.session.commit()
Пример #5
0
def test_login_updates_user(api_gateway, serverdb):
    uname = "newestuser2"
    user = add_user(username=uname, password='******')
    header = {'content-type': 'application/json'}
    api_gateway.post('/api/auth',
                     data=json.dumps(dict(username=uname, password='******')),
                     headers=header)
    check = serverdb.session.query(User).filter_by(
        username=uname).first().login_count
    assert check == 1
Пример #6
0
def test_delete_current_user(api_gateway):
    user = add_user('test', 'test')
    user.set_roles({1})
    response = api_gateway.post('/api/auth', content_type="application/json",
                                data=json.dumps(dict(username='******', password='******')))
    key = json.loads(response.get_data(as_text=True))
    access_token = key['access_token']
    headers = {'Authorization': 'Bearer {}'.format(access_token)}
    response2 = api_gateway.delete(f'/api/users/{user.id}', headers=headers)
    assert response2.status_code == 403
Пример #7
0
def test_login_inactive_user(api_gateway, serverdb):
    user = add_user(username="******", password="******")
    user.active = False
    serverdb.session.commit()
    FAILURE = 401
    header = {'content-type': 'application/json'}
    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username="******",
                                         password='******')),
                                headers=header)
    assert response.status_code == FAILURE
Пример #8
0
def test_update_different_user_not_admin(api_gateway):
    user = add_user('guest', 'guest', ['guest'])
    response = api_gateway.post('/api/auth', content_type="application/json",
                                data=json.dumps(dict(username='******', password='******')))
    key = json.loads(response.get_data(as_text=True))
    access_token = key['access_token']
    headers = {'Authorization': 'Bearer {}'.format(access_token)}
    admin = User.query.filter_by(username='******').first()
    data = {'id': admin.id, 'username': '******'}
    response = api_gateway.put(f'/api/users/{admin.id}', headers=headers, content_type='application/json',
                               data=json.dumps(data))
    assert response.status_code == 403
Пример #9
0
def test_update_active_with_guest_user(api_gateway, serverdb):
    user = add_user('guest', 'guest', ['guest'])
    response = api_gateway.post('/api/auth', content_type="application/json",
                                data=json.dumps(dict(username='******', password='******')))
    key = json.loads(response.get_data(as_text=True))
    access_token = key['access_token']
    headers = {'Authorization': 'Bearer {}'.format(access_token)}
    data = {'id': user.id, 'active': False}
    response = api_gateway.put(f'/api/users/{user.id}', headers=headers, content_type='application/json',
                               data=json.dumps(data))
    assert response.status_code == 200
    assert user.active is True
Пример #10
0
def test_logout_mismatched_tokens(api_gateway, serverdb):
    header = {'content-type': "application/json"}
    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username='******', password='******')),
                                headers=header)
    key = json.loads(response.get_data(as_text=True))
    headers = {'Authorization': 'Bearer {}'.format(key['access_token'])}

    add_user(username='******', password='******')

    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username='******', password='******')),
                                headers=header)
    key = json.loads(response.get_data(as_text=True))
    token = key['refresh_token']

    response = api_gateway.post('/api/auth/logout',
                                headers=headers,
                                content_type="application/json",
                                data=json.dumps(dict(refresh_token=token)))
    assert response.status_code == 400
    assert len(BlacklistedToken.query.all()) == 0
Пример #11
0
def test_logout_updates_user(api_gateway, serverdb):
    user = add_user('testlogout', 'test')
    header = {'content-type': "application/json"}
    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username='******',
                                         password='******')),
                                headers=header)
    key = json.loads(response.get_data(as_text=True))
    access_token = key['access_token']
    refresh_token = key['refresh_token']
    headers = {'Authorization': 'Bearer {}'.format(access_token)}
    api_gateway.post('/api/auth/logout',
                     headers=headers,
                     content_type="application/json",
                     data=json.dumps(dict(refresh_token=refresh_token)))
    assert user.login_count == 0
Пример #12
0
def test_refresh_deactivated_user(api_gateway, serverdb):
    FAILURE = 401
    user = add_user(username='******', password='******')
    header = {'content-type': "application/json"}
    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username='******', password='******')),
                                headers=header)
    key = json.loads(response.get_data(as_text=True))
    token = key['refresh_token']
    headers = {'Authorization': 'Bearer {}'.format(token)}
    user.active = False
    serverdb.session.commit()
    refresh = api_gateway.post('/api/auth/refresh',
                               content_type="application/json",
                               headers=headers)
    assert refresh.status_code == FAILURE
Пример #13
0
def create_user():
    data = request.get_json()
    username = data['username']
    if not User.query.filter_by(username=username).first():
        user = add_user(username=username, password=data['password'])

        if 'roles' in data or 'active' in data:
            role_update_user_fields(data, user)

        db.session.commit()
        current_app.logger.info(f'User added: {user.as_json()}')
        return user.as_json(), HTTPStatus.CREATED
    else:
        current_app.logger.warning(
            f'Cannot create user {username}. User already exists.')
        return Problem.from_crud_resource(
            HTTPStatus.BAD_REQUEST, 'user', 'create',
            f'User with username {username} already exists')
Пример #14
0
def test_refresh_invalid_user_blacklists_token(api_gateway, serverdb):
    user = add_user(username='******', password='******')
    header = {'content-type': "application/json"}
    response = api_gateway.post('/api/auth',
                                data=json.dumps(
                                    dict(username='******', password='******')),
                                headers=header)
    key = json.loads(response.get_data(as_text=True))
    token = key['refresh_token']
    serverdb.session.delete(user)
    serverdb.session.commit()
    headers = {'Authorization': 'Bearer {}'.format(token)}
    refresh = api_gateway.post('/api/auth/refresh',
                               content_type="application/json",
                               headers=headers)
    assert refresh.status_code == 401

    token = decode_token(token)

    tokens = BlacklistedToken.query.filter_by(jti=token['jti']).all()
    assert len(tokens) == 1