From 2a41f639c653662fa7e1a13b611384bf508b7a25 Mon Sep 17 00:00:00 2001 From: MoritzWeber Date: Tue, 30 Jul 2024 13:29:05 +0200 Subject: [PATCH] refactor: Clean up authentication code; add tests for OIDC --- Makefile | 4 +- .../f3d2dedd7906_add_jupyter_token_column.py | 2 +- .../core/authentication/api_key_cookie.py | 10 +- .../core/authentication/injectables.py | 25 +- .../core/authentication/models.py | 7 + .../{oidc_provider.py => oidc.py} | 79 +- .../core/authentication/routes.py | 87 +- .../capellacollab/core/logging/__init__.py | 5 +- .../settings/configuration/routes.py | 5 +- .../integrations/purevariants/routes.py | 1 + backend/capellacollab/users/models.py | 1 + backend/tests/conftest.py | 28 +- backend/tests/core/conftest.py | 124 --- backend/tests/core/test_auth.py | 56 - backend/tests/core/test_auth_routes.py | 236 +++++ .../tests/projects/test_projects_routes.py | 51 +- .../sessions/hooks/test_guacamole_hook.py | 10 +- .../sessions/test_session_environment.py | 4 +- backend/tests/sessions/test_session_routes.py | 1 + .../teamforcapella/test_t4c_instances.py | 4 +- .../settings/test_global_configuration.py | 13 +- backend/tests/test_event_creation.py | 104 +- backend/tests/test_metrics.py | 5 +- .../tests/tools/test_tools_natures_routes.py | 3 +- backend/tests/tools/test_tools_routes.py | 6 +- .../versions/test_tools_version_routes.py | 3 +- backend/tests/users/fixtures.py | 2 +- backend/tests/users/test_users.py | 4 +- frontend/Makefile | 12 +- .../auth/auth-guard/auth-guard.service.ts | 4 +- .../auth-redirect/auth-redirect.component.ts | 14 +- .../app/general/auth/auth/auth.component.ts | 4 +- .../auth/http-interceptor/auth.interceptor.ts | 8 +- .../logout-redirect.component.ts | 4 +- .../app/general/header/header.component.ts | 4 +- .../nav-bar-menu/nav-bar-menu.component.ts | 4 +- .../src/app/openapi/.openapi-generator/FILES | 5 +- frontend/src/app/openapi/api/api.ts | 10 +- .../app/openapi/api/authentication.service.ts | 424 ++++++++ .../app/openapi/api/configuration.service.ts | 307 ++++++ .../src/app/openapi/api/default.service.ts | 960 ------------------ .../api/integrations-pure-variants.service.ts | 421 ++++++++ ...e-request.ts => authorization-response.ts} | 12 +- frontend/src/app/openapi/model/base-user.ts | 1 + frontend/src/app/openapi/model/models.ts | 1 + frontend/src/app/openapi/model/user.ts | 1 + .../src/app/services/auth/auth.service.ts | 48 +- .../src/app/services/user/user.service.ts | 4 +- .../active-sessions.stories.ts | 4 + .../user-information.component.html | 4 +- .../user-information.stories.ts | 8 +- frontend/src/storybook/user.ts | 3 +- helm/config/oauth.json | 27 +- helm/templates/mock/oauth.deployment.yaml | 2 +- 54 files changed, 1692 insertions(+), 1484 deletions(-) rename backend/capellacollab/core/authentication/{oidc_provider.py => oidc.py} (74%) delete mode 100644 backend/tests/core/conftest.py delete mode 100644 backend/tests/core/test_auth.py create mode 100644 backend/tests/core/test_auth_routes.py create mode 100644 frontend/src/app/openapi/api/authentication.service.ts create mode 100644 frontend/src/app/openapi/api/configuration.service.ts delete mode 100644 frontend/src/app/openapi/api/default.service.ts create mode 100644 frontend/src/app/openapi/api/integrations-pure-variants.service.ts rename frontend/src/app/openapi/model/{patch-user-role-request.ts => authorization-response.ts} (71%) diff --git a/Makefile b/Makefile index df958368f9..b84bee3729 100644 --- a/Makefile +++ b/Makefile @@ -96,8 +96,8 @@ helm-deploy: --set docker.registry.sessions=$(CAPELLACOLLAB_SESSIONS_REGISTRY) \ --set docker.tag=$(DOCKER_TAG) \ --set mocks.oauth=True \ - --set authentication.claimMapping.username=sub \ - --set authentication.endpoints.authorization=https://localhost/default/authorize \ + --set backend.authentication.claimMapping.username=sub \ + --set backend.authentication.endpoints.authorization=https://localhost/default/authorize \ --set development=$(DEVELOPMENT_MODE) \ --set cluster.ingressClassName=traefik \ --set cluster.ingressNamespace=kube-system \ diff --git a/backend/capellacollab/alembic/versions/f3d2dedd7906_add_jupyter_token_column.py b/backend/capellacollab/alembic/versions/f3d2dedd7906_add_jupyter_token_column.py index c9a9184d2c..9b043d46a7 100644 --- a/backend/capellacollab/alembic/versions/f3d2dedd7906_add_jupyter_token_column.py +++ b/backend/capellacollab/alembic/versions/f3d2dedd7906_add_jupyter_token_column.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors # SPDX-License-Identifier: Apache-2.0 -"""Commit message +"""Add column for Jupyter token Revision ID: f3d2dedd7906 Revises: 4df9c82766e2 diff --git a/backend/capellacollab/core/authentication/api_key_cookie.py b/backend/capellacollab/core/authentication/api_key_cookie.py index 772508e592..71d86d497d 100644 --- a/backend/capellacollab/core/authentication/api_key_cookie.py +++ b/backend/capellacollab/core/authentication/api_key_cookie.py @@ -11,7 +11,7 @@ from capellacollab.config import config -from . import exceptions, oidc_provider +from . import exceptions, oidc log = logging.getLogger(__name__) @@ -21,7 +21,7 @@ class JWTConfig: _jwks_client = None - def __init__(self, oidc_config: oidc_provider.AbstractOIDCProviderConfig): + def __init__(self, oidc_config: oidc.OIDCProviderConfig): self.oidc_config = oidc_config if JWTConfig._jwks_client is None: @@ -32,10 +32,10 @@ def __init__(self, oidc_config: oidc_provider.AbstractOIDCProviderConfig): class JWTAPIKeyCookie(security.APIKeyCookie): - def __init__(self, oidc_config: oidc_provider.AbstractOIDCProviderConfig): + def __init__(self): super().__init__(name="id_token", auto_error=True) - self.oidc_config = oidc_config - self.jwt_config = JWTConfig(oidc_config) + self.oidc_config = oidc.get_cached_oidc_config() + self.jwt_config = JWTConfig(self.oidc_config) async def __call__(self, request: fastapi.Request) -> str: token: str | None = await super().__call__(request) diff --git a/backend/capellacollab/core/authentication/injectables.py b/backend/capellacollab/core/authentication/injectables.py index 844c1a7497..c4a0edcaf5 100644 --- a/backend/capellacollab/core/authentication/injectables.py +++ b/backend/capellacollab/core/authentication/injectables.py @@ -4,7 +4,6 @@ from __future__ import annotations import dataclasses -import functools import logging import fastapi @@ -24,28 +23,11 @@ from capellacollab.users import exceptions as users_exceptions from capellacollab.users import models as users_models -from . import exceptions, oidc_provider +from . import exceptions logger = logging.getLogger(__name__) -@functools.lru_cache -def get_cached_oidc_config() -> oidc_provider.AbstractOIDCProviderConfig: - return oidc_provider.WellKnownOIDCProviderConfig() - - -async def get_oidc_config() -> oidc_provider.AbstractOIDCProviderConfig: - return get_cached_oidc_config() - - -async def get_oidc_provider( - oidc_config: oidc_provider.AbstractOIDCProviderConfig = fastapi.Depends( - get_oidc_config - ), -) -> oidc_provider.AbstractOIDCProvider: - return oidc_provider.OIDCProvider(oidc_config) - - class OpenAPIFakeBase(security_base.SecurityBase): """Fake class to display the authentication methods in the OpenAPI docs @@ -79,13 +61,10 @@ class OpenAPIPersonalAccessToken(OpenAPIFakeBase): async def get_username( request: fastapi.Request, - oidc_config: oidc_provider.AbstractOIDCProviderConfig = fastapi.Depends( - get_oidc_config - ), _unused1=fastapi.Depends(OpenAPIPersonalAccessToken()), ) -> str: if request.cookies.get("id_token"): - username = await api_key_cookie.JWTAPIKeyCookie(oidc_config)(request) + username = await api_key_cookie.JWTAPIKeyCookie()(request) return username authorization = request.headers.get("Authorization") diff --git a/backend/capellacollab/core/authentication/models.py b/backend/capellacollab/core/authentication/models.py index 2a4d936efc..7dadb470b8 100644 --- a/backend/capellacollab/core/authentication/models.py +++ b/backend/capellacollab/core/authentication/models.py @@ -9,3 +9,10 @@ class TokenRequest(core_pydantic.BaseModel): code: str nonce: str code_verifier: str + + +class AuthorizationResponse(core_pydantic.BaseModel): + auth_url: str + state: str + nonce: str + code_verifier: str diff --git a/backend/capellacollab/core/authentication/oidc_provider.py b/backend/capellacollab/core/authentication/oidc.py similarity index 74% rename from backend/capellacollab/core/authentication/oidc_provider.py rename to backend/capellacollab/core/authentication/oidc.py index 9970f473f1..ea65eaadf1 100644 --- a/backend/capellacollab/core/authentication/oidc_provider.py +++ b/backend/capellacollab/core/authentication/oidc.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors # SPDX-License-Identifier: Apache-2.0 -import abc +import functools import logging import typing as t @@ -10,46 +10,12 @@ from capellacollab.config import config -from . import exceptions +from . import exceptions, models logger = logging.getLogger(__name__) -class AbstractOIDCProviderConfig(abc.ABC): - @abc.abstractmethod - def get_authorization_endpoint(self) -> str: - pass - - @abc.abstractmethod - def get_token_endpoint(self) -> str: - pass - - @abc.abstractmethod - def get_jwks_uri(self) -> str: - pass - - @abc.abstractmethod - def get_supported_signing_algorithms(self) -> list[str]: - pass - - @abc.abstractmethod - def get_issuer(self) -> str: - pass - - @abc.abstractmethod - def get_scopes(self) -> list[str]: - pass - - @abc.abstractmethod - def get_client_id(self) -> str: - pass - - @abc.abstractmethod - def get_client_secret(self) -> str: - pass - - -class WellKnownOIDCProviderConfig(AbstractOIDCProviderConfig): +class OIDCProviderConfig: def __init__(self): self.well_known_uri = config.authentication.endpoints.well_known self.well_known = self._fetch_well_known_configuration() @@ -92,32 +58,16 @@ def get_client_id(self) -> str: return config.authentication.client.id -class AbstractOIDCProvider(abc.ABC): - def __init__(self, oidc_config: AbstractOIDCProviderConfig): - self.oidc_config = oidc_config +@functools.lru_cache +def get_cached_oidc_config() -> OIDCProviderConfig: + return OIDCProviderConfig() - @abc.abstractmethod - def get_authorization_url_with_parameters( - self, - ) -> t.Tuple[str, str, str, str]: - pass - - @abc.abstractmethod - def exchange_code_for_tokens( - self, authorization_code: str, code_verifier: str - ) -> dict[str, t.Any]: - pass - - @abc.abstractmethod - def refresh_token(self, _refresh_token: str) -> dict[str, t.Any]: - pass - -class OIDCProvider(AbstractOIDCProvider): +class OIDCProvider: CODE_CHALLENGE_METHOD = "S256" - def __init__(self, oidc_config: AbstractOIDCProviderConfig): - super().__init__(oidc_config) + def __init__(self): + self.oidc_config = get_cached_oidc_config() self.web_client: oauth2.WebApplicationClient = ( oauth2.WebApplicationClient( client_id=self.oidc_config.get_client_id() @@ -126,10 +76,10 @@ def __init__(self, oidc_config: AbstractOIDCProviderConfig): def get_authorization_url_with_parameters( self, - ) -> t.Tuple[str, str, str, str]: + ) -> models.AuthorizationResponse: state = common.generate_token() - nonce = common.generate_nonce() + code_verifier = self.web_client.create_code_verifier(length=43) code_challenge = self.web_client.create_code_challenge( code_verifier, OIDCProvider.CODE_CHALLENGE_METHOD @@ -145,7 +95,12 @@ def get_authorization_url_with_parameters( code_challenge_method=OIDCProvider.CODE_CHALLENGE_METHOD, ) - return (auth_url, state, nonce, code_verifier) + return models.AuthorizationResponse( + auth_url=auth_url, + state=state, + nonce=nonce, + code_verifier=code_verifier, + ) def exchange_code_for_tokens( self, authorization_code: str, code_verifier: str diff --git a/backend/capellacollab/core/authentication/routes.py b/backend/capellacollab/core/authentication/routes.py index 1974833d4c..5fce7f9db8 100644 --- a/backend/capellacollab/core/authentication/routes.py +++ b/backend/capellacollab/core/authentication/routes.py @@ -13,50 +13,34 @@ from capellacollab.users import crud as users_crud from capellacollab.users import models as users_models -from . import api_key_cookie, exceptions, injectables, models, oidc_provider +from . import api_key_cookie, exceptions, models, oidc -router = fastapi.APIRouter() +router = fastapi.APIRouter(tags=["Authentication"]) -@router.get("", name="Get the authorization URL for the OAuth Server") -async def get_redirect_url( +@router.get("") +async def get_authorization_url( response: fastapi.Response, - provider: oidc_provider.AbstractOIDCProvider = fastapi.Depends( - injectables.get_oidc_provider - ), -) -> dict[str, str]: - auth_url, state, nonce, code_verifier = ( - provider.get_authorization_url_with_parameters() +) -> models.AuthorizationResponse: + authorization_response = ( + oidc.OIDCProvider().get_authorization_url_with_parameters() ) delete_token_cookies(response) - return { - "auth_url": auth_url, - "state": state, - "nonce": nonce, - "code_verifier": code_verifier, - } + return authorization_response -@router.post("/tokens", name="Create the identity token") -async def api_get_token( +@router.post("/tokens") +async def get_identity_token( token_request: models.TokenRequest, response: fastapi.Response, db: orm.Session = fastapi.Depends(database.get_db), - provider: oidc_provider.AbstractOIDCProvider = fastapi.Depends( - injectables.get_oidc_provider - ), - oidc_config: oidc_provider.AbstractOIDCProviderConfig = fastapi.Depends( - injectables.get_oidc_config - ), ): - tokens = provider.exchange_code_for_tokens( + tokens = oidc.OIDCProvider().exchange_code_for_tokens( token_request.code, token_request.code_verifier ) - validated_id_token = validate_id_token( - tokens["id_token"], oidc_config, None - ) + validated_id_token = validate_id_token(tokens["id_token"], None) user = create_or_update_user(db, validated_id_token) update_token_cookies( @@ -64,26 +48,18 @@ async def api_get_token( ) -@router.put("/tokens", name="Refresh the identity token") -async def api_refresh_token( +@router.put("/tokens") +async def refresh_identity_token( response: fastapi.Response, refresh_token: t.Annotated[str | None, fastapi.Cookie()] = None, db: orm.Session = fastapi.Depends(database.get_db), - provider: oidc_provider.AbstractOIDCProvider = fastapi.Depends( - injectables.get_oidc_provider - ), - oidc_config: oidc_provider.AbstractOIDCProviderConfig = fastapi.Depends( - injectables.get_oidc_config - ), -): +) -> None: if refresh_token is None or refresh_token == "": raise exceptions.RefreshTokenCookieMissingError() - tokens = provider.refresh_token(refresh_token) + tokens = oidc.OIDCProvider().refresh_token(refresh_token) - validated_id_token = validate_id_token( - tokens["id_token"], oidc_config, None - ) + validated_id_token = validate_id_token(tokens["id_token"], None) user = create_or_update_user(db, validated_id_token) update_token_cookies( @@ -91,22 +67,19 @@ async def api_refresh_token( ) -@router.delete("/tokens", name="Remove the token (log out)") +@router.delete("/tokens") async def logout(response: fastapi.Response): delete_token_cookies(response) return None -@router.get("/tokens", name="Validate the token") -async def validate_token( +@router.get("/tokens") +async def validate_jwt_token( request: fastapi.Request, scope: users_models.Role | None = None, db: orm.Session = fastapi.Depends(database.get_db), - oidc_config: oidc_provider.AbstractOIDCProviderConfig = fastapi.Depends( - injectables.get_oidc_config - ), ): - username = await api_key_cookie.JWTAPIKeyCookie(oidc_config)(request) + username = await api_key_cookie.JWTAPIKeyCookie()(request) if scope and scope.ADMIN: auth_injectables.RoleVerification( required_role=users_models.Role.ADMIN @@ -116,12 +89,12 @@ async def validate_token( def validate_id_token( id_token: str, - oidc_config: oidc_provider.AbstractOIDCProviderConfig, nonce: str | None, ) -> dict[str, str]: - validated_id_token = api_key_cookie.JWTAPIKeyCookie( - oidc_config - ).validate_token(id_token) + validated_id_token = api_key_cookie.JWTAPIKeyCookie().validate_token( + id_token + ) + oidc_config = oidc.get_cached_oidc_config() if nonce and not hmac.compare_digest(validated_id_token["nonce"], nonce): raise exceptions.NonceMismatchError() @@ -146,6 +119,16 @@ def create_or_update_user( user = users_crud.create_user(db, username, idp_identifier, email) events_crud.create_user_creation_event(db, user) + if user.email != email: + user = users_crud.update_user( + db, user, users_models.PatchUser(email=email) + ) + + if user.name != username: + user = users_crud.update_user( + db, user, users_models.PatchUser(name=username) + ) + users_crud.update_last_login(db, user) return user diff --git a/backend/capellacollab/core/logging/__init__.py b/backend/capellacollab/core/logging/__init__.py index 58cef5f9fb..605bf3b2ac 100644 --- a/backend/capellacollab/core/logging/__init__.py +++ b/backend/capellacollab/core/logging/__init__.py @@ -80,10 +80,7 @@ async def dispatch( call_next: base.RequestResponseEndpoint, ): try: - oidc_config = await auth_injectables.get_oidc_config() - username = await auth_injectables.get_username( - request, oidc_config - ) + username = await auth_injectables.get_username(request) except fastapi.HTTPException: username = "anonymous" diff --git a/backend/capellacollab/settings/configuration/routes.py b/backend/capellacollab/settings/configuration/routes.py index 41fb29de67..d7dba47367 100644 --- a/backend/capellacollab/settings/configuration/routes.py +++ b/backend/capellacollab/settings/configuration/routes.py @@ -19,10 +19,11 @@ required_role=users_models.Role.ADMIN ) ) - ] + ], + tags=["Configuration"], ) -schema_router = fastapi.APIRouter(dependencies=[]) +schema_router = fastapi.APIRouter(dependencies=[], tags=["Configuration"]) @router.get( diff --git a/backend/capellacollab/settings/integrations/purevariants/routes.py b/backend/capellacollab/settings/integrations/purevariants/routes.py index b603d2256a..dcc25b643a 100644 --- a/backend/capellacollab/settings/integrations/purevariants/routes.py +++ b/backend/capellacollab/settings/integrations/purevariants/routes.py @@ -21,6 +21,7 @@ ) ) ], + tags=["Integrations - PureVariants"], ) diff --git a/backend/capellacollab/users/models.py b/backend/capellacollab/users/models.py index 7e8ee71f0a..0aa2509160 100644 --- a/backend/capellacollab/users/models.py +++ b/backend/capellacollab/users/models.py @@ -29,6 +29,7 @@ class BaseUser(core_pydantic.BaseModel): id: int name: str idp_identifier: str + email: str | None = None role: Role diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index da5343f590..ced2d08b23 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -12,13 +12,11 @@ import pytest import sqlalchemy import sqlalchemy.exc -from core import conftest as core_conftest from fastapi import testclient from sqlalchemy import engine, orm from testcontainers import postgres from capellacollab.__main__ import app -from capellacollab.core.authentication import oidc_provider from capellacollab.core.database import migration os.environ["DEVELOPMENT_MODE"] = "1" @@ -91,28 +89,16 @@ def commit(*args, **kwargs): yield session -@pytest.fixture() -def client(monkeypatch: pytest.MonkeyPatch) -> testclient.TestClient: - monkeypatch.setattr( - "capellacollab.core.authentication.api_key_cookie.JWTConfig", - core_conftest.MockJWTConfig, - ) - +@pytest.fixture(name="client") +def fixture_client() -> testclient.TestClient: return testclient.TestClient(app, cookies={"id_token": "any"}) +@pytest.fixture(name="client_unauthenticated") +def fixture_client_unauthenticated() -> testclient.TestClient: + return testclient.TestClient(app) + + @pytest.fixture(name="logger") def fixture_logger() -> logging.LoggerAdapter: return logging.LoggerAdapter(logging.getLogger()) - - -@pytest.fixture(name="mock_oidc_config") -def fixture_mock_oidc_config(): - return core_conftest.MockOIDCProviderConfig() - - -@pytest.fixture(name="mock_oidc_provider") -def fixture_mock_oidc_provider( - mock_oidc_config: oidc_provider.AbstractOIDCProviderConfig, -): - return core_conftest.MockOIDCProvider(mock_oidc_config) diff --git a/backend/tests/core/conftest.py b/backend/tests/core/conftest.py deleted file mode 100644 index 3be79f8756..0000000000 --- a/backend/tests/core/conftest.py +++ /dev/null @@ -1,124 +0,0 @@ -# SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors -# SPDX-License-Identifier: Apache-2.0 - - -import typing as t - -import pytest -from fastapi import testclient - -from capellacollab.__main__ import app -from capellacollab.core.authentication import injectables as auth_injectables -from capellacollab.core.authentication import oidc_provider - - -class MockPyJWK: - def __init__(self) -> None: - self.key = "mock-key" - - -class MockJWKSClient: - def get_signing_key_from_jwt(self, token: str): - return MockPyJWK() - - -class MockJWTConfig: - def __init__( - self, oidc_config: oidc_provider.AbstractOIDCProviderConfig - ) -> None: - self.oidc_config = oidc_config - self.jwks_client = MockJWKSClient() - - -class MockOIDCProviderConfig(oidc_provider.AbstractOIDCProviderConfig): - def get_authorization_endpoint(self) -> str: - return "mock-authorization-endpoint" - - def get_token_endpoint(self) -> str: - return "mock-token-endpoint" - - def get_jwks_uri(self) -> str: - return "mock-jwks-uri" - - def get_supported_signing_algorithms(self) -> list[str]: - return ["RS256"] - - def get_issuer(self) -> str: - return "mock-issuer" - - def get_scopes(self) -> list[str]: - return ["openid", "offline_access", "email"] - - def get_client_secret(self) -> str: - return "mock-secret" - - def get_client_id(self) -> str: - return "mock-client-id" - - -class MockOIDCProvider(oidc_provider.AbstractOIDCProvider): - def __init__(self, oidc_config: oidc_provider.AbstractOIDCProviderConfig): - super().__init__(oidc_config) - self.oidc_config = oidc_config - - def get_authorization_url_with_parameters( - self, - ) -> t.Tuple[str, str, str, str]: - return ( - "mock-auth-url", - "mock-state", - "mock-nonce", - "mock-code-verifier", - ) - - def exchange_code_for_tokens( - self, authorization_code: str, code_verifier: str - ) -> dict[str, t.Any]: - return { - "id_token": "mock-id-token", - "access-token": "mock-access-token", - "refresh-token": "mock-refresh-token", - } - - def refresh_token(self, _refresh_token: str) -> dict[str, t.Any]: - return { - "id_token": "mock-id-token", - "access-token": "mock-access-token", - "refresh-token": "mock-refresh-token", - } - - -@pytest.fixture(name="mock_oidc_provider_and_config") -def fixture_mock_oidc_provider_and_config( - mock_oidc_config: oidc_provider.AbstractOIDCProviderConfig, - mock_oidc_provider: oidc_provider.AbstractOIDCProvider, -): - async def get_mock_oidc_config() -> ( - oidc_provider.AbstractOIDCProviderConfig - ): - return mock_oidc_config - - async def get_mock_oidc_provider() -> oidc_provider.AbstractOIDCProvider: - return mock_oidc_provider - - app.dependency_overrides[auth_injectables.get_oidc_config] = ( - get_mock_oidc_config - ) - app.dependency_overrides[auth_injectables.get_oidc_provider] = ( - get_mock_oidc_provider - ) - - yield - - del app.dependency_overrides[auth_injectables.get_oidc_config] - del app.dependency_overrides[auth_injectables.get_oidc_provider] - - -@pytest.mark.usefixtures("mock_oidc_provider_and_config") -@pytest.fixture(name="unauthorized_client") -def fixture_unauthorized_client(monkeypatch: pytest.MonkeyPatch): - monkeypatch.setattr( - "capellacollab.core.authentication.api_key_cookie.JWTConfig", - MockJWTConfig, - ) - return testclient.TestClient(app) diff --git a/backend/tests/core/test_auth.py b/backend/tests/core/test_auth.py deleted file mode 100644 index 6f47388e4b..0000000000 --- a/backend/tests/core/test_auth.py +++ /dev/null @@ -1,56 +0,0 @@ -# SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors -# SPDX-License-Identifier: Apache-2.0 - - -from unittest import mock - -import pytest -from fastapi import status, testclient - -from capellacollab.core.authentication import ( - api_key_cookie, - exceptions, - oidc_provider, - routes, -) - - -def test_missing_refresh_token(unauthorized_client: testclient.TestClient): - response = unauthorized_client.put("api/v1/authentication/tokens") - json_response = response.json() - - assert response.status_code == status.HTTP_400_BAD_REQUEST - assert json_response["detail"]["err_code"] == "NO_REFRESH_TOKEN_COOKIE" - - -@pytest.mark.usefixtures("mock_auth_endpoints") -def test_validate_id_token_nonce_mismatch( - mock_oidc_config: oidc_provider.AbstractOIDCProviderConfig, - monkeypatch: pytest.MonkeyPatch, -): - mock_jwt_api_cookie = mock.MagicMock() - mock_jwt_api_cookie.return_value.validate_token.return_value = { - "nonce": "mismatch-nonce" - } - - monkeypatch.setattr(api_key_cookie, "JWTAPIKeyCookie", mock_jwt_api_cookie) - - with pytest.raises(exceptions.NonceMismatchError): - routes.validate_id_token("any", mock_oidc_config, "correct-nonce") - - -@pytest.mark.usefixtures("mock_auth_endpoints") -def test_validate_id_token_audience_mismatch( - mock_oidc_config: oidc_provider.AbstractOIDCProviderConfig, - monkeypatch: pytest.MonkeyPatch, -): - mock_jwt_api_cookie = mock.MagicMock() - mock_jwt_api_cookie.return_value.validate_token.return_value = { - "nonce": "mock-nonce", - "aud": "mock-audience", - } - - monkeypatch.setattr(api_key_cookie, "JWTAPIKeyCookie", mock_jwt_api_cookie) - - with pytest.raises(exceptions.UnauthenticatedError): - routes.validate_id_token("any", mock_oidc_config, "mock-nonce") diff --git a/backend/tests/core/test_auth_routes.py b/backend/tests/core/test_auth_routes.py new file mode 100644 index 0000000000..687362240d --- /dev/null +++ b/backend/tests/core/test_auth_routes.py @@ -0,0 +1,236 @@ +# SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors +# SPDX-License-Identifier: Apache-2.0 + + +from unittest import mock + +import pytest +import responses +from fastapi import status, testclient +from sqlalchemy import orm + +from capellacollab.config import config +from capellacollab.core.authentication import api_key_cookie, exceptions, oidc +from capellacollab.core.authentication import routes +from capellacollab.core.authentication import routes as auth_routes +from capellacollab.users import crud as users_crud +from capellacollab.users import models as users_models + + +@pytest.fixture(name="mock_auth_endpoints") +def fixture_mock_oidc_endpoints(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr( + config.authentication.endpoints, + "well_known", + "https://mock.localhost/default/.well-known/openid-configuration", + ) + responses.get( + "https://mock.localhost/default/.well-known/openid-configuration", + status=200, + json={ + "authorization_endpoint": "https://mock.localhost/default/authorize", + "token_endpoint": "https://mock.localhost/default/token", + "jwks_uri": "https:///mock.localhost/default/jwks", + }, + ) + + +@pytest.fixture(name="mock_token_creation") +def fixture_mock_token_creation(monkeypatch: pytest.MonkeyPatch): + responses.post( + "https://mock.localhost/default/token", + status=200, + json={ + "id_token": "id_token", + "refresh_token": "refresh_token", + "access_token": "access_token", + }, + ) + + monkeypatch.setattr(config.authentication.client, "id", "client_id") + monkeypatch.setattr( + api_key_cookie.JWTAPIKeyCookie, + "validate_token", + lambda self, token: { + "nonce": "nonce", + "aud": "client_id", + "sub": "sub", + }, + ) + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints") +def test_get_prefilled_authorization_url( + client_unauthenticated: testclient.TestClient, +): + """Get the authorization URL from the backend""" + response = client_unauthenticated.get("/api/v1/authentication") + assert response.status_code == status.HTTP_200_OK + assert response.json()["auth_url"].startswith( + "https://mock.localhost/default/authorize" + ) + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints", "mock_token_creation") +def test_get_identity_token( + client_unauthenticated: testclient.TestClient, +): + """Check that the identity token is set as cookie""" + response = client_unauthenticated.post( + "/api/v1/authentication/tokens", + json={"code": "any", "nonce": "nonce", "code_verifier": "any"}, + ) + + assert response.status_code == status.HTTP_200_OK + + assert "id_token" in response.headers["set-cookie"] + assert "refresh_token" in response.headers["set-cookie"] + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints") +def test_user_info_updated_on_login( + db: orm.Session, + monkeypatch: pytest.MonkeyPatch, + client_unauthenticated: testclient.TestClient, + user: users_models.DatabaseUser, +): + """Propagate changes of the name or email fields of the JWT""" + monkeypatch.setattr( + oidc.OIDCProvider, + "exchange_code_for_tokens", + lambda *args: {"id_token": ""}, + ) + monkeypatch.setattr( + config.authentication.mapping, "identifier", "idp_identifier" + ) + monkeypatch.setattr( + auth_routes, + "validate_id_token", + lambda *args: { + "idp_identifier": user.idp_identifier, + "sub": "new_name", + "email": "test@example.com", + }, + ) + + response = client_unauthenticated.post( + "/api/v1/authentication/tokens", + json={"code": "any", "nonce": "nonce", "code_verifier": "any"}, + ) + assert response.status_code == status.HTTP_200_OK + + updated_user = users_crud.get_user_by_idp_identifier( + db, user.idp_identifier + ) + assert updated_user is not None + assert updated_user.name == "new_name" + assert updated_user.email == "test@example.com" + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints") +def test_user_created_on_first_login( + db: orm.Session, + monkeypatch: pytest.MonkeyPatch, + client_unauthenticated: testclient.TestClient, +): + """When a user logs in the first time, it should be created""" + assert users_crud.get_user_by_idp_identifier(db, "test") is None + + monkeypatch.setattr( + oidc.OIDCProvider, + "exchange_code_for_tokens", + lambda *args: {"id_token": ""}, + ) + monkeypatch.setattr( + auth_routes, "validate_id_token", lambda *args: {"sub": "sub"} + ) + monkeypatch.setattr( + auth_routes, + "validate_id_token", + lambda *args: { + "sub": "test", + }, + ) + + response = client_unauthenticated.post( + "/api/v1/authentication/tokens", + json={"code": "any", "nonce": "nonce", "code_verifier": "any"}, + ) + assert response.status_code == status.HTTP_200_OK + + assert users_crud.get_user_by_name(db, "test") is not None + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints", "mock_token_creation") +def test_refresh_token( + client_unauthenticated: testclient.TestClient, +): + response = client_unauthenticated.put( + "/api/v1/authentication/tokens", + cookies={ + "refresh_token": "refresh_token", + }, + json={"code": "any", "nonce": "nonce", "code_verifier": "any"}, + ) + + assert response.status_code == status.HTTP_200_OK + + assert "id_token" in response.headers["set-cookie"] + assert "refresh_token" in response.headers["set-cookie"] + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints") +def test_delete_token_cookies( + client_unauthenticated: testclient.TestClient, +): + response = client_unauthenticated.delete("/api/v1/authentication/tokens") + + assert response.status_code == status.HTTP_200_OK + assert 'id_token=""' in response.headers["set-cookie"] + + +def test_missing_refresh_token(client_unauthenticated: testclient.TestClient): + response = client_unauthenticated.put("api/v1/authentication/tokens") + json_response = response.json() + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert json_response["detail"]["err_code"] == "NO_REFRESH_TOKEN_COOKIE" + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints") +def test_validate_id_token_nonce_mismatch( + monkeypatch: pytest.MonkeyPatch, +): + mock_jwt_api_cookie = mock.MagicMock() + mock_jwt_api_cookie.return_value.validate_token.return_value = { + "nonce": "mismatch-nonce" + } + + monkeypatch.setattr(api_key_cookie, "JWTAPIKeyCookie", mock_jwt_api_cookie) + + with pytest.raises(exceptions.NonceMismatchError): + routes.validate_id_token("any", "correct-nonce") + + +@responses.activate +@pytest.mark.usefixtures("mock_auth_endpoints") +def test_validate_id_token_audience_mismatch( + monkeypatch: pytest.MonkeyPatch, +): + mock_jwt_api_cookie = mock.MagicMock() + mock_jwt_api_cookie.return_value.validate_token.return_value = { + "nonce": "mock-nonce", + "aud": "mock-audience", + } + + monkeypatch.setattr(api_key_cookie, "JWTAPIKeyCookie", mock_jwt_api_cookie) + + with pytest.raises(exceptions.UnauthenticatedError): + routes.validate_id_token("any", "mock-nonce") diff --git a/backend/tests/projects/test_projects_routes.py b/backend/tests/projects/test_projects_routes.py index 29b6ff9171..a989b530d0 100644 --- a/backend/tests/projects/test_projects_routes.py +++ b/backend/tests/projects/test_projects_routes.py @@ -19,7 +19,9 @@ def test_get_internal_default_project_as_user( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.USER @@ -40,7 +42,9 @@ def test_get_internal_default_project_as_user( def test_get_projects_as_user_only_shows_default_internal_project( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.USER @@ -59,7 +63,8 @@ def test_get_projects_as_user_only_shows_default_internal_project( @pytest.mark.usefixtures("project_manager") def test_get_projects_as_user_with_project( - client: testclient.TestClient, project: projects_models.DatabaseProject + client: testclient.TestClient, + project: projects_models.DatabaseProject, ): response = client.get("/api/v1/projects") @@ -73,7 +78,9 @@ def test_get_projects_as_user_with_project( def test_get_projects_as_admin( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): project = projects_crud.create_project( db, "test project", visibility=projects_models.Visibility.PRIVATE @@ -94,7 +101,9 @@ def test_get_projects_as_admin( def test_get_internal_projects_as_user( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): project = projects_crud.create_project( db, "test project", visibility=projects_models.Visibility.INTERNAL @@ -115,7 +124,9 @@ def test_get_internal_projects_as_user( def test_get_internal_projects_as_user_without_duplicates( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): user = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.USER @@ -149,7 +160,9 @@ def test_get_internal_projects_as_user_without_duplicates( def test_create_private_project_as_admin( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -172,7 +185,9 @@ def test_create_private_project_as_admin( def test_create_internal_project_as_admin( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -196,7 +211,9 @@ def test_create_internal_project_as_admin( def test_update_project_as_admin( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -295,28 +312,36 @@ def test_delete_pipeline_called_when_archiving_project( @pytest.mark.usefixtures("project_user") -def test_get_project_per_role_user(client: testclient.TestClient): +def test_get_project_per_role_user( + client: testclient.TestClient, +): response = client.get("/api/v1/projects/?minimum_role=user") assert response.status_code == 200 assert len(response.json()) > 0 @pytest.mark.usefixtures("project_user") -def test_get_project_per_role_manager_as_user(client: testclient.TestClient): +def test_get_project_per_role_manager_as_user( + client: testclient.TestClient, +): response = client.get("/api/v1/projects/?minimum_role=manager") assert response.status_code == 200 assert len(response.json()) == 0 @pytest.mark.usefixtures("project_manager") -def test_get_project_per_role_manager(client: testclient.TestClient): +def test_get_project_per_role_manager( + client: testclient.TestClient, +): response = client.get("/api/v1/projects/?minimum_role=manager") assert response.status_code == 200 assert len(response.json()) > 0 def test_get_project_per_role_admin( - client: testclient.TestClient, executor_name: str, db: orm.Session + client: testclient.TestClient, + executor_name: str, + db: orm.Session, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN diff --git a/backend/tests/sessions/hooks/test_guacamole_hook.py b/backend/tests/sessions/hooks/test_guacamole_hook.py index 8c583607ae..851139e835 100644 --- a/backend/tests/sessions/hooks/test_guacamole_hook.py +++ b/backend/tests/sessions/hooks/test_guacamole_hook.py @@ -27,7 +27,7 @@ def fixture_session() -> sessions_models.DatabaseSession: created_at=datetime.datetime.now(), type=sessions_models.SessionType.READONLY, owner=users_models.DatabaseUser( - name="test", role=users_models.Role.USER + name="test", idp_identifier="test", role=users_models.Role.USER ), tool=tool_version.tool, version=tool_version, @@ -141,7 +141,7 @@ def test_guacamole_configuration_hook( "host": "test", }, user=users_models.DatabaseUser( - name="test", role=users_models.Role.USER + name="test", idp_identifier="test", role=users_models.Role.USER ), connection_method=tools_models.GuacamoleConnectionMethod(), ) @@ -180,7 +180,7 @@ def test_fail_if_guacamole_unreachable( "host": "test", }, user=users_models.DatabaseUser( - name="test", role=users_models.Role.USER + name="test", idp_identifier="test", role=users_models.Role.USER ), connection_method=tools_models.GuacamoleConnectionMethod(), ) @@ -208,7 +208,7 @@ def test_guacamole_hook_not_executed_for_http_method( }, db_session=session, user=users_models.DatabaseUser( - name="test", role=users_models.Role.USER + name="test", idp_identifier="test", role=users_models.Role.USER ), connection_method=tools_models.HTTPConnectionMethod(), ) @@ -236,7 +236,7 @@ def test_skip_guacamole_user_deletion_on_404( "host": "test", }, user=users_models.DatabaseUser( - name="test", role=users_models.Role.USER + name="test", idp_identifier="test", role=users_models.Role.USER ), connection_method=tools_models.GuacamoleConnectionMethod(), ) diff --git a/backend/tests/sessions/test_session_environment.py b/backend/tests/sessions/test_session_environment.py index 8df44b934b..3009f2ad12 100644 --- a/backend/tests/sessions/test_session_environment.py +++ b/backend/tests/sessions/test_session_environment.py @@ -145,7 +145,9 @@ class GetSessionsReponseMock: connection_method_id="test", provisioning=[], ), - users_models.DatabaseUser(name="test", role=users_models.Role.USER), + users_models.DatabaseUser( + name="test", idp_identifier="test", role=users_models.Role.USER + ), None, operator, logger, diff --git a/backend/tests/sessions/test_session_routes.py b/backend/tests/sessions/test_session_routes.py index 1f3b15d0b9..8472083b7f 100644 --- a/backend/tests/sessions/test_session_routes.py +++ b/backend/tests/sessions/test_session_routes.py @@ -177,6 +177,7 @@ def test_create_session_without_provisioning( assert kubernetes.sessions +@pytest.mark.usefixtures("executor_name") def test_validate_session_token_with_invalid_session( client: testclient.TestClient, ): diff --git a/backend/tests/settings/teamforcapella/test_t4c_instances.py b/backend/tests/settings/teamforcapella/test_t4c_instances.py index 63e1836c44..89fd9cde3c 100644 --- a/backend/tests/settings/teamforcapella/test_t4c_instances.py +++ b/backend/tests/settings/teamforcapella/test_t4c_instances.py @@ -87,7 +87,9 @@ def test_create_t4c_instance_already_existing_name( @pytest.mark.usefixtures("t4c_instance") def test_get_t4c_instances( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN diff --git a/backend/tests/settings/test_global_configuration.py b/backend/tests/settings/test_global_configuration.py index 2c85319390..9a0655dd06 100644 --- a/backend/tests/settings/test_global_configuration.py +++ b/backend/tests/settings/test_global_configuration.py @@ -14,7 +14,9 @@ @pytest.mark.usefixtures("admin") -def test_get_default_configuration(client: testclient.TestClient): +def test_get_default_configuration( + client: testclient.TestClient, +): """Test that the default configuration is returned if no configuration is set.""" response = client.get("/api/v1/settings/configurations/global") @@ -47,6 +49,7 @@ def test_get_general_configuration( ) +@pytest.mark.usefixtures("executor_name") def test_get_configuration_schema(client: testclient.TestClient): response = client.get("/api/v1/settings/configurations/global/schema") @@ -55,7 +58,9 @@ def test_get_configuration_schema(client: testclient.TestClient): @pytest.mark.usefixtures("admin") -def test_update_general_configuration(client: testclient.TestClient): +def test_update_general_configuration( + client: testclient.TestClient, +): common_metadata = { "privacy_policy_url": "https://example.com/privacy-policy", "imprint_url": "https://example.com/imprint", @@ -109,7 +114,9 @@ def test_update_general_configuration_additional_properties_fails( def test_metadata_is_updated( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): admin = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN diff --git a/backend/tests/test_event_creation.py b/backend/tests/test_event_creation.py index 2589dc6841..c24e4ff234 100644 --- a/backend/tests/test_event_creation.py +++ b/backend/tests/test_event_creation.py @@ -3,10 +3,12 @@ import pytest import sqlalchemy as sa +from fastapi import testclient from sqlalchemy import orm from capellacollab import config from capellacollab.events import models as events_models +from capellacollab.projects import models as projects_models from capellacollab.projects.users import crud as projects_users_crud from capellacollab.projects.users import models as projects_users_models from capellacollab.users import crud as users_crud @@ -16,9 +18,8 @@ def test_create_admin_user_by_system(db): - user: users_models.DatabaseUser = users_crud.get_user_by_name( - db, config.config.initial.admin - ) + user = users_crud.get_user_by_name(db, config.config.initial.admin) + assert user is not None events: list[events_models.DatabaseUserHistoryEvent] = ( get_events_by_user_id(db, user.id) @@ -41,8 +42,13 @@ def test_create_user_created_event(client, db, executor_name, unique_username): ) response = client.post( - "/api/v1/users/", - json={"name": unique_username, "role": "user", "reason": reason}, + "/api/v1/users", + json={ + "name": unique_username, + "role": "user", + "reason": reason, + "idp_identifier": "test", + }, ) events = get_events_by_username(db, unique_username) @@ -59,14 +65,24 @@ def test_create_user_created_event(client, db, executor_name, unique_username): assert event.user_id == int(response.json()["id"]) -def test_user_deleted_cleanup(client, db, executor_name, unique_username): +def test_user_deleted_cleanup( + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, +): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN ) response = client.post( - "/api/v1/users/", - json={"name": unique_username, "role": "user", "reason": reason}, + "/api/v1/users", + json={ + "name": unique_username, + "idp_identifier": "test", + "role": "user", + "reason": reason, + }, ) assert response.status_code == 200 @@ -97,13 +113,13 @@ def test_user_deleted_cleanup(client, db, executor_name, unique_username): ], ) def test_create_assign_user_role_event( - client, - db, - executor_name, - unique_username, - initial_role, - target_role, - expected_event_type, + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, + initial_role: users_models.Role, + target_role: users_models.Role, + expected_event_type: events_models.EventType, ): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -145,13 +161,13 @@ def test_create_assign_user_role_event( ], ) def test_create_user_added_to_project_event( - client, - db, - executor_name, - unique_username, - project, - permission, - expected_permission_event_type, + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, + project: projects_models.DatabaseProject, + permission: projects_users_models.ProjectUserPermission, + expected_permission_event_type: events_models.EventType, ): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -192,7 +208,11 @@ def test_create_user_added_to_project_event( def test_create_user_removed_from_project_event( - client, db, executor_name, unique_username, project + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, + project: projects_models.DatabaseProject, ): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -231,7 +251,11 @@ def test_create_user_removed_from_project_event( def test_create_manager_added_to_project_event( - client, db, executor_name, unique_username, project + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, + project: projects_models.DatabaseProject, ): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -285,14 +309,14 @@ def test_create_manager_added_to_project_event( ], ) def test_create_user_permission_change_event( - client, - db, - executor_name, - unique_username, - project, - initial_permission, - target_permission, - expected_permission_event_type, + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, + project: projects_models.DatabaseProject, + initial_permission: projects_users_models.ProjectUserPermission, + target_permission: projects_users_models.ProjectUserPermission, + expected_permission_event_type: events_models.EventType, ): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN @@ -347,14 +371,14 @@ def test_create_user_permission_change_event( ], ) def test_create_user_role_change_event( - client, - db, - executor_name, - unique_username, - project, - initial_role, - target_role, - expected_role_event_type, + client: testclient.TestClient, + db: orm.Session, + executor_name: str, + unique_username: str, + project: projects_models.DatabaseProject, + initial_role: projects_users_models.ProjectUserRole, + target_role: projects_users_models.ProjectUserRole, + expected_role_event_type: events_models.EventType, ): executor = users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN diff --git a/backend/tests/test_metrics.py b/backend/tests/test_metrics.py index 49aeab99fd..8591703b86 100644 --- a/backend/tests/test_metrics.py +++ b/backend/tests/test_metrics.py @@ -5,11 +5,12 @@ from fastapi import testclient from kubernetes import client as k8s_client +from capellacollab import __main__ from capellacollab.sessions import metrics -def test_metrics_endpoint(client: testclient.TestClient): - response = client.get("/metrics") +def test_metrics_endpoint(client_unauthenticated: testclient.TestClient): + response = client_unauthenticated.get("/metrics") assert response.status_code == 200 assert "# HELP " in response.text diff --git a/backend/tests/tools/test_tools_natures_routes.py b/backend/tests/tools/test_tools_natures_routes.py index 2b003b9715..53ea7ada06 100644 --- a/backend/tests/tools/test_tools_natures_routes.py +++ b/backend/tests/tools/test_tools_natures_routes.py @@ -9,7 +9,8 @@ @pytest.mark.usefixtures("admin") def test_create_tool_nature( - client: testclient.TestClient, tool: tools_models.DatabaseTool + client: testclient.TestClient, + tool: tools_models.DatabaseTool, ): """Test creating a tool nature""" diff --git a/backend/tests/tools/test_tools_routes.py b/backend/tests/tools/test_tools_routes.py index dae6c23c05..4d1fe4cf5e 100644 --- a/backend/tests/tools/test_tools_routes.py +++ b/backend/tests/tools/test_tools_routes.py @@ -46,7 +46,8 @@ def test_create_tool(client: testclient.TestClient): @pytest.mark.usefixtures("admin") def test_update_tool( - client: testclient.TestClient, tool: tools_models.DatabaseTool + client: testclient.TestClient, + tool: tools_models.DatabaseTool, ): """Test updating a tool""" response = client.put( @@ -85,7 +86,8 @@ def test_update_tool( @pytest.mark.usefixtures("admin") def test_delete_tool( - client: testclient.TestClient, tool: tools_models.DatabaseTool + client: testclient.TestClient, + tool: tools_models.DatabaseTool, ): """Test deleting a tool""" response = client.delete( diff --git a/backend/tests/tools/versions/test_tools_version_routes.py b/backend/tests/tools/versions/test_tools_version_routes.py index 953e890a1f..0c7658e88c 100644 --- a/backend/tests/tools/versions/test_tools_version_routes.py +++ b/backend/tests/tools/versions/test_tools_version_routes.py @@ -9,7 +9,8 @@ @pytest.mark.usefixtures("admin") def test_create_tool_version( - client: testclient.TestClient, tool: tools_models.DatabaseTool + client: testclient.TestClient, + tool: tools_models.DatabaseTool, ): """Test creating a tool version""" response = client.post( diff --git a/backend/tests/users/fixtures.py b/backend/tests/users/fixtures.py index 4d614dd7ed..62cbe9c3cc 100644 --- a/backend/tests/users/fixtures.py +++ b/backend/tests/users/fixtures.py @@ -21,10 +21,10 @@ def fixture_executor_name(monkeypatch: pytest.MonkeyPatch) -> str: name = str(uuid.uuid1()) - # pylint: disable=unused-argument async def cookie_passthrough(self, request: fastapi.Request): return name + monkeypatch.setattr(JWTAPIKeyCookie, "__init__", lambda self: None) monkeypatch.setattr(JWTAPIKeyCookie, "__call__", cookie_passthrough) return name diff --git a/backend/tests/users/test_users.py b/backend/tests/users/test_users.py index f6acc8da60..b7c58d7adc 100644 --- a/backend/tests/users/test_users.py +++ b/backend/tests/users/test_users.py @@ -18,7 +18,9 @@ def test_get_user_by_id_admin( - client: testclient.TestClient, db: orm.Session, executor_name: str + client: testclient.TestClient, + db: orm.Session, + executor_name: str, ): users_crud.create_user( db, executor_name, executor_name, None, users_models.Role.ADMIN diff --git a/frontend/Makefile b/frontend/Makefile index a9e40925f2..8b17671742 100644 --- a/frontend/Makefile +++ b/frontend/Makefile @@ -3,6 +3,8 @@ export NG_FORCE_TTY=false +.ONESHELL: + dev: ng serve --host 0.0.0.0 --open @@ -20,11 +22,11 @@ storybook: openapi: python postprocess_openapi_schema.py - mkdir -p /tmp/openapi + OPENAPI_DIR=$$(mktemp -d) docker run --rm \ -v /tmp/openapi.json:/tmp/openapi.json \ -v $$(pwd)/openapi_templates:/tmp/openapi_templates \ - -v /tmp/openapi:/tmp/output \ + -v $$OPENAPI_DIR:/tmp/output \ -u $$(id -u $${USER}):$$(id -g $${USER}) \ openapitools/openapi-generator-cli:v7.7.0 generate \ -i /tmp/openapi.json \ @@ -33,6 +35,6 @@ openapi: --additional-properties=fileNaming=kebab-case,legacyDiscriminatorBehavior=false \ -g typescript-angular \ -o /tmp/output - cp ../LICENSES/.license_header_cc0.txt /tmp/openapi/.openapi-generator/FILES.license - cp ../LICENSES/.license_header_cc0.txt /tmp/openapi/.openapi-generator/VERSION.license - rsync -avh --delete /tmp/openapi/ $$(pwd)/src/app/openapi + cp ../LICENSES/.license_header_cc0.txt $$OPENAPI_DIR/.openapi-generator/FILES.license + cp ../LICENSES/.license_header_cc0.txt $$OPENAPI_DIR/.openapi-generator/VERSION.license + rsync -avh --delete $$OPENAPI_DIR/ $$(pwd)/src/app/openapi diff --git a/frontend/src/app/general/auth/auth-guard/auth-guard.service.ts b/frontend/src/app/general/auth/auth-guard/auth-guard.service.ts index 4b173132b2..e5fc8df23c 100644 --- a/frontend/src/app/general/auth/auth-guard/auth-guard.service.ts +++ b/frontend/src/app/general/auth/auth-guard/auth-guard.service.ts @@ -9,13 +9,13 @@ import { CanActivateFn, RouterStateSnapshot, } from '@angular/router'; -import { AuthService } from 'src/app/services/auth/auth.service'; +import { AuthenticationWrapperService } from 'src/app/services/auth/auth.service'; export const authGuard: CanActivateFn = ( _route: ActivatedRouteSnapshot, _state: RouterStateSnapshot, ) => { - const authService = inject(AuthService); + const authService = inject(AuthenticationWrapperService); if (authService.isLoggedIn()) { return true; diff --git a/frontend/src/app/general/auth/auth-redirect/auth-redirect.component.ts b/frontend/src/app/general/auth/auth-redirect/auth-redirect.component.ts index d5fb875114..86413a64f1 100644 --- a/frontend/src/app/general/auth/auth-redirect/auth-redirect.component.ts +++ b/frontend/src/app/general/auth/auth-redirect/auth-redirect.component.ts @@ -6,7 +6,8 @@ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ToastService } from 'src/app/helpers/toast/toast.service'; -import { AuthService } from 'src/app/services/auth/auth.service'; +import { AuthenticationService } from 'src/app/openapi'; +import { AuthenticationWrapperService } from 'src/app/services/auth/auth.service'; import { UserWrapperService } from 'src/app/services/user/user.service'; @Component({ @@ -18,7 +19,8 @@ export class AuthRedirectComponent implements OnInit { constructor( private route: ActivatedRoute, private toastService: ToastService, - private authService: AuthService, + private authService: AuthenticationWrapperService, + private authenticationService: AuthenticationService, private userService: UserWrapperService, private router: Router, ) {} @@ -66,8 +68,12 @@ export class AuthRedirectComponent implements OnInit { this.authService.SESSION_STORAGE_CODE_VERIFIER_KEY, ); - this.authService - .getIdentityToken(params.code, nonce, codeVerifier) + this.authenticationService + .getIdentityToken({ + code: params.code, + nonce, + code_verifier: codeVerifier, + }) .subscribe({ next: () => { localStorage.setItem(this.authService.LOGGED_IN_KEY, 'true'); diff --git a/frontend/src/app/general/auth/auth/auth.component.ts b/frontend/src/app/general/auth/auth/auth.component.ts index 7826f04caa..d17dd453ef 100644 --- a/frontend/src/app/general/auth/auth/auth.component.ts +++ b/frontend/src/app/general/auth/auth/auth.component.ts @@ -9,7 +9,7 @@ import { MatButton } from '@angular/material/button'; import { ActivatedRoute, ParamMap } from '@angular/router'; import { MetadataService } from 'src/app/general/metadata/metadata.service'; import { PageLayoutService } from 'src/app/page-layout/page-layout.service'; -import { AuthService } from 'src/app/services/auth/auth.service'; +import { AuthenticationWrapperService } from 'src/app/services/auth/auth.service'; @Component({ selector: 'app-auth', @@ -30,7 +30,7 @@ export class AuthComponent implements OnInit { constructor( public metadataService: MetadataService, - public authService: AuthService, + public authService: AuthenticationWrapperService, private pageLayoutService: PageLayoutService, private route: ActivatedRoute, ) { diff --git a/frontend/src/app/general/auth/http-interceptor/auth.interceptor.ts b/frontend/src/app/general/auth/http-interceptor/auth.interceptor.ts index 93bb384a60..f85a5c179d 100644 --- a/frontend/src/app/general/auth/http-interceptor/auth.interceptor.ts +++ b/frontend/src/app/general/auth/http-interceptor/auth.interceptor.ts @@ -14,13 +14,15 @@ import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { catchError, switchMap } from 'rxjs/operators'; -import { AuthService } from 'src/app/services/auth/auth.service'; +import { AuthenticationService } from 'src/app/openapi'; +import { AuthenticationWrapperService } from 'src/app/services/auth/auth.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor( private router: Router, - private authService: AuthService, + private authService: AuthenticationWrapperService, + private authenticationService: AuthenticationService, ) {} intercept( @@ -43,7 +45,7 @@ export class AuthInterceptor implements HttpInterceptor { if (err.status === 401) { localStorage.setItem(this.authService.LOGGED_IN_KEY, 'false'); if (err.error.detail.err_code == 'TOKEN_SIGNATURE_EXPIRED') { - return this.authService.performTokenRefresh().pipe( + return this.authenticationService.refreshIdentityToken().pipe( switchMap(() => { return next.handle(request); }), diff --git a/frontend/src/app/general/auth/logout/logout-redirect/logout-redirect.component.ts b/frontend/src/app/general/auth/logout/logout-redirect/logout-redirect.component.ts index c4e707d1d2..775a8641db 100644 --- a/frontend/src/app/general/auth/logout/logout-redirect/logout-redirect.component.ts +++ b/frontend/src/app/general/auth/logout/logout-redirect/logout-redirect.component.ts @@ -5,7 +5,7 @@ import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; -import { AuthService } from 'src/app/services/auth/auth.service'; +import { AuthenticationWrapperService } from 'src/app/services/auth/auth.service'; @Component({ selector: 'app-logout-redirect', @@ -15,7 +15,7 @@ import { AuthService } from 'src/app/services/auth/auth.service'; }) export class LogoutRedirectComponent implements OnInit { constructor( - private authService: AuthService, + private authService: AuthenticationWrapperService, private router: Router, ) {} diff --git a/frontend/src/app/general/header/header.component.ts b/frontend/src/app/general/header/header.component.ts index 5f31abaedd..d6cbea9a48 100644 --- a/frontend/src/app/general/header/header.component.ts +++ b/frontend/src/app/general/header/header.component.ts @@ -9,7 +9,7 @@ import { MatIcon } from '@angular/material/icon'; import { MatMenu, MatMenuItem, MatMenuTrigger } from '@angular/material/menu'; import { RouterLink } from '@angular/router'; import { NavBarService } from 'src/app/general/nav-bar/nav-bar.service'; -import { AuthService } from '../../services/auth/auth.service'; +import { AuthenticationWrapperService } from '../../services/auth/auth.service'; import { UserWrapperService } from '../../services/user/user.service'; import { BreadcrumbsComponent } from '../breadcrumbs/breadcrumbs.component'; @@ -31,7 +31,7 @@ import { BreadcrumbsComponent } from '../breadcrumbs/breadcrumbs.component'; }) export class HeaderComponent { constructor( - public authService: AuthService, + public authService: AuthenticationWrapperService, public userService: UserWrapperService, public navBarService: NavBarService, ) {} diff --git a/frontend/src/app/general/nav-bar-menu/nav-bar-menu.component.ts b/frontend/src/app/general/nav-bar-menu/nav-bar-menu.component.ts index 6c1af1eb88..45b0f695fd 100644 --- a/frontend/src/app/general/nav-bar-menu/nav-bar-menu.component.ts +++ b/frontend/src/app/general/nav-bar-menu/nav-bar-menu.component.ts @@ -9,7 +9,7 @@ import { MatIcon } from '@angular/material/icon'; import { MatList, MatListItem } from '@angular/material/list'; import { RouterLink } from '@angular/router'; import { NavBarService } from 'src/app/general/nav-bar/nav-bar.service'; -import { AuthService } from 'src/app/services/auth/auth.service'; +import { AuthenticationWrapperService } from 'src/app/services/auth/auth.service'; import { UserWrapperService } from 'src/app/services/user/user.service'; @Component({ @@ -21,7 +21,7 @@ import { UserWrapperService } from 'src/app/services/user/user.service'; }) export class NavBarMenuComponent { constructor( - public authService: AuthService, + public authService: AuthenticationWrapperService, public navBarService: NavBarService, public userService: UserWrapperService, ) {} diff --git a/frontend/src/app/openapi/.openapi-generator/FILES b/frontend/src/app/openapi/.openapi-generator/FILES index ef2e6ad6e4..0a149ccfcd 100644 --- a/frontend/src/app/openapi/.openapi-generator/FILES +++ b/frontend/src/app/openapi/.openapi-generator/FILES @@ -1,8 +1,10 @@ api.module.ts api/api.ts -api/default.service.ts +api/authentication.service.ts +api/configuration.service.ts api/events.service.ts api/health.service.ts +api/integrations-pure-variants.service.ts api/metadata.service.ts api/notices.service.ts api/projects-events.service.ts @@ -25,6 +27,7 @@ api/users.service.ts configuration.ts encoder.ts index.ts +model/authorization-response.ts model/backup-pipeline-run.ts model/backup.ts model/base-user.ts diff --git a/frontend/src/app/openapi/api/api.ts b/frontend/src/app/openapi/api/api.ts index 7de12560a8..64dcdb5246 100644 --- a/frontend/src/app/openapi/api/api.ts +++ b/frontend/src/app/openapi/api/api.ts @@ -9,12 +9,16 @@ + To generate a new version, run `make openapi` in the root directory of this repository. */ -export * from './default.service'; -import { DefaultService } from './default.service'; +export * from './authentication.service'; +import { AuthenticationService } from './authentication.service'; +export * from './configuration.service'; +import { ConfigurationService } from './configuration.service'; export * from './events.service'; import { EventsService } from './events.service'; export * from './health.service'; import { HealthService } from './health.service'; +export * from './integrations-pure-variants.service'; +import { IntegrationsPureVariantsService } from './integrations-pure-variants.service'; export * from './metadata.service'; import { MetadataService } from './metadata.service'; export * from './notices.service'; @@ -53,4 +57,4 @@ export * from './users-token.service'; import { UsersTokenService } from './users-token.service'; export * from './users-workspaces.service'; import { UsersWorkspacesService } from './users-workspaces.service'; -export const APIS = [DefaultService, EventsService, HealthService, MetadataService, NoticesService, ProjectsService, ProjectsEventsService, ProjectsModelsService, ProjectsModelsBackupsService, ProjectsModelsDiagramsService, ProjectsModelsGitService, ProjectsModelsModelComplexityBadgeService, ProjectsModelsRestrictionsService, ProjectsModelsT4CService, SessionsService, SettingsModelsourcesGitService, SettingsModelsourcesT4CService, ToolsService, UsersService, UsersSessionsService, UsersTokenService, UsersWorkspacesService]; +export const APIS = [AuthenticationService, ConfigurationService, EventsService, HealthService, IntegrationsPureVariantsService, MetadataService, NoticesService, ProjectsService, ProjectsEventsService, ProjectsModelsService, ProjectsModelsBackupsService, ProjectsModelsDiagramsService, ProjectsModelsGitService, ProjectsModelsModelComplexityBadgeService, ProjectsModelsRestrictionsService, ProjectsModelsT4CService, SessionsService, SettingsModelsourcesGitService, SettingsModelsourcesT4CService, ToolsService, UsersService, UsersSessionsService, UsersTokenService, UsersWorkspacesService]; diff --git a/frontend/src/app/openapi/api/authentication.service.ts b/frontend/src/app/openapi/api/authentication.service.ts new file mode 100644 index 0000000000..c254aeb795 --- /dev/null +++ b/frontend/src/app/openapi/api/authentication.service.ts @@ -0,0 +1,424 @@ +/* + * SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Capella Collaboration + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit the class manually. + + To generate a new version, run `make openapi` in the root directory of this repository. + */ + +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { AuthorizationResponse } from '../model/authorization-response'; +// @ts-ignore +import { HTTPValidationError } from '../model/http-validation-error'; +// @ts-ignore +import { Role } from '../model/role'; +// @ts-ignore +import { TokenRequest } from '../model/token-request'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class AuthenticationService { + + protected basePath = 'http://localhost'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; + if (firstBasePath != undefined) { + basePath = firstBasePath; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substring(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Get Authorization Url + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getAuthorizationUrl(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorizationUrl(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorizationUrl(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorizationUrl(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/authentication`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Get Identity Token + * @param tokenRequest + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getIdentityToken(tokenRequest: TokenRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getIdentityToken(tokenRequest: TokenRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityToken(tokenRequest: TokenRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityToken(tokenRequest: TokenRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (tokenRequest === null || tokenRequest === undefined) { + throw new Error('Required parameter tokenRequest was null or undefined when calling getIdentityToken.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/authentication/tokens`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: tokenRequest, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Logout + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/authentication/tokens`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Refresh Identity Token + * @param refreshToken + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public refreshIdentityToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public refreshIdentityToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshIdentityToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshIdentityToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/authentication/tokens`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Validate Jwt Token + * @param scope + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public validateJwtToken(scope?: Role, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public validateJwtToken(scope?: Role, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public validateJwtToken(scope?: Role, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public validateJwtToken(scope?: Role, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (scope !== undefined && scope !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + scope, 'scope'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/authentication/tokens`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + +} diff --git a/frontend/src/app/openapi/api/configuration.service.ts b/frontend/src/app/openapi/api/configuration.service.ts new file mode 100644 index 0000000000..bb2d495d52 --- /dev/null +++ b/frontend/src/app/openapi/api/configuration.service.ts @@ -0,0 +1,307 @@ +/* + * SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Capella Collaboration + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit the class manually. + + To generate a new version, run `make openapi` in the root directory of this repository. + */ + +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { GlobalConfigurationInput } from '../model/global-configuration-input'; +// @ts-ignore +import { GlobalConfigurationOutput } from '../model/global-configuration-output'; +// @ts-ignore +import { HTTPValidationError } from '../model/http-validation-error'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class ConfigurationService { + + protected basePath = 'http://localhost'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; + if (firstBasePath != undefined) { + basePath = firstBasePath; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substring(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Get Configuration + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getConfiguration(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getConfiguration(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getConfiguration(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getConfiguration(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (PersonalAccessToken) required + localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/configurations/global`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Get Json Schema + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getJsonSchema(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getJsonSchema(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getJsonSchema(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getJsonSchema(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/configurations/global/schema`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Update Configuration + * @param globalConfigurationInput + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (globalConfigurationInput === null || globalConfigurationInput === undefined) { + throw new Error('Required parameter globalConfigurationInput was null or undefined when calling updateConfiguration.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (PersonalAccessToken) required + localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/configurations/global`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: globalConfigurationInput, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + +} diff --git a/frontend/src/app/openapi/api/default.service.ts b/frontend/src/app/openapi/api/default.service.ts deleted file mode 100644 index b6094b8cb2..0000000000 --- a/frontend/src/app/openapi/api/default.service.ts +++ /dev/null @@ -1,960 +0,0 @@ -/* - * SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors - * SPDX-License-Identifier: Apache-2.0 - * - * Capella Collaboration - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * Do not edit the class manually. - + To generate a new version, run `make openapi` in the root directory of this repository. - */ - -/* tslint:disable:no-unused-variable member-ordering */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; - -// @ts-ignore -import { GlobalConfigurationInput } from '../model/global-configuration-input'; -// @ts-ignore -import { GlobalConfigurationOutput } from '../model/global-configuration-output'; -// @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; -// @ts-ignore -import { PureVariantsLicensesInput } from '../model/pure-variants-licenses-input'; -// @ts-ignore -import { PureVariantsLicensesOutput } from '../model/pure-variants-licenses-output'; -// @ts-ignore -import { Role } from '../model/role'; -// @ts-ignore -import { TokenRequest } from '../model/token-request'; - -// @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; - - - -@Injectable({ - providedIn: 'root' -}) -export class DefaultService { - - protected basePath = 'http://localhost'; - public defaultHeaders = new HttpHeaders(); - public configuration = new Configuration(); - public encoder: HttpParameterCodec; - - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { - if (configuration) { - this.configuration = configuration; - } - if (typeof this.configuration.basePath !== 'string') { - const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; - if (firstBasePath != undefined) { - basePath = firstBasePath; - } - - if (typeof basePath !== 'string') { - basePath = this.basePath; - } - this.configuration.basePath = basePath; - } - this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); - } - - /** - * @param consumes string[] mime-types - * @return true: consumes contains 'multipart/form-data', false: otherwise - */ - private canConsumeForm(consumes: string[]): boolean { - const form = 'multipart/form-data'; - for (const consume of consumes) { - if (form === consume) { - return true; - } - } - return false; - } - - // @ts-ignore - private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { - if (typeof value === "object" && value instanceof Date === false) { - httpParams = this.addToHttpParamsRecursive(httpParams, value); - } else { - httpParams = this.addToHttpParamsRecursive(httpParams, value, key); - } - return httpParams; - } - - private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { - if (value == null) { - return httpParams; - } - - if (typeof value === "object") { - if (Array.isArray(value)) { - (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); - } else if (value instanceof Date) { - if (key != null) { - httpParams = httpParams.append(key, (value as Date).toISOString().substring(0, 10)); - } else { - throw Error("key may not be null if value is Date"); - } - } else { - Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( - httpParams, value[k], key != null ? `${key}.${k}` : k)); - } - } else if (key != null) { - httpParams = httpParams.append(key, value); - } else { - throw Error("key may not be null if value is not object or array"); - } - return httpParams; - } - - /** - * Create The Identity Token - * @param tokenRequest - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public createTheIdentityToken(tokenRequest: TokenRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createTheIdentityToken(tokenRequest: TokenRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createTheIdentityToken(tokenRequest: TokenRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createTheIdentityToken(tokenRequest: TokenRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (tokenRequest === null || tokenRequest === undefined) { - throw new Error('Required parameter tokenRequest was null or undefined when calling createTheIdentityToken.'); - } - - let localVarHeaders = this.defaultHeaders; - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/authentication/tokens`; - return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: tokenRequest, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Delete License Key File - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public deleteLicenseKeyFile(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteLicenseKeyFile(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteLicenseKeyFile(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteLicenseKeyFile(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarCredential: string | undefined; - // authentication (PersonalAccessToken) required - localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); - if (localVarCredential) { - localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); - } - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/integrations/pure-variants/license-keys/0`; - return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Get Configuration - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getConfiguration(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getConfiguration(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getConfiguration(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getConfiguration(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarCredential: string | undefined; - // authentication (PersonalAccessToken) required - localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); - if (localVarCredential) { - localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); - } - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/configurations/global`; - return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Get Json Schema - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getJsonSchema(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getJsonSchema(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getJsonSchema(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getJsonSchema(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/configurations/global/schema`; - return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Get License - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getLicense(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getLicense(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getLicense(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getLicense(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarCredential: string | undefined; - // authentication (PersonalAccessToken) required - localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); - if (localVarCredential) { - localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); - } - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/integrations/pure-variants`; - return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Get The Authorization Url For The Oauth Server - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getTheAuthorizationURLForTheOAuthServer(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<{ [key: string]: string | null; }>; - public getTheAuthorizationURLForTheOAuthServer(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTheAuthorizationURLForTheOAuthServer(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTheAuthorizationURLForTheOAuthServer(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/authentication`; - return this.httpClient.request<{ [key: string]: string | null; }>('get', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Refresh The Identity Token - * @param refreshToken - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public refreshTheIdentityToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public refreshTheIdentityToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshTheIdentityToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshTheIdentityToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/authentication/tokens`; - return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Remove The Token (Log Out) - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public removeTheTokenLogOut(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public removeTheTokenLogOut(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public removeTheTokenLogOut(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public removeTheTokenLogOut(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarHeaders = this.defaultHeaders; - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/authentication/tokens`; - return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Set License - * @param pureVariantsLicensesInput - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (pureVariantsLicensesInput === null || pureVariantsLicensesInput === undefined) { - throw new Error('Required parameter pureVariantsLicensesInput was null or undefined when calling setLicense.'); - } - - let localVarHeaders = this.defaultHeaders; - - let localVarCredential: string | undefined; - // authentication (PersonalAccessToken) required - localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); - if (localVarCredential) { - localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); - } - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/integrations/pure-variants`; - return this.httpClient.request('patch', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: pureVariantsLicensesInput, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Update Configuration - * @param globalConfigurationInput - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateConfiguration(globalConfigurationInput: GlobalConfigurationInput, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (globalConfigurationInput === null || globalConfigurationInput === undefined) { - throw new Error('Required parameter globalConfigurationInput was null or undefined when calling updateConfiguration.'); - } - - let localVarHeaders = this.defaultHeaders; - - let localVarCredential: string | undefined; - // authentication (PersonalAccessToken) required - localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); - if (localVarCredential) { - localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); - } - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/configurations/global`; - return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: globalConfigurationInput, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Upload License Key File - * @param file - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public uploadLicenseKeyFile(file: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public uploadLicenseKeyFile(file: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public uploadLicenseKeyFile(file: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public uploadLicenseKeyFile(file: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (file === null || file === undefined) { - throw new Error('Required parameter file was null or undefined when calling uploadLicenseKeyFile.'); - } - - let localVarHeaders = this.defaultHeaders; - - let localVarCredential: string | undefined; - // authentication (PersonalAccessToken) required - localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); - if (localVarCredential) { - localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); - } - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - // to determine the Content-Type header - const consumes: string[] = [ - 'multipart/form-data' - ]; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any; }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - // use FormData to transmit files using content-type "multipart/form-data" - // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data - localVarUseForm = canConsumeForm; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({encoder: this.encoder}); - } - - if (file !== undefined) { - localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/settings/integrations/pure-variants/license-keys`; - return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - - /** - * Validate The Token - * @param scope - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public validateTheToken(scope?: Role, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public validateTheToken(scope?: Role, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public validateTheToken(scope?: Role, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public validateTheToken(scope?: Role, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - if (scope !== undefined && scope !== null) { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - scope, 'scope'); - } - - let localVarHeaders = this.defaultHeaders; - - let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; - if (localVarHttpHeaderAcceptSelected === undefined) { - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); - } - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - let localVarHttpContext: HttpContext | undefined = options && options.context; - if (localVarHttpContext === undefined) { - localVarHttpContext = new HttpContext(); - } - - let localVarTransferCache: boolean | undefined = options && options.transferCache; - if (localVarTransferCache === undefined) { - localVarTransferCache = true; - } - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/v1/authentication/tokens`; - return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - withCredentials: this.configuration.withCredentials, - headers: localVarHeaders, - observe: observe, - transferCache: localVarTransferCache, - reportProgress: reportProgress - } - ); - } - -} diff --git a/frontend/src/app/openapi/api/integrations-pure-variants.service.ts b/frontend/src/app/openapi/api/integrations-pure-variants.service.ts new file mode 100644 index 0000000000..bd5f818ad8 --- /dev/null +++ b/frontend/src/app/openapi/api/integrations-pure-variants.service.ts @@ -0,0 +1,421 @@ +/* + * SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Capella Collaboration + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit the class manually. + + To generate a new version, run `make openapi` in the root directory of this repository. + */ + +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { HTTPValidationError } from '../model/http-validation-error'; +// @ts-ignore +import { PureVariantsLicensesInput } from '../model/pure-variants-licenses-input'; +// @ts-ignore +import { PureVariantsLicensesOutput } from '../model/pure-variants-licenses-output'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class IntegrationsPureVariantsService { + + protected basePath = 'http://localhost'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; + if (firstBasePath != undefined) { + basePath = firstBasePath; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substring(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Delete License Key File + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteLicenseKeyFile(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteLicenseKeyFile(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteLicenseKeyFile(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteLicenseKeyFile(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (PersonalAccessToken) required + localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/integrations/pure-variants/license-keys/0`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Get License + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getLicense(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getLicense(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getLicense(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getLicense(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (PersonalAccessToken) required + localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/integrations/pure-variants`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Set License + * @param pureVariantsLicensesInput + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public setLicense(pureVariantsLicensesInput: PureVariantsLicensesInput, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (pureVariantsLicensesInput === null || pureVariantsLicensesInput === undefined) { + throw new Error('Required parameter pureVariantsLicensesInput was null or undefined when calling setLicense.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (PersonalAccessToken) required + localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/integrations/pure-variants`; + return this.httpClient.request('patch', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: pureVariantsLicensesInput, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + + /** + * Upload License Key File + * @param file + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadLicenseKeyFile(file: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public uploadLicenseKeyFile(file: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public uploadLicenseKeyFile(file: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public uploadLicenseKeyFile(file: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (file === null || file === undefined) { + throw new Error('Required parameter file was null or undefined when calling uploadLicenseKeyFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (PersonalAccessToken) required + localVarCredential = this.configuration.lookupCredential('PersonalAccessToken'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + let localVarTransferCache: boolean | undefined = options && options.transferCache; + if (localVarTransferCache === undefined) { + localVarTransferCache = true; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/v1/settings/integrations/pure-variants/license-keys`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + transferCache: localVarTransferCache, + reportProgress: reportProgress + } + ); + } + +} diff --git a/frontend/src/app/openapi/model/patch-user-role-request.ts b/frontend/src/app/openapi/model/authorization-response.ts similarity index 71% rename from frontend/src/app/openapi/model/patch-user-role-request.ts rename to frontend/src/app/openapi/model/authorization-response.ts index fd5312abae..816254081b 100644 --- a/frontend/src/app/openapi/model/patch-user-role-request.ts +++ b/frontend/src/app/openapi/model/authorization-response.ts @@ -9,14 +9,12 @@ + To generate a new version, run `make openapi` in the root directory of this repository. */ -import { Role } from './role'; -export interface PatchUserRoleRequest { - role: Role; - reason: string; +export interface AuthorizationResponse { + auth_url: string; + state: string; + nonce: string; + code_verifier: string; } -export namespace PatchUserRoleRequest { -} - diff --git a/frontend/src/app/openapi/model/base-user.ts b/frontend/src/app/openapi/model/base-user.ts index e5f16e749c..8fce88990b 100644 --- a/frontend/src/app/openapi/model/base-user.ts +++ b/frontend/src/app/openapi/model/base-user.ts @@ -16,6 +16,7 @@ export interface BaseUser { id: number; name: string; idp_identifier: string; + email: string | null; role: Role; } export namespace BaseUser { diff --git a/frontend/src/app/openapi/model/models.ts b/frontend/src/app/openapi/model/models.ts index 098253c3f6..fbf5f03616 100644 --- a/frontend/src/app/openapi/model/models.ts +++ b/frontend/src/app/openapi/model/models.ts @@ -9,6 +9,7 @@ + To generate a new version, run `make openapi` in the root directory of this repository. */ +export * from './authorization-response'; export * from './backup'; export * from './backup-pipeline-run'; export * from './base-user'; diff --git a/frontend/src/app/openapi/model/user.ts b/frontend/src/app/openapi/model/user.ts index d3af471a20..ca7bd058ce 100644 --- a/frontend/src/app/openapi/model/user.ts +++ b/frontend/src/app/openapi/model/user.ts @@ -16,6 +16,7 @@ export interface User { id: number; name: string; idp_identifier: string; + email: string | null; role: Role; created: string | null; last_login: string | null; diff --git a/frontend/src/app/services/auth/auth.service.ts b/frontend/src/app/services/auth/auth.service.ts index e4ac3457ac..f35ecf6e48 100644 --- a/frontend/src/app/services/auth/auth.service.ts +++ b/frontend/src/app/services/auth/auth.service.ts @@ -3,48 +3,18 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; -import { Observable } from 'rxjs'; -import { environment } from 'src/environments/environment'; +import { AuthenticationService } from 'src/app/openapi'; @Injectable({ providedIn: 'root', }) -export class AuthService { - SESSION_STORAGE_NONCE_KEY = 'nonce'; - SESSION_STORAGE_CODE_VERIFIER_KEY = 'coderVerifier'; - LOGGED_IN_KEY = 'loggedIn'; +export class AuthenticationWrapperService { + SESSION_STORAGE_NONCE_KEY = 'CCM_NONCE'; + SESSION_STORAGE_CODE_VERIFIER_KEY = 'CCM_CODE_VERIFIER'; + LOGGED_IN_KEY = 'CCM_LOGGED_IN'; - constructor(private http: HttpClient) {} - - getRedirectURL(): Observable { - return this.http.get( - environment.backend_url + '/authentication', - ); - } - - getIdentityToken( - code: string, - nonce: string, - code_verifier: string, - ): Observable { - return this.http.post( - environment.backend_url + '/authentication/tokens', - { - code, - nonce, - code_verifier, - }, - ); - } - - performTokenRefresh(): Observable { - return this.http.put( - environment.backend_url + '/authentication/tokens', - {}, - ); - } + constructor(private authenticationService: AuthenticationService) {} isLoggedIn(): boolean { const loggedIn = localStorage.getItem(this.LOGGED_IN_KEY); @@ -52,7 +22,7 @@ export class AuthService { } login(redirectTo: string) { - this.getRedirectURL().subscribe((res) => { + this.authenticationService.getAuthorizationUrl().subscribe((res) => { sessionStorage.setItem(res.state, redirectTo); sessionStorage.setItem(this.SESSION_STORAGE_NONCE_KEY, res.nonce); sessionStorage.setItem( @@ -66,9 +36,7 @@ export class AuthService { logOut() { localStorage.setItem('GUAC_AUTH', ''); localStorage.setItem(this.LOGGED_IN_KEY, 'false'); - return this.http - .delete(environment.backend_url + '/authentication/tokens') - .subscribe(); + this.authenticationService.logout().subscribe(); } } diff --git a/frontend/src/app/services/user/user.service.ts b/frontend/src/app/services/user/user.service.ts index 221f09d13f..1a20572d3e 100644 --- a/frontend/src/app/services/user/user.service.ts +++ b/frontend/src/app/services/user/user.service.ts @@ -6,7 +6,7 @@ import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { UsersService, User } from 'src/app/openapi'; -import { AuthService } from '../auth/auth.service'; +import { AuthenticationWrapperService } from '../auth/auth.service'; @Injectable({ providedIn: 'root', @@ -20,7 +20,7 @@ export class UserWrapperService { } constructor( - private authService: AuthService, + private authService: AuthenticationWrapperService, private usersService: UsersService, ) { this.updateOwnUser(); diff --git a/frontend/src/app/sessions/user-sessions-wrapper/active-sessions/active-sessions.stories.ts b/frontend/src/app/sessions/user-sessions-wrapper/active-sessions/active-sessions.stories.ts index d0f5149a5b..ad4861bff2 100644 --- a/frontend/src/app/sessions/user-sessions-wrapper/active-sessions/active-sessions.stories.ts +++ b/frontend/src/app/sessions/user-sessions-wrapper/active-sessions/active-sessions.stories.ts @@ -207,6 +207,8 @@ export const SessionSharedWithUser: Story = { id: 1, name: 'user_1', role: 'administrator', + email: null, + idp_identifier: 'user_1', }, created_at: '2024-04-29T15:00:00Z', }, @@ -215,6 +217,8 @@ export const SessionSharedWithUser: Story = { id: 2, name: 'user_2', role: 'user', + email: null, + idp_identifier: 'user_2', }, created_at: '2024-04-29T15:00:00Z', }, diff --git a/frontend/src/app/users/users-profile/user-information/user-information.component.html b/frontend/src/app/users/users-profile/user-information/user-information.component.html index ad41f8d116..f2ca48a828 100644 --- a/frontend/src/app/users/users-profile/user-information/user-information.component.html +++ b/frontend/src/app/users/users-profile/user-information/user-information.component.html @@ -2,7 +2,6 @@ ~ SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors ~ SPDX-License-Identifier: Apache-2.0 --> - @if (user && userService.user?.role === "administrator") {

User information

@@ -16,6 +15,9 @@

User information

}
Identity provider identifier: {{ user.idp_identifier }}
+ @if (user.email) { +
Email: {{ user.email }}
+ } @if (userEvents) {
diff --git a/frontend/src/app/users/users-profile/user-information/user-information.stories.ts b/frontend/src/app/users/users-profile/user-information/user-information.stories.ts index 6b9626837b..6421b9365d 100644 --- a/frontend/src/app/users/users-profile/user-information/user-information.stories.ts +++ b/frontend/src/app/users/users-profile/user-information/user-information.stories.ts @@ -20,11 +20,17 @@ const meta: Meta = { { provide: UserWrapperService, useFactory: () => - new MockUserService({ ...mockUser, role: 'administrator' }), + new MockUserService({ + ...mockUser, + role: 'administrator', + }), }, ], }), ], + args: { + _user: { ...mockUser, id: 0 }, + }, }; export default meta; diff --git a/frontend/src/storybook/user.ts b/frontend/src/storybook/user.ts index 4375ad935e..f03082329b 100644 --- a/frontend/src/storybook/user.ts +++ b/frontend/src/storybook/user.ts @@ -13,7 +13,8 @@ import { export const mockUser: Readonly = { id: 1, name: 'fakeUser', - idp_identifier: 'fakeIdPIdentifier', + idp_identifier: 'identifier', + email: 'test@example.com', role: 'user', created: '2024-04-29T14:00:00Z', last_login: '2024-04-29T14:59:00Z', diff --git a/helm/config/oauth.json b/helm/config/oauth.json index 33c8ea93fa..c955ce90f4 100644 --- a/helm/config/oauth.json +++ b/helm/config/oauth.json @@ -1,24 +1,7 @@ { - "interactiveLogin": true, - "httpServer": { - "type": "NettyWrapper" - }, - "tokenCallbacks": [ - { - "issuerId": "issuer1", - "tokenExpiry": 120, - "requestMappings": [ - { - "requestParam": "scope", - "match": "openid", - "claims": { - "sub": "subByScope", - "aud": [ - "audByScope" - ] - } - } - ] - } - ] + "interactiveLogin": true, + "httpServer": { + "type": "NettyWrapper" + }, + "tokenCallbacks": [] } diff --git a/helm/templates/mock/oauth.deployment.yaml b/helm/templates/mock/oauth.deployment.yaml index 1f64dbac5b..33a69cbb97 100644 --- a/helm/templates/mock/oauth.deployment.yaml +++ b/helm/templates/mock/oauth.deployment.yaml @@ -33,7 +33,7 @@ spec: {{ if .Values.docker.images.mockOauth2Server }} image: {{ .Values.docker.images.mockOauth2Server }} {{ else }} - image: {{ .Values.docker.registry.github }}/navikt/mock-oauth2-server:0.5.8 + image: {{ .Values.docker.registry.github }}/navikt/mock-oauth2-server:2.1.8 {{ end }} ports: - name: http