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)
Exemple #2
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)
Exemple #3
0
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)
Exemple #4
0
def test_client_authenticated(app):
    """Test for testutils.py:client_authenticated(client).

    We want to verify that it doesn't return True when the client isn't
    authenticated/logged in."""
    ext = InvenioAccounts(app)
    # Required for the test app/templates
    app.register_blueprint(blueprint)

    email = '*****@*****.**'
    password = '******'

    with app.app_context():
        change_password_url = url_for_security('change_password')
        login_url = url_for_security('login')

    with app.test_client() as client:
        # At this point we should not be authenticated/logged in as a user
        assert flask_login.current_user.is_anonymous
        assert not testutils.client_authenticated(client,
                                                  test_url=change_password_url)

        # Test HTTP status code of view when not logged in.
        response = client.get(change_password_url)
        assert response.status_code == 302
        assert change_password_url not in response.location
        assert login_url in response.location

        # Once more, following redirects.
        response = client.get(change_password_url, follow_redirects=True)
        assert response.status_code == 200
        assert response.location is None

        # Create a user manually directly in the datastore
        ext.datastore.create_user(email=email,
                                  password=encrypt_password(password))
        db.session.commit()

        # Manual login via view
        response = client.post(login_url,
                               data={
                                   'email': email,
                                   'password': password
                               },
                               environ_base={'REMOTE_ADDR': '127.0.0.1'})

        # Client gets redirected after logging in
        assert response.status_code == 302
        assert testutils.client_authenticated(client)
        assert flask_login.current_user.is_authenticated
        # `is_authenticated` returns True as long as the user object
        # isn't anonymous, i.e. it's an actual user.

        response = client.get(change_password_url)
        assert response.status_code == 200
        response = client.get(change_password_url, follow_redirects=True)
        assert response.status_code == 200
def test_client_authenticated(app):
    """Test for testutils.py:client_authenticated(client).

    We want to verify that it doesn't return True when the client isn't
    authenticated/logged in.
    """
    ds = app.extensions["security"].datastore
    email = "*****@*****.**"
    password = "******"

    with app.app_context():
        change_password_url = url_for_security("change_password")
        login_url = url_for_security("login")

        with app.test_client() as client:
            # At this point we should not be authenticated/logged in as a user
            # assert flask_login.current_user.is_anonymous
            assert not testutils.client_authenticated(
                client, test_url=change_password_url)

            # Test HTTP status code of view when not logged in.
            response = client.get(change_password_url)
            assert response.status_code == 302
            assert change_password_url not in response.location
            assert login_url in response.location

            # Once more, following redirects.
            response = client.get(change_password_url, follow_redirects=True)
            assert response.status_code == 200
            assert response.location is None

            # Create a user manually directly in the datastore
            ds.create_user(email=email, password=hash_password(password))
            db.session.commit()

            # Manual login via view
            response = client.post(
                login_url,
                data={
                    "email": email,
                    "password": password
                },
                environ_base={"REMOTE_ADDR": "127.0.0.1"},
            )

            # Client gets redirected after logging in
            assert response.status_code == 302
            assert testutils.client_authenticated(client)
            assert flask_login.current_user.is_authenticated
            # `is_authenticated` returns True as long as the user object
            # isn't anonymous, i.e. it's an actual user.

            response = client.get(change_password_url)
            assert response.status_code == 200
            response = client.get(change_password_url, follow_redirects=True)
            assert response.status_code == 200
def test_client_authenticated(app):
    """Test for testutils.py:client_authenticated(client).

    We want to verify that it doesn't return True when the client isn't
    authenticated/logged in."""
    ext = InvenioAccounts(app)
    # Required for the test app/templates
    app.register_blueprint(blueprint)

    email = '*****@*****.**'
    password = '******'

    with app.app_context():
        change_password_url = url_for_security('change_password')
        login_url = url_for_security('login')

    with app.test_client() as client:
        # At this point we should not be authenticated/logged in as a user
        assert flask_login.current_user.is_anonymous
        assert not testutils.client_authenticated(
            client, test_url=change_password_url)

        # Test HTTP status code of view when not logged in.
        response = client.get(change_password_url)
        assert response.status_code == 302
        assert change_password_url not in response.location
        assert login_url in response.location

        # Once more, following redirects.
        response = client.get(change_password_url, follow_redirects=True)
        assert response.status_code == 200
        assert response.location is None

        # Create a user manually directly in the datastore
        ext.datastore.create_user(email=email,
                                  password=encrypt_password(password))
        db.session.commit()

        # Manual login via view
        response = client.post(login_url,
                               data={'email': email, 'password': password},
                               environ_base={'REMOTE_ADDR': '127.0.0.1'})

        # Client gets redirected after logging in
        assert response.status_code == 302
        assert testutils.client_authenticated(client)
        assert flask_login.current_user.is_authenticated
        # `is_authenticated` returns True as long as the user object
        # isn't anonymous, i.e. it's an actual user.

        response = client.get(change_password_url)
        assert response.status_code == 200
        response = client.get(change_password_url, follow_redirects=True)
        assert response.status_code == 200
def test_login_user_via_session(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_session(client, email=user.email)
            assert testutils.client_authenticated(client)
def test_login_user_via_session(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_session(client, email=user.email)
            assert testutils.client_authenticated(client)
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_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)
Exemple #11
0
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)
Exemple #12
0
def test_headers_info(app, users):
    """Test if session and user id is set response header."""
    u = users[0]
    url = url_for_security('change_password')
    app.config['ACCOUNTS_USERINFO_HEADERS'] = True
    with app.app_context():
        with app.test_client() as client:
            assert not testutils.client_authenticated(client)
            testutils.login_user_via_session(client, email=u['email'])
            assert testutils.client_authenticated(client)
            response = client.get(url)
            cookie = requests.utils.dict_from_cookiejar(client.cookie_jar)
            assert response.headers['X-Session-ID'] == \
                cookie['session'].split('.')[0]
            assert int(response.headers['X-User-ID']) == u['id']
Exemple #13
0
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_create_sessions_for_user(app):
    """Test testutils.py:create_sessions_for_user."""
    InvenioAccounts(app)
    app.register_blueprint(blueprint)
    user = testutils.create_test_user()
    assert len(user.active_sessions) == 0
    res = testutils.create_sessions_for_user(user=user)
    assert len(user.active_sessions) == 1
    assert res['user'] == user

    # Cookie is retrievable from the client.
    sid_s = user.active_sessions[0].sid_s
    client_one = res['clients'][0]
    cookie = testutils.get_cookie_from_client(client_one)
    assert sid_s == testutils.get_sid_s_from_cookie(cookie)

    # The client is still authenticated
    with client_one as client:
        assert testutils.client_authenticated(client)

    # Repeated calls create new sessions.
    res = testutils.create_sessions_for_user(app=app, user=user)
    assert len(user.active_sessions) == 2
    assert len(res['clients']) == 1

    # No user argument (fails b/c `create_test_user` has static default values)
    # res = testutils.create_sessions_for_user(app=app)
    # user_two = res['user']
    # assert not user_two == user
    # assert len(user_two.active_sessions) == 1

    n = 3
    res = testutils.create_sessions_for_user(user=user, n=n)
    assert len(user.active_sessions) == 2+n
    assert len(res['clients']) == n
Exemple #15
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())
Exemple #16
0
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
Exemple #17
0
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)
Exemple #18
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]

            # 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]
Exemple #19
0
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_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_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."""
    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_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)
Exemple #24
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_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_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
Exemple #27
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_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)
Exemple #29
0
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 = 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
Exemple #31
0
def test_create_sessions_for_user(app):
    """Test testutils.py:create_sessions_for_user."""
    InvenioAccounts(app)
    app.register_blueprint(blueprint)
    user = testutils.create_test_user()
    assert len(user.active_sessions) == 0
    res = testutils.create_sessions_for_user(user=user)
    assert len(user.active_sessions) == 1
    assert res['user'] == user

    # Cookie is retrievable from the client.
    sid_s = user.active_sessions[0].sid_s
    client_one = res['clients'][0]
    cookie = testutils.get_cookie_from_client(client_one)
    assert sid_s == testutils.get_sid_s_from_cookie(cookie)

    # The client is still authenticated
    with client_one as client:
        assert testutils.client_authenticated(client)

    # Repeated calls create new sessions.
    res = testutils.create_sessions_for_user(app=app, user=user)
    assert len(user.active_sessions) == 2
    assert len(res['clients']) == 1

    # No user argument (fails b/c `create_test_user` has static default values)
    # res = testutils.create_sessions_for_user(app=app)
    # user_two = res['user']
    # assert not user_two == user
    # assert len(user_two.active_sessions) == 1

    n = 3
    res = testutils.create_sessions_for_user(user=user, n=n)
    assert len(user.active_sessions) == 2 + n
    assert len(res['clients']) == n
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)
Exemple #33
0
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_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_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_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
Exemple #37
0
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
Exemple #38
0
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_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
Exemple #40
0
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_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
Exemple #42
0
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
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)
Exemple #44
0
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_headers_info(app, users):
    """Test if session and user id is set response header."""
    u = users[0]
    url = url_for_security('change_password')
    with app.app_context():
        with app.test_client() as client:
            response = client.get(url)
            # Not logged in, so only session id available
            assert not testutils.client_authenticated(client)
            assert 'X-Session-ID' in response.headers
            assert 'X-User-ID' not in response.headers
            # Login
            testutils.login_user_via_session(client, email=u['email'])
            response = client.get(url)
            cookie = requests.utils.dict_from_cookiejar(client.cookie_jar)
            assert response.headers['X-Session-ID'] == \
                cookie['session'].split('.')[0]
            assert int(response.headers['X-User-ID']) == u['id']
def test_headers_info(app, users):
    """Test if session and user id is set response header."""
    u = users[0]
    url = url_for_security("change_password")
    with app.app_context():
        with app.test_client() as client:
            response = client.get(url)
            # Not logged in, so only session id available
            assert not testutils.client_authenticated(client)
            assert "X-Session-ID" in response.headers
            assert "X-User-ID" not in response.headers
            # Login
            testutils.login_user_via_session(client, email=u["email"])
            response = client.get(url)
            cookie = requests.utils.dict_from_cookiejar(client.cookie_jar)
            assert response.headers["X-Session-ID"] == cookie["session"].split(
                ".")[0]
            assert int(response.headers["X-User-ID"]) == u["id"]
Exemple #47
0
def test_headers_info(app, users):
    """Test if session and user id is set response header."""
    u = users[0]
    url = url_for_security('change_password')
    with app.app_context():
        with app.test_client() as client:
            response = client.get(url)
            # Not logged in, so only session id available
            assert not testutils.client_authenticated(client)
            assert 'X-Session-ID' in response.headers
            assert 'X-User-ID' not in response.headers
            # Login
            testutils.login_user_via_session(client, email=u['email'])
            response = client.get(url)
            cookie = requests.utils.dict_from_cookiejar(client.cookie_jar)
            assert response.headers['X-Session-ID'] == \
                cookie['session'].split('.')[0]
            assert int(response.headers['X-User-ID']) == u['id']
Exemple #48
0
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 == session.sid_s
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
Exemple #50
0
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."""
    InvenioAccounts(app)
    app.register_blueprint(blueprint)
    ttl_seconds = 1
    ttl_delta = datetime.timedelta(0, ttl_seconds)
    app.config['PERMANENT_SESSION_LIFETIME'] = ttl_delta

    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
        testutils.let_session_expire()
        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_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
Exemple #52
0
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_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