예제 #1
0
 def test_user(self):
     test_user_id = "a6454e643f7f4e8889b7085c466548d4"
     return User(
         id=uuid.UUID(test_user_id).hex,
         level=UserLevels.STAFF,
         is_authenticated=True,
     )
예제 #2
0
    def test_get_cache_key_returns_correct_key_if_user_is_authenticated(
            self, insanic_application, test_user_token_factory):
        class DummyView(InsanicView):
            throttle_scope = "user"

            def get(self, *args, **kwargs):
                return text("dummy")

        user_id = 1
        user = User(id=user_id, level=UserLevels.ACTIVE, is_authenticated=True)

        class MockRequest:
            @property
            def user(self):
                return user

        request = MockRequest()

        loop = uvloop.new_event_loop()
        loop.run_until_complete(
            self.throttle.allow_request(request, DummyView()))

        loop = uvloop.new_event_loop()
        cache_key = loop.run_until_complete(
            self.throttle.get_cache_key(request, view=DummyView()))

        assert cache_key == "throttle_user_%s" % user_id
예제 #3
0
def test_user():
    test_level = UserLevels.ACTIVE
    test_authenticated = True

    return User(id=TEST_USER_ID,
                level=test_level,
                is_authenticated=test_authenticated)
예제 #4
0
    async def test_task_context_service_http_dispatch_injection(
        self,
        insanic_application,
        test_client,
        test_service_token_factory,
        monkeypatch,
    ):
        import aiotask_context
        import asyncio
        from insanic.loading import get_service

        monkeypatch.setattr(settings, "SERVICE_CONNECTIONS", ["userip"])
        UserIPService = get_service("userip")

        class TokenView(InsanicView):
            async def get(self, request, *args, **kwargs):
                context_user = aiotask_context.get(
                    settings.TASK_CONTEXT_REQUEST_USER)
                request_user = request.user
                handlers.jwt_decode_handler(request.auth)

                token = UserIPService.service_token
                assert token is not None

                assert dict(request_user) == context_user
                return json({"user": dict(request_user)})

        insanic_application.add_route(TokenView.as_view(), "/")

        client = await test_client(insanic_application)

        users = []
        requests = []

        for i in range(10):
            user = User(id=i, level=UserLevels.STAFF, is_authenticated=True)

            token = test_service_token_factory()
            requests.append(
                client.get(
                    "/",
                    headers={
                        "Authorization":
                        token,
                        settings.INTERNAL_REQUEST_USER_HEADER:
                        to_header_value(user),
                    },
                ))
            users.append(user)

        responses = await asyncio.gather(*requests)

        for i in range(10):
            r = responses[i]
            resp = await r.json()
            assert r.status == 200, resp

            assert resp["user"]["id"] == str(users[i].id)
예제 #5
0
    def authenticate_credentials(self, request, payload):
        user_id = payload.pop("id", payload.get("user_id"))

        user = User(id=user_id, is_authenticated=True, **payload)

        if not user.is_active:
            msg = "User account is disabled."
            raise exceptions.AuthenticationFailed(
                msg, error_code=GlobalErrorCodes.inactive_user)

        return user, AnonymousRequestService
예제 #6
0
    def test_authenticated_user_not_affected(self, loop):
        user_id = 1
        user = User(id=user_id, level=UserLevels.ACTIVE, is_authenticated=True)

        class MockRequest:
            @property
            def user(self):
                return user

        mock_request = MockRequest()
        assert (loop.run_until_complete(
            self.throttle.get_cache_key(mock_request, view={})) is None)
예제 #7
0
    async def test_task_context_service_multiple_after_authentication(
            self, insanic_application, test_client,
            test_service_token_factory):
        import aiotask_context
        import asyncio

        class TokenView(InsanicView):
            async def get(self, request, *args, **kwargs):
                user = aiotask_context.get(settings.TASK_CONTEXT_REQUEST_USER)
                assert user is not None

                request_user = request.user
                assert user == dict(request_user)

                payload = handlers.jwt_decode_handler(request.auth)
                assert "user" not in payload
                assert user == dict(request_user)

                return json({"user": user})

        insanic_application.add_route(TokenView.as_view(), "/")

        client = await test_client(insanic_application)
        #
        # insanic_application.run(host='127.0.0.1', port=unused_port)
        requests = []
        for i in range(10):
            user = User(id=i, level=UserLevels.STAFF, is_authenticated=True)

            token = test_service_token_factory()
            requests.append(
                client.get(
                    "/",
                    headers={
                        "Authorization":
                        token,
                        settings.INTERNAL_REQUEST_USER_HEADER:
                        to_header_value(user),
                    },
                ))

        responses = await asyncio.gather(*requests)

        for i in range(10):
            r = responses[i]
            assert r.status == 200

            resp = await r.json()
            assert resp["user"]["id"] == str(i)
예제 #8
0
    def factory(user=None):
        if user is None:
            user = User(
                id=uuid.uuid4().hex,
                email="*****@*****.**",
                level=UserLevels.ACTIVE,
            )
        # source, aud, source_ip, destination_version, is_authenticated):
        service = MockService()
        payload = handlers.jwt_service_payload_handler(service)
        payload.update({"user": dict(user)})

        return " ".join(
            [
                settings.JWT_SERVICE_AUTH_AUTH_HEADER_PREFIX,
                handlers.jwt_service_encode_handler(payload),
            ]
        )
예제 #9
0
    def factory(id=None, *, level, return_with_user=False):
        if not id:
            id = uuid.uuid4().hex

        user = User(id=id, level=level)

        mock_issuer = uuid.uuid4().hex
        mock_secret = uuid.uuid4().hex

        payload = jwt_payload_handler(user, mock_issuer)
        token = jwt.encode(payload, mock_secret, "HS256").decode()

        if return_with_user:
            return (
                user,
                " ".join([settings.JWT_AUTH_AUTH_HEADER_PREFIX, token]),
            )

        return " ".join([settings.JWT_AUTH_AUTH_HEADER_PREFIX, token])
예제 #10
0
    def authenticate_credentials(self, request, payload):

        user_params = {"id": "", "level": -1}

        for f in request.headers.get(settings.INTERNAL_REQUEST_USER_HEADER,
                                     "").split(";"):
            if f:
                k, v = f.split("=")
                user_params.update({k: v})

        user = User(**user_params)

        service = RequestService(is_authenticated=True, **payload)

        if not service.is_valid:
            msg = f"Invalid request to {settings.SERVICE_NAME}."
            raise exceptions.AuthenticationFailed(
                msg, error_code=GlobalErrorCodes.invalid_service_token)

        return user, service
예제 #11
0
    async def test_authenticate_credentials_with_user_header(
            self, auth, test_service_token_factory):
        test_user_id = "a6454e643f7f4e8889b7085c466548d4"
        test_user = User(
            id=uuid.UUID(test_user_id).hex,
            level=UserLevels.STAFF,
            is_authenticated=1,
        )
        token = test_service_token_factory()
        payload = handlers.jwt_service_decode_handler(token.split()[1])

        class MockRequest:
            @property
            def headers(self):
                return {
                    settings.INTERNAL_REQUEST_USER_HEADER:
                    to_header_value(test_user)
                }

        user, service = auth.authenticate_credentials(MockRequest(), payload)
        assert dict(user) == dict(test_user)
예제 #12
0
    def test_get_cache_key_returns_correct_value(self, loop):
        user_id = 1
        user = User(id=user_id,
                    level=UserLevels.ACTIVE,
                    is_authenticated=False)

        class MockRequest:
            ip = None
            headers = {}

            @property
            def remote_addr(self, *args, **kwargs):
                return None

            @property
            def user(self):
                return user

        mock_request = MockRequest()

        cache_key = loop.run_until_complete(
            self.throttle.get_cache_key(mock_request, view={}))
        assert cache_key == "throttle_anon_None"
예제 #13
0
    def test_jwt_token_authentication_success(self, monkeypatch,
                                              authentication_class,
                                              test_user_token_factory):
        app = self._create_app_with_authentication(authentication_class)

        user_id = uuid.uuid4()
        level = UserLevels.ACTIVE
        token = test_user_token_factory(id=user_id.hex, level=level)

        self.monkeypatch_get_user(
            monkeypatch,
            authentication_class,
            User(id=user_id.hex, level=level),
        )

        request, response = app.test_client.get(
            "/",
            headers={
                "Authorization": token,
                "x-consumer-username": user_id.hex,
            },
        )

        assert response.status == status.HTTP_200_OK