def test_session_deletion(app): """Test that a user/client is no longer authenticated when its session is deleted via `delete_session`.""" InvenioAccounts(app) app.register_blueprint(blueprint) user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) assert len(user.active_sessions) == 1 saved_sid_s = flask.session.sid_s delete_session(saved_sid_s) # The user now has no active sessions assert len(testutils.get_kvsession_keys()) == 0 assert len(user.active_sessions) == 0 query = _datastore.db.session.query(SessionActivity) assert query.count() == 0 # After deleting the session, the client is not authenticated assert not testutils.client_authenticated(client) # A new session is created in the kv-sessionstore, but its # sid_s is different and the user is not authenticated with it. assert len(testutils.get_kvsession_keys()) == 1 assert not flask.session.sid_s == saved_sid_s assert not testutils.client_authenticated(client)
def test_sessionstore_default_ttl_secs(app): """Test the `default_ttl_secs` field for simplekv sessionstore backends using the TimeToLive-mixin (http://pythonhosted.org/simplekv/index.html#simplekv.TimeToLiveMixin)""" ttl_seconds = 1 ttl_delta = datetime.timedelta(0, ttl_seconds) sessionstore = RedisStore(redis.StrictRedis()) sessionstore.default_ttl_secs = ttl_seconds ext = InvenioAccounts(app, sessionstore=sessionstore) app.register_blueprint(blueprint) # Verify that the backend supports ttl assert ext.sessionstore.ttl_support user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) sid = testutils.unserialize_session(flask.session.sid_s) while not sid.has_expired(ttl_delta): pass # When we get here the session should have expired. # But the client is still authenticated. assert testutils.client_authenticated(client)
def test_session_ttl(app): """Test actual/working session expiration/TTL settings.""" ttl_seconds = 1 # Set ttl to "0 days, 1 seconds" ttl_delta = datetime.timedelta(0, ttl_seconds) ext = InvenioAccounts(app) app.register_blueprint(blueprint) assert ext.sessionstore.ttl_support # _THIS_ is what flask_kvsession uses to determine default ttl # sets default ttl to `ttl_seconds` seconds app.config['PERMANENT_SESSION_LIFETIME'] = ttl_delta assert app.permanent_session_lifetime.total_seconds() == ttl_seconds user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) assert len(testutils.get_kvsession_keys()) == 1 sid = testutils.unserialize_session(flask.session.sid_s) testutils.let_session_expire() assert sid.has_expired(ttl_delta) assert not testutils.client_authenticated(client) # Expired sessions are automagically removed from the sessionstore # Although not _instantly_. while len(testutils.get_kvsession_keys()) > 0: pass assert len(testutils.get_kvsession_keys()) == 0
def test_user_login(app): """Test users' high-level login process.""" with app.app_context(): user = create_test_user('*****@*****.**') with app.test_client() as client: login_user_via_view(client, user.email, user.password_plaintext) assert client_authenticated(client)
def test_load_user_collections_called_upon_login(app_client, users): login_user_via_view(app_client, email='*****@*****.**', password='******', login_url='/login/?local=1') with app_client.get('/'): assert session['restricted_collections']
def test_repeated_login_session_population(app): """Verify session population on repeated login.""" with app.app_context(): user = testutils.create_test_user('*****@*****.**') query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys()) with app.test_client() as client: # After logging in, there should be one session in the kv-store and # one SessionActivity testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) query = db.session.query(SessionActivity) assert query.count() == 1 assert len(app.kvsession_store.keys()) == 1 first_login_session_id = app.kvsession_store.keys()[0] # Sessions are not deleted upon logout client.get(flask_security.url_for_security('logout')) assert len(app.kvsession_store.keys()) == 1 query = db.session.query(SessionActivity) assert query.count() == 1 assert len(app.kvsession_store.keys()) == 1 # Session id doesn't change after logout assert first_login_session_id == app.kvsession_store.keys()[0] # After logging out and back in, the inital session id in the # sessionstore should be updated, and there should be two # SessionActivity entries (the old one and the regenerated). testutils.login_user_via_view(client, user=user) query = db.session.query(SessionActivity) assert query.count() == 2 assert len(app.kvsession_store.keys()) == 1 assert first_login_session_id != app.kvsession_store.keys()[0]
def test_repeated_login_session_population(app): """Verify that the number of SessionActivity entries match the number of sessions in the kv-store, when logging in with one user.""" InvenioAccounts(app) app.register_blueprint(blueprint) user = testutils.create_test_user() query = _datastore.db.session.query(SessionActivity) assert query.count() == len(testutils.get_kvsession_keys()) with app.test_client() as client: # After logging in, there should be one session in the kv-store and # one SessionActivity testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) query = _datastore.db.session.query(SessionActivity) assert query.count() == 1 assert query.count() == len(testutils.get_kvsession_keys()) # Sessions are not deleted upon logout client.get(flask_security.url_for_security('logout')) assert len(testutils.get_kvsession_keys()) == 1 query = _datastore.db.session.query(SessionActivity) assert query.count() == len(testutils.get_kvsession_keys()) # After logging out and back in, the number of sessions correspond to # the number of SessionActivity entries. testutils.login_user_via_view(client, user=user) query = _datastore.db.session.query(SessionActivity) assert query.count() == len(testutils.get_kvsession_keys())
def test_repeated_login_session_population(app): """Verify session population on repeated login. Check that the number of SessionActivity entries match the number of sessions in the kv-store, when logging in with one user. """ with app.app_context(): user = testutils.create_test_user('*****@*****.**') query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys()) with app.test_client() as client: # After logging in, there should be one session in the kv-store and # one SessionActivity testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) query = db.session.query(SessionActivity) assert query.count() == 1 assert query.count() == len(app.kvsession_store.keys()) # Sessions are not deleted upon logout client.get(flask_security.url_for_security('logout')) assert len(app.kvsession_store.keys()) == 1 query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys()) # After logging out and back in, the number of sessions correspond # to the number of SessionActivity entries. testutils.login_user_via_view(client, user=user) query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys())
def test_pdf_extractor_test_page(client, user): """Test the PDF extractor test page.""" login_user_via_view(client, email=user['email'], password='******') response = client.get('/pdf-extractor/test') assert response.status_code == 200 assert 'PDF metadata extraction' in str(response.data)
def test_session_ttl(app): """Test actual/working session expiration/TTL settings.""" if type(app.kvsession_store) is not RedisStore: pytest.skip('TTL support needed, this test requires Redis.') ttl_seconds = 1 # Set ttl to "0 days, 1 seconds" ttl_delta = datetime.timedelta(0, ttl_seconds) assert app.kvsession_store.ttl_support # _THIS_ is what flask_kvsession uses to determine default ttl # sets default ttl to `ttl_seconds` seconds app.config['PERMANENT_SESSION_LIFETIME'] = ttl_delta assert app.permanent_session_lifetime.total_seconds() == ttl_seconds with app.app_context(): user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) assert len(app.kvsession_store.keys()) == 1 sid = testutils.unserialize_session(flask.session.sid_s) time.sleep(ttl_seconds + 1) assert sid.has_expired(ttl_delta) assert not testutils.client_authenticated(client) # Expired sessions are automagically removed from the sessionstore # Although not _instantly_. while len(app.kvsession_store.keys()) > 0: pass assert len(app.kvsession_store.keys()) == 0
def test_repeated_login_session_population(app): """Verify session population on repeated login.""" with app.app_context(): user = testutils.create_test_user('*****@*****.**') query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys()) with app.test_client() as client: # After logging in, there should be one session in the kv-store and # one SessionActivity testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) query = db.session.query(SessionActivity) assert query.count() == 1 assert len(app.kvsession_store.keys()) == 1 first_login_session_id = app.kvsession_store.keys()[0] # SessionActivity is deleted upon logout client.get(flask_security.url_for_security('logout')) query = db.session.query(SessionActivity) assert query.count() == 0 # Session id changes after logout assert len(app.kvsession_store.keys()) == 1 assert first_login_session_id != app.kvsession_store.keys()[0] # After logging out and back in, the should be one # SessionActivity entry. testutils.login_user_via_view(client, user=user) query = db.session.query(SessionActivity) assert query.count() == 1 assert len(app.kvsession_store.keys()) == 1 assert first_login_session_id != app.kvsession_store.keys()[0]
def test_session_deletion(app): """Test if user is not authenticated when session is deleted.""" with app.app_context(): user = testutils.create_test_user('*****@*****.**') with app.test_client() as client: testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) assert len(user.active_sessions) == 1 saved_sid_s = session.sid_s delete_session(saved_sid_s) db.session.commit() # The user now has no active sessions assert len(app.kvsession_store.keys()) == 0 assert len(user.active_sessions) == 0 query = db.session.query(SessionActivity) assert query.count() == 0 # After deleting the session, the client is not authenticated assert not testutils.client_authenticated(client) # A new session is created in the kv-sessionstore, but its # sid_s is different and the user is not authenticated with it. assert len(app.kvsession_store.keys()) == 1 assert not session.sid_s == saved_sid_s assert not testutils.client_authenticated(client)
def test_session_deletion(app): """Test that a user/client is no longer authenticated when its session is deleted via `delete_session`.""" with app.app_context(): user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) assert len(user.active_sessions) == 1 saved_sid_s = flask.session.sid_s delete_session(saved_sid_s) db.session.commit() # The user now has no active sessions assert len(app.kvsession_store.keys()) == 0 assert len(user.active_sessions) == 0 query = db.session.query(SessionActivity) assert query.count() == 0 # After deleting the session, the client is not authenticated assert not testutils.client_authenticated(client) # A new session is created in the kv-sessionstore, but its # sid_s is different and the user is not authenticated with it. assert len(app.kvsession_store.keys()) == 1 assert not flask.session.sid_s == saved_sid_s assert not testutils.client_authenticated(client)
def test_sessionstore_default_ttl_secs(app): """Test the `default_ttl_secs` field for simplekv sessionstore. See http://simplekv.readthedocs.io/index.html#simplekv.TimeToLiveMixin. """ if type(app.kvsession_store) is not RedisStore: pytest.skip('TTL support needed, this test requires Redis.') ttl_seconds = 3 ttl_delta = datetime.timedelta(0, ttl_seconds) sessionstore = app.kvsession_store sessionstore.default_ttl_secs = ttl_seconds # Verify that the backend supports ttl assert sessionstore.ttl_support app.kvsession_store = sessionstore with app.app_context(): user = testutils.create_test_user('*****@*****.**') with app.test_client() as client: testutils.login_user_via_view(client, user=user) sid = testutils.unserialize_session(session.sid_s) while not sid.has_expired(ttl_delta): pass # When we get here the session should have expired. # But the client is still authenticated. assert testutils.client_authenticated(client)
def test_session_ttl(app): """Test actual/working session expiration/TTL settings.""" if type(app.kvsession_store) is not RedisStore: pytest.skip('TTL support needed, this test requires Redis.') ttl_seconds = 3 # Set ttl to "0 days, 1 seconds" ttl_delta = datetime.timedelta(0, ttl_seconds) assert app.kvsession_store.ttl_support # _THIS_ is what flask_kvsession uses to determine default ttl # sets default ttl to `ttl_seconds` seconds app.config['PERMANENT_SESSION_LIFETIME'] = ttl_delta assert app.permanent_session_lifetime.total_seconds() == ttl_seconds with app.app_context(): user = testutils.create_test_user('*****@*****.**') with app.test_client() as client: testutils.login_user_via_view(client, user=user) assert len(app.kvsession_store.keys()) == 1 sid = testutils.unserialize_session(session.sid_s) time.sleep(ttl_seconds + 1) assert sid.has_expired(ttl_delta) assert not testutils.client_authenticated(client) # Expired sessions are automagically removed from the sessionstore # Although not _instantly_. while len(app.kvsession_store.keys()) > 0: pass assert len(app.kvsession_store.keys()) == 0
def test_sessionstore_default_ttl_secs(app): """Test the `default_ttl_secs` field for simplekv sessionstore. See http://pythonhosted.org/simplekv/index.html#simplekv.TimeToLiveMixin. """ if type(app.kvsession_store) is not RedisStore: pytest.skip('TTL support needed, this test requires Redis.') ttl_seconds = 1 ttl_delta = datetime.timedelta(0, ttl_seconds) sessionstore = app.kvsession_store sessionstore.default_ttl_secs = ttl_seconds # Verify that the backend supports ttl assert sessionstore.ttl_support app.kvsession_store = sessionstore with app.app_context(): user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) sid = testutils.unserialize_session(flask.session.sid_s) while not sid.has_expired(ttl_delta): pass # When we get here the session should have expired. # But the client is still authenticated. assert testutils.client_authenticated(client)
def test_repeated_login_session_population(app): """Verify session population on repeated login. Check that the number of SessionActivity entries match the number of sessions in the kv-store, when logging in with one user. """ with app.app_context(): user = testutils.create_test_user() query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys()) with app.test_client() as client: # After logging in, there should be one session in the kv-store and # one SessionActivity testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) query = db.session.query(SessionActivity) assert query.count() == 1 assert query.count() == len(app.kvsession_store.keys()) # Sessions are not deleted upon logout client.get(flask_security.url_for_security('logout')) assert len(app.kvsession_store.keys()) == 1 query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys()) # After logging out and back in, the number of sessions correspond # to the number of SessionActivity entries. testutils.login_user_via_view(client, user=user) query = db.session.query(SessionActivity) assert query.count() == len(app.kvsession_store.keys())
def test_read_deleted_record(client, location, minimal_record, users, es_clear): """Test read a deleted record.""" user1 = users['user1'] # Login user1 login_user_via_view(client, email=user1['email'], password=user1['password'], login_url='/login') # Create dummy record to test delete response = client.post(LIST_RECORDS_API_URL, headers=HEADERS, data=json.dumps(minimal_record)) assert response.status_code == 201 recid = response.json["pid"] # Publish it response = client.post(DRAFT_ACTION_API_URL.format(recid, "publish"), headers=HEADERS) assert response.status_code == 200 # Delete the record response = client.delete(SINGLE_RECORD_API_URL.format(recid), headers=HEADERS) assert response.status_code == 204 # Read the deleted record response = client.get(SINGLE_RECORD_API_URL.format(recid), headers=HEADERS) assert response.status_code == 410 assert response.json['message'] == "The record has been deleted."
def test_files_permission_factory(app, client, admin): """Test files permission factory.""" app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=True) assert files_permission_factory().can() app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=False) login_user_via_view(client, email=admin['email'], password='******') assert files_permission_factory().can()
def test_create_test_user_defaults(app): """Test the default values for testutils.py:create_test_user.""" with app.app_context(): user = testutils.create_test_user('*****@*****.**') with app.test_client() as client: testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client)
def test_admin_permission_factory(app, client, superuser): """Test factory for admin access permission.""" app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=True) assert admin_permission_factory(None).can() app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=False) login_user_via_view(client, email=superuser['email'], password='******') assert admin_permission_factory(None).can()
def test_create_test_user_defaults(app): """Test the default values for testutils.py:create_test_user.""" with app.app_context(): user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client)
def test_unknown_permission_factory(app, client, superuser, document): """Test unknown permission factory""" app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=True) assert record_permission_factory(document, 'unknown').can() app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=False) assert not record_permission_factory(document, 'unknown').can() login_user_via_view(client, email=superuser['email'], password='******') assert not record_permission_factory(document, 'unknown').can()
def test_list_permission_factory(app, client, superuser): """Test list permission factory.""" app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=True) assert record_permission_factory(action='list').can() app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=False) assert not record_permission_factory(action='list').can() login_user_via_view(client, email=superuser['email'], password='******') assert record_permission_factory(action='list').can()
def test_login_user_via_view(app): """Test the login-via-view function/hack.""" email = '*****@*****.**' password = '******' with app.app_context(): user = testutils.create_test_user(email, password) with app.test_client() as client: assert not testutils.client_authenticated(client) testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client)
def test_create_test_user_defaults(app): """Test the default values for testutils.py:create_test_user.""" ext = InvenioAccounts(app) app.register_blueprint(blueprint) with app.app_context(): user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client)
def test_wiki_edit_ui_permission(client, user, admin): """Test wiki edit ui permission.""" # No access login_user_via_view(client, email=user['email'], password='******') assert not wiki_edit_permission() # Logout user client.get(url_for_security('logout')) # OK user has access login_user_via_view(client, email=admin['email'], password='******') assert wiki_edit_permission()
def test_inspire_search_filter(app, restricted_record, users, user_info, total_count, es_filter): """Test default inspire search filter.""" with app.test_client() as client: if user_info: login_user_via_view(client, email=user_info['email'], password=user_info['password'], login_url='/login/?local=1') # Doing a client request creates a request context that allows the # assert to correctly use the logged in user. client.get('/search') assert LiteratureSearch().to_dict()['query']['bool']['filter'] == es_filter assert LiteratureSearch().count() == total_count
def test_legacy_user_login(app): """Test legacy users' high-level login process.""" with app.app_context(): user = create_legacy_user() old_hashval = user.password with app.test_client() as client: login_user_via_view(client, user.email, user.password_plaintext) # Verify user is authenticated assert client_authenticated(client) # Verify password hash is upgraded ds = flask.current_app.extensions['security'].datastore user2 = ds.find_user(email=user.email) assert old_hashval != user2.password
def test_login_user_via_view(app): """Test the login-via-view function/hack.""" InvenioAccounts(app) app.register_blueprint(blueprint) email = '*****@*****.**' password = '******' with app.app_context(): user = testutils.create_test_user(email, password) with app.test_client() as client: assert not testutils.client_authenticated(client) testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client)
def test_inspire_search_filter(app, app_client, user_info, total_count, es_filter): """Test default inspire search filter.""" if user_info: login_user_via_view(app_client, email=user_info['email'], password=user_info['password'], login_url='/login/?local=1') # Doing a client request creates a request context that allows the # assert to correctly use the logged in user. app_client.get('/search') assert LiteratureSearch().to_dict()['query']['bool'][ 'filter'] == es_filter assert LiteratureSearch().count() == total_count
def test_inspire_search_filter_restricted_collection(app, app_client, user_info, total_count, es_filter): """Test default inspire search filter.""" if user_info: login_user_via_view(app_client, email=user_info['email'], password=user_info['password'], login_url='/login/?local=1') # Doing a client request creates a request context that allows the # assert to correctly use the logged in user. app_client.get('/search?cc=HERMES Internal Notes') assert LiteratureSearch().to_dict()['query']['bool'][ 'filter'] == es_filter assert LiteratureSearch().count() == total_count
def test_set_app_session_ttl(app): """Test testutils.py:set_app_session_ttl.""" InvenioAccounts(app) app.register_blueprint(blueprint) ttl_seconds = 1 ttl_delta = testutils.set_app_session_ttl(app, ttl_seconds) assert ttl_delta == datetime.timedelta(0, ttl_seconds) user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) login_at = datetime.datetime.utcnow() sid = testutils.unserialize_session(flask.session.sid_s) while not sid.has_expired(ttl_delta): pass assert not testutils.client_authenticated(client)
def test_permission_links(client, db, published_json): """Test the links when affected by permissions.""" # We test that only admins get the "delete" link (according to our policy) pid_value = published_json["pid"] user = create_test_user("*****@*****.**") db.session.add(ActionUsers(action='admin-access', user=user)) db.session.commit() login_user_via_view(client, email=user.email, password=user.password_plaintext, login_url='/login') response = client.get(f"/rdm-records/{pid_value}", headers=HEADERS) read_record_links = response.json["links"] assert (f"https://localhost:5000/api/rdm-records/{pid_value}" == read_record_links["delete"])
def test_get_user_by_current_user(app, client, user_without_role, user): """Test getting a user with email taken from logged user.""" record = UserRecord.get_user_by_current_user(current_user) assert record is None login_user_via_view(client, email=user_without_role.email, password='******') record = UserRecord.get_user_by_current_user(current_user) assert record is None client.get(url_for_security('logout')) login_user_via_view(client, email=user['email'], password='******') record = UserRecord.get_user_by_current_user(current_user) assert 'email' in record assert user['email'] == '*****@*****.**'
def test_deactivate_user(app): """Test deactivation of users.""" with app.app_context(): user_bob = testutils.create_test_user(email='*****@*****.**', password='******', active=True) with app.test_client() as client: assert user_bob.active assert not testutils.client_authenticated(client) testutils.login_user_via_view(client, user_bob.email, user_bob.password_plaintext) assert testutils.client_authenticated(client) # Now we deactivate Bob. # `deactivate_user` returns True if a change was made. _datastore.deactivate_user(user_bob) db.session.commit() assert not testutils.client_authenticated(client)
def test_has_superuser_access(app, client, user_without_role, superuser): """Test if user has a super admin access.""" app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=True) assert has_superuser_access() app.config.update(SONAR_APP_DISABLE_PERMISSION_CHECKS=False) login_user_via_view(client, email=user_without_role.email, password='******') assert not has_superuser_access() client.get(url_for_security('logout')) login_user_via_view(client, email=superuser['email'], password='******') assert has_superuser_access()
def test_login_listener(app): """Test login listener.""" with app.app_context(): with app.test_client() as client: user = testutils.create_test_user() # The SessionActivity table is initially empty query = db.session.query(SessionActivity) assert query.count() == 0 testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client) # After logging in, a SessionActivity has been created # corresponding to the user's session. query = db.session.query(SessionActivity) assert query.count() == 1 session_entry = query.first() assert session_entry.user_id == user.id assert session_entry.sid_s == flask.session.sid_s
def test_links_html_link_missing(api, es, location, fake_schemas, users, json_headers): """Test if the html key from links is missing.""" api.config['DEPOSIT_UI_ENDPOINT'] = None with api.test_request_context(): with api.test_client() as client: login_user_via_view( client, users[0]['email'], 'tester', ) # try create deposit as logged in user res = client.post(url_for('invenio_deposit_rest.depid_list'), data=json.dumps({}), headers=json_headers) assert res.status_code == 201 data = json.loads(res.data.decode('utf-8')) links = data['links'] assert 'html' not in links
def test_repeated_login_session_expiration(app): """Test that a new session (with a different sid_s) is created when logging in again after a previous session has expired.""" ttl_seconds = 1 ttl_delta = datetime.timedelta(0, ttl_seconds) app.config['PERMANENT_SESSION_LIFETIME'] = ttl_delta with app.app_context(): user = testutils.create_test_user() with app.test_client() as client: testutils.login_user_via_view(client, user=user) first_sid_s = flask.session.sid_s time.sleep(ttl_seconds + 1) assert not testutils.client_authenticated(client) app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta( 0, 10000) testutils.login_user_via_view(client, user=user) second_sid_s = flask.session.sid_s assert not first_sid_s == second_sid_s
def test_login_multiple_clients_single_user_session_population(app): """Test session population/creation from multiple clients for same user.""" with app.app_context(): user = testutils.create_test_user('*****@*****.**') client_count = 3 clients = [app.test_client() for _ in range(client_count)] sid_s_list = [] for c in clients: with c as client: testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) sid_s_list.append(session.sid_s) client.get(flask_security.url_for_security('logout')) assert not testutils.client_authenticated(client) # There is now `client_count` existing sessions and SessionActivity # entries assert len(app.kvsession_store.keys()) == client_count query = db.session.query(SessionActivity) assert query.count() == client_count assert len(user.active_sessions) == client_count
def test_admin_sessions(app, admin_view, users): """Test flask-admin session.""" with app.test_request_context(): index_view_url = url_for('sessionactivity.index_view') delete_view_url = url_for('sessionactivity.delete_view') with app.test_client() as client: res = client.get(index_view_url) assert res.status_code == 200 # simulate login as user 1 datastore = app.extensions['security'].datastore login_user_via_view(client=client, email=users[0]['email'], password=users[0]['password']) from flask import session sid_s = session.sid_s # and try to delete own session sid_s: FAILS res = client.post( delete_view_url, data={'id': sid_s}, follow_redirects=True) assert res.status_code == 200 sessions = SessionActivity.query.all() assert len(sessions) == 1 assert sessions[0].sid_s == sid_s with app.test_client() as client: # simulate login as user 2 login_user_via_view(client=client, email=users[1]['email'], password=users[1]['password']) new_sid_s = session.sid_s sessions = SessionActivity.query.all() assert len(sessions) == 2 all_sid_s = [session.sid_s for session in sessions] assert sorted([sid_s, new_sid_s]) == sorted(all_sid_s) # and try to delete a session of another user: WORKS res = client.post( delete_view_url, data={'id': sid_s}, follow_redirects=True) sessions = SessionActivity.query.all() assert len(sessions) == 1 assert sessions[0].sid_s == new_sid_s
def test_login_listener(app): """Test sessions.py:login_listener""" InvenioAccounts(app) app.register_blueprint(blueprint) user = testutils.create_test_user() # The SessionActivity table is initially empty query = _datastore.db.session.query(SessionActivity) assert query.count() == 0 with app.test_client() as client: testutils.login_user_via_view(client, user.email, user.password_plaintext) assert testutils.client_authenticated(client) # After logging in, a SessionActivity has been created corresponding # to the user's session. query = _datastore.db.session.query(SessionActivity) assert query.count() == 1 session_entry = query.first() assert session_entry.user_id == user.id assert session_entry.sid_s == flask.session.sid_s
def test_login_multiple_clients_single_user_session_population(app): """Test session population/creation when logging in as the same user from multiple clients.""" InvenioAccounts(app) app.register_blueprint(blueprint) user = testutils.create_test_user() client_count = 3 clients = [app.test_client() for _ in range(client_count)] sid_s_list = [] for c in clients: with c as client: testutils.login_user_via_view(client, user=user) assert testutils.client_authenticated(client) sid_s_list.append(flask.session.sid_s) response = client.get(flask_security.url_for_security('logout')) assert not testutils.client_authenticated(client) # There is now `client_count` existing sessions and SessionActivity # entries assert len(testutils.get_kvsession_keys()) == client_count query = _datastore.db.session.query(SessionActivity) assert query.count() == client_count assert len(user.active_sessions) == client_count