def test_session_store_stores_none_for_trading_as_if_not_present(self):
        session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            response_id="response_id",
            questionnaire_id="questionnaire_id",
            case_id="case_id",
        )
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=session_data,
                expires_at=self.expires_at,
            ).save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")

            self.assertIsNone(session_store.session_data.trad_as)
Ejemplo n.º 2
0
def app_session_store(app, mocker, session_data):
    app.permanent_session_lifetime = timedelta(seconds=1)
    store = mocker.MagicMock()
    store.session_store = SessionStore("user_ik", "pepper")
    store.expires_at = datetime.now(tz=timezone.utc) + timedelta(seconds=3)
    store.session_data = session_data
    return store
    def test_session_store_ignores_new_values_in_session_data(self):
        session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            response_id="response_id",
            questionnaire_id="questionnaire_id",
            case_id="case_id",
        )

        session_data.additional_value = "some cool new value you do not know about yet"

        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=self.session_data,
                expires_at=self.expires_at,
            ).save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")

            self.assertFalse(
                hasattr(session_store.session_data, "additional_value"))
Ejemplo n.º 4
0
class TestSubmissionPayload(AppContextTestCase):
    def setUp(self):
        super().setUp()
        self.session_data = SessionData(
            tx_id="tx_id",
            schema_name="schema_name",
            response_id="response_id",
            period_str="period_str",
            language_code="cy",
            launch_language_code="en",
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            case_id="0123456789000000",
        )
        self.session_store = SessionStore("user_ik", "pepper", "eq_session_id")
        self.expires_at = datetime.now(tzutc()) + timedelta(seconds=5)

    def test_submission_language_code_in_payload(self):
        session_store = self.session_store.create("eq_session_id", "user_id",
                                                  self.session_data,
                                                  self.expires_at)
        storage = Mock()
        storage.get_user_data = Mock(return_value=("{}", 1))

        with patch(
                "app.views.handlers.submission.get_session_store",
                return_value=session_store,
        ):
            with patch("app.views.handlers.submission.convert_answers",
                       return_value={}):
                submission_handler = SubmissionHandler(
                    QuestionnaireSchema({}), QuestionnaireStore(storage), {})
                assert (submission_handler.get_payload()
                        ["submission_language_code"] == "cy")
Ejemplo n.º 5
0
 def setUp(self):
     super().setUp()
     self.session_data = SessionData(
         tx_id="tx_id",
         schema_name="schema_name",
         response_id="response_id",
         period_str="period_str",
         language_code="cy",
         launch_language_code="en",
         survey_url=None,
         ru_name="ru_name",
         ru_ref="ru_ref",
         case_id="0123456789000000",
     )
     self.session_store = SessionStore("user_ik", "pepper", "eq_session_id")
     self.expires_at = datetime.now(tzutc()) + timedelta(seconds=5)
 def setUp(self):
     super().setUp()
     self._app.permanent_session_lifetime = timedelta(seconds=1)
     self.session_store = SessionStore("user_ik", "pepper")
     self.expires_at = datetime.utcnow() + timedelta(seconds=3)
     self.session_data = SessionData(
         tx_id="tx_id",
         schema_name="some_schema_name",
         period_str="period_str",
         language_code=None,
         launch_language_code=None,
         survey_url=None,
         ru_name="ru_name",
         ru_ref="ru_ref",
         response_id="response_id",
         case_id="case_id",
     )
def _extend_session_expiry(session_store: SessionStore) -> None:
    """
    Extends the expiration time of the session
    :param session_store:
    """
    session_timeout = cookie_session.get("expires_in")
    if session_timeout:
        new_expiration_time = datetime.now(tz=timezone.utc) + timedelta(
            seconds=session_timeout)

        # Only update expiry time if its greater than 60s different to what is currently set
        if (not session_store.expiration_time
                or (new_expiration_time -
                    session_store.expiration_time).total_seconds() > 60):
            session_store.expiration_time = new_expiration_time
            session_store.save()
            logger.debug("session expiry extended")
 def test_legacy_load(self):
     self._save_session(self.session_id,
                        self.user_id,
                        self.session_data,
                        legacy=True)
     session_store = SessionStore(self.user_ik, self.pepper,
                                  self.session_id)
     self.assertEqual(session_store.session_data.tx_id,
                      self.session_data.tx_id)
 def test_save(self):
     with self._app.test_request_context():
         self.session_store.create(
             eq_session_id="eq_session_id",
             user_id="test",
             session_data=self.session_data,
             expires_at=self.expires_at,
         ).save()
         session_store = SessionStore("user_ik", "pepper", "eq_session_id")
         self.assertEqual(session_store.session_data.tx_id, "tx_id")
Ejemplo n.º 10
0
def test_save(app, app_session_store):
    with app.test_request_context():
        app_session_store.session_store.create(
            eq_session_id="eq_session_id",
            user_id="test",
            session_data=app_session_store.session_data,
            expires_at=app_session_store.expires_at,
        ).save()
        session_store = SessionStore("user_ik", "pepper", "eq_session_id")
        assert session_store.session_data.tx_id == "tx_id"
Ejemplo n.º 11
0
def test_session_store_stores_trading_as_value_if_present(
        app, app_session_store, session_data):
    with app.test_request_context():
        app_session_store.session_store.create(
            eq_session_id="eq_session_id",
            user_id="test",
            session_data=session_data,
            expires_at=app_session_store.expires_at,
        ).save()

        session_store = SessionStore("user_ik", "pepper", "eq_session_id")

        assert hasattr(session_store.session_data, "trad_as") is True
Ejemplo n.º 12
0
def create_session_store(eq_session_id: str, user_id: str, user_ik: str,
                         session_data: str) -> None:
    pepper = current_app.eq["secret_store"].get_secret_by_name(
        "EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER")
    session_timeout_in_seconds = get_session_timeout_in_seconds(g.schema)
    expires_at = datetime.now(tz=tzutc()) + timedelta(
        seconds=session_timeout_in_seconds)

    # pylint: disable=W0212
    g._session_store = (SessionStore(user_ik,
                                     pepper).create(eq_session_id, user_id,
                                                    session_data,
                                                    expires_at).save())
    def test_add_data_to_session(self):
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=self.session_data,
                expires_at=self.expires_at,
            ).save()
            current_time = datetime.utcnow().isoformat()
            self.session_store.session_data.submitted_time = current_time
            self.session_store.save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")
            self.assertEqual(session_store.session_data.submitted_time, current_time)
Ejemplo n.º 14
0
def test_add_data_to_session(app, app_session_store):
    with app.test_request_context():
        app_session_store.session_store.create(
            eq_session_id="eq_session_id",
            user_id="test",
            session_data=app_session_store.session_data,
            expires_at=app_session_store.expires_at,
        ).save()
        display_address = "68 Abingdon Road, Goathill"
        app_session_store.session_store.session_data.display_address = display_address
        app_session_store.session_store.save()

        session_store = SessionStore("user_ik", "pepper", "eq_session_id")
        assert session_store.session_data.display_address == display_address
Ejemplo n.º 15
0
def test_load(app_session_store_encoded):
    _save_session(
        app_session_store_encoded,
        app_session_store_encoded.session_id,
        app_session_store_encoded.user_id,
        app_session_store_encoded.session_data,
    )
    session_store = SessionStore(
        app_session_store_encoded.user_ik,
        app_session_store_encoded.pepper,
        app_session_store_encoded.session_id,
    )
    assert (session_store.session_data.tx_id ==
            app_session_store_encoded.session_data.tx_id)
Ejemplo n.º 16
0
def test_session_store_stores_none_for_trading_as_if_not_present(
        app, app_session_store, session_data):
    session_data.trad_as = None
    with app.test_request_context():
        app_session_store.session_store.create(
            eq_session_id="eq_session_id",
            user_id="test",
            session_data=session_data,
            expires_at=app_session_store.expires_at,
        ).save()

        session_store = SessionStore("user_ik", "pepper", "eq_session_id")

        assert session_store.session_data.trad_as is None
Ejemplo n.º 17
0
def create_session_store(eq_session_id: str, user_id: str, user_ik: str,
                         session_data: SessionData) -> None:
    secret_store = current_app.eq["secret_store"]  # type: ignore
    pepper = secret_store.get_secret_by_name(
        "EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER")
    session_timeout_in_seconds = get_session_timeout_in_seconds(g.schema)
    expires_at = datetime.now(tz=tzutc()) + timedelta(
        seconds=session_timeout_in_seconds)

    # pylint: disable=protected-access, assigning-non-slot
    g._session_store = (SessionStore(user_ik,
                                     pepper).create(eq_session_id, user_id,
                                                    session_data,
                                                    expires_at).save())
Ejemplo n.º 18
0
def test_session_store_ignores_new_values_in_session_data(
        app, app_session_store, session_data):
    session_data.additional_value = "some cool new value you do not know about yet"

    with app.test_request_context():
        app_session_store.session_store.create(
            eq_session_id="eq_session_id",
            user_id="test",
            session_data=app_session_store.session_data,
            expires_at=app_session_store.expires_at,
        ).save()

        session_store = SessionStore("user_ik", "pepper", "eq_session_id")

        assert hasattr(session_store.session_data, "additional_value") is False
Ejemplo n.º 19
0
def get_session_store() -> Union[SessionStore, None]:
    if USER_IK not in cookie_session or EQ_SESSION_ID not in cookie_session:
        return None

    # Sets up a single SessionStore instance per request context.
    store = g.get("_session_store")

    if store is None:
        pepper = current_app.eq["secret_store"].get_secret_by_name(
            "EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER")
        store = g._session_store = SessionStore(cookie_session[USER_IK],
                                                pepper,
                                                cookie_session[EQ_SESSION_ID])

    return store if store.session_data else None
    def test_submission_language_code_uses_default_language_if_session_data_language_none(
        self, ):
        self.session_data.language_code = None
        self.session_data.launch_language_code = None
        session_store = SessionStore("user_ik", "pepper",
                                     "eq_session_id").create(
                                         "eq_session_id", "user_id",
                                         self.session_data, self.expires_at)

        with patch(
                "app.views.handlers.submission.get_session_store",
                return_value=session_store,
        ):
            submission_handler = SubmissionHandler(
                QuestionnaireSchema({}), self.questionnaire_store_mock(), {})
            assert submission_handler.get_payload(
            )["submission_language_code"] == "en"
Ejemplo n.º 21
0
class TestAuthenticator(AppContextTestCase):  # pylint: disable=too-many-public-methods
    def setUp(self):
        super().setUp()
        self.session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            response_id="response_id",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            case_id="case_id",
        )
        self.session_store = SessionStore("user_ik", "pepper", "eq_session_id")
        self.expires_at = datetime.now(tzutc()) + timedelta(seconds=5)

    def test_check_session_with_user_id_in_session(self):
        with self.app_request_context("/status"):
            with patch(
                    "app.authentication.authenticator.get_session_store",
                    return_value=self.session_store,
            ):
                # Given
                self.session_store.create("eq_session_id", "user_id",
                                          self.session_data, self.expires_at)
                cookie_session[USER_IK] = "user_ik"

                # When
                user = load_user()

                # Then
                self.assertEqual(user.user_id, "user_id")
                self.assertEqual(user.user_ik, "user_ik")

    def test_check_session_with_no_user_id_in_session(self):
        with self.app_request_context("/status"):
            with patch("app.authentication.authenticator.get_session_store",
                       return_value=None):
                # When
                user = load_user()

                # Then
                self.assertIsNone(user)

    def test_load_user(self):
        with self.app_request_context("/status"):
            with patch(
                    "app.authentication.authenticator.get_session_store",
                    return_value=self.session_store,
            ):
                # Given
                self.session_store.create("eq_session_id", "user_id",
                                          self.session_data, self.expires_at)
                cookie_session[USER_IK] = "user_ik"

                # When
                user = user_loader(None)

                # Then
                self.assertEqual(user.user_id, "user_id")
                self.assertEqual(user.user_ik, "user_ik")

    def test_request_load_user(self):
        with self.app_request_context("/status"):
            with patch(
                    "app.authentication.authenticator.get_session_store",
                    return_value=self.session_store,
            ):
                # Given
                self.session_store.create("eq_session_id", "user_id",
                                          self.session_data, self.expires_at)
                cookie_session[USER_IK] = "user_ik"

                # When
                user = request_load_user(None)

                # Then
                self.assertEqual(user.user_id, "user_id")
                self.assertEqual(user.user_ik, "user_ik")

    def test_no_user_when_session_has_expired(self):
        with self.app_request_context("/status"):
            with patch(
                    "app.authentication.authenticator.get_session_store",
                    return_value=self.session_store,
            ):
                # Given
                self.session_store.create(
                    "eq_session_id",
                    "user_id",
                    self.session_data,
                    expires_at=datetime.now(tzutc()),
                )
                cookie_session[USER_IK] = "user_ik"

                # When
                user = user_loader(None)

                # Then
                self.assertIsNone(user)
                self.assertIsNone(cookie_session.get(USER_IK))

    def test_valid_user_does_not_extend_session_expiry_when_expiry_less_than_60_seconds_different(
        self, ):
        with self.app_request_context("/status"):
            with patch(
                    "app.authentication.authenticator.get_session_store",
                    return_value=self.session_store,
            ):
                # Given
                self.session_store.create("eq_session_id", "user_id",
                                          self.session_data, self.expires_at)
                cookie_session[USER_IK] = "user_ik"
                cookie_session["expires_in"] = 5

                # When
                user = user_loader(None)

                # Then
                self.assertEqual(user.user_id, "user_id")
                self.assertEqual(user.user_ik, "user_ik")
                self.assertEqual(user.is_authenticated, True)
                self.assertEqual(self.session_store.expiration_time,
                                 self.expires_at)

    def test_valid_user_extends_session_expiry_when_expiry_greater_than_60_seconds_different(
        self, ):
        with self.app_request_context("/status"):
            with patch(
                    "app.authentication.authenticator.get_session_store",
                    return_value=self.session_store,
            ):
                # Given
                self.session_store.create("eq_session_id", "user_id",
                                          self.session_data, self.expires_at)
                cookie_session[USER_IK] = "user_ik"
                cookie_session["expires_in"] = 600

                # When
                user = user_loader(None)

                # Then
                self.assertEqual(user.user_id, "user_id")
                self.assertEqual(user.user_ik, "user_ik")
                self.assertEqual(user.is_authenticated, True)
                self.assertGreater(self.session_store.expiration_time,
                                   self.expires_at)
Ejemplo n.º 22
0
def fixture_session_store():
    return SessionStore("user_ik", "pepper", "eq_session_id")
class SessionStoreTest(AppContextTestCase):
    def setUp(self):
        super().setUp()
        self._app.permanent_session_lifetime = timedelta(seconds=1)
        self.session_store = SessionStore("user_ik", "pepper")
        self.expires_at = datetime.utcnow() + timedelta(seconds=3)
        self.session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            questionnaire_id="questionnaire_id",
            response_id="response_id",
            case_id="case_id",
        )

    def test_no_session(self):
        with self._app.test_request_context():
            self.assertIsNone(self.session_store.user_id)
            self.assertIsNone(self.session_store.session_data)

    def test_create(self):
        with self._app.test_request_context():
            self.session_store.create("eq_session_id", "test",
                                      self.session_data, self.expires_at)
            self.assertEqual("eq_session_id", self.session_store.eq_session_id)
            self.assertEqual("test", self.session_store.user_id)
            self.assertEqual(self.session_data,
                             self.session_store.session_data)

    def test_save(self):
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=self.session_data,
                expires_at=self.expires_at,
            ).save()
            session_store = SessionStore("user_ik", "pepper", "eq_session_id")
            self.assertEqual(session_store.session_data.tx_id, "tx_id")

    def test_delete(self):
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=self.session_data,
                expires_at=self.expires_at,
            ).save()
            self.assertEqual("test", self.session_store.user_id)
            self.session_store.delete()
            self.assertEqual(self.session_store.user_id, None)

    def test_add_data_to_session(self):
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=self.session_data,
                expires_at=self.expires_at,
            ).save()
            current_time = datetime.utcnow().isoformat()
            self.session_store.session_data.submitted_time = current_time
            self.session_store.save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")
            self.assertEqual(session_store.session_data.submitted_time,
                             current_time)

    def test_should_not_delete_when_no_session(self):
        with self.app_request_context("/status") as context:

            # Call clear with a valid user_id but no session in database
            self.session_store.delete()

            # No database calls should have been made
            self.assertEqual(
                context.app.eq["storage"].client.delete_call_count, 0)

    def test_session_store_ignores_new_values_in_session_data(self):
        session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            response_id="response_id",
            questionnaire_id="questionnaire_id",
            case_id="case_id",
        )

        session_data.additional_value = "some cool new value you do not know about yet"

        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=self.session_data,
                expires_at=self.expires_at,
            ).save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")

            self.assertFalse(
                hasattr(session_store.session_data, "additional_value"))

    def test_session_store_ignores_multiple_new_values_in_session_data(self):
        session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            response_id="response_id",
            questionnaire_id="questionnaire_id",
            case_id="case_id",
        )

        session_data.additional_value = "some cool new value you do not know about yet"
        session_data.second_additional_value = "some other not so cool value"

        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=session_data,
                expires_at=self.expires_at,
            ).save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")

            self.assertFalse(
                hasattr(session_store.session_data, "additional_value"))
            self.assertFalse(
                hasattr(session_store.session_data, "second_additional_value"))

    def test_session_store_stores_trading_as_value_if_present(self):
        session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            response_id="response_id",
            questionnaire_id="questionnaire_id",
            trad_as="trading_as",
            case_id="case_id",
        )
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=session_data,
                expires_at=self.expires_at,
            ).save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")

            self.assertTrue(hasattr(session_store.session_data, "trad_as"))

    def test_session_store_stores_none_for_trading_as_if_not_present(self):
        session_data = SessionData(
            tx_id="tx_id",
            schema_name="some_schema_name",
            period_str="period_str",
            language_code=None,
            launch_language_code=None,
            survey_url=None,
            ru_name="ru_name",
            ru_ref="ru_ref",
            response_id="response_id",
            questionnaire_id="questionnaire_id",
            case_id="case_id",
        )
        with self._app.test_request_context():
            self.session_store.create(
                eq_session_id="eq_session_id",
                user_id="test",
                session_data=session_data,
                expires_at=self.expires_at,
            ).save()

            session_store = SessionStore("user_ik", "pepper", "eq_session_id")

            self.assertIsNone(session_store.session_data.trad_as)