Compare commits

...
Author SHA1 Message Date
Mats Paul Tončik 0e80cc3fc3 feat(auth): completed auth restructure
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 15:59:34 +02:00
Mats Paul Tončik a464a95c4e fix(frontend/organizations): unfucked everything (again) 2026-07-05 00:19:06 +02:00
Mats Paul Tončik 2264582d1e fix(frontend/accounts): unfucked everything 2026-07-04 23:49:39 +02:00
Mats Paul Tončik e648ea1ec4 feat(backend/auth): added otk response model 2026-07-04 22:37:34 +02:00
farajollahi 8805ec9e57 Merge pull request 'active-deactive-accounts' (#187) from active-deactive-accounts into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #187
2026-07-03 19:24:15 +02:00
Mats Paul Tončik 7b4c459fd8 fix(frontend/register): fixed wrong variable name
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 17:00:19 +02:00
Mats Paul Tončik 08824bd7ba Merge remote-tracking branch 'origin/dev' into auth-restructure
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-03 16:57:10 +02:00
Mats Paul Tončik 1297f85124 feat(auth): started auth restructure
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-03 16:56:17 +02:00
70 changed files with 3153 additions and 4650 deletions
@@ -1,12 +1,11 @@
import uuid import uuid
from typing import Optional from typing import Annotated, Optional
from fastapi import APIRouter, Depends, Query, Response, status from fastapi import APIRouter, Query, Response, status
from sqlmodel import Session
from inse.auth import service as auth_service from inse.auth import service as auth_service
from inse.auth.model import AccessToken from inse.auth.model import AccessTokenMetadata
from inse.database import get_session from inse.database import SessionDep
from inse.tags import Tags from inse.tags import Tags
from . import service from . import service
@@ -24,11 +23,10 @@ router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
@router.get( @router.get(
"/me", "/me",
operation_id="getCurrentAccount", operation_id="getCurrentAccount",
response_model=AccountProfile,
) )
async def get_current_account( async def get_current_account(
session: Session = Depends(get_session), session: SessionDep,
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile: ) -> AccountProfile:
return service.get_current_account(session=session, access_token=access_token) return service.get_current_account(session=session, access_token=access_token)
@@ -36,16 +34,15 @@ async def get_current_account(
@router.get( @router.get(
"", "",
operation_id="listAccounts", operation_id="listAccounts",
response_model=AccountPage,
) )
async def list_accounts( async def list_accounts(
page: int = Query(default=0, ge=0), session: SessionDep,
page_size: int = Query(default=25, ge=1, le=100), page: Annotated[int, Query(ge=0)] = 0,
offset: Optional[int] = Query(default=None, ge=0), page_size: Annotated[int, Query(ge=1, le=100)] = 10,
search: Optional[str] = Query(default=None), offset: Annotated[int, Query(ge=0)] = 0,
organization_id: Optional[uuid.UUID] = Query(default=None), search: Annotated[Optional[str], Query()] = None,
session: Session = Depends(get_session), organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage: ) -> AccountPage:
return service.list_accounts( return service.list_accounts(
session=session, session=session,
@@ -61,13 +58,12 @@ async def list_accounts(
@router.post( @router.post(
"", "",
operation_id="createAccount", operation_id="createAccount",
response_model=AccountProfile,
status_code=status.HTTP_201_CREATED, status_code=status.HTTP_201_CREATED,
) )
async def create_account( async def create_account(
payload: CreateAccountRequest, payload: CreateAccountRequest,
session: Session = Depends(get_session), session: SessionDep,
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile: ) -> AccountProfile:
return service.create_account( return service.create_account(
session=session, session=session,
@@ -79,11 +75,10 @@ async def create_account(
@router.get( @router.get(
"/organizations", "/organizations",
operation_id="listAccountOrganizations", operation_id="listAccountOrganizations",
response_model=list[OrganizationProfile],
) )
async def list_organizations( async def list_organizations(
session: Session = Depends(get_session), session: SessionDep,
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[OrganizationProfile]: ) -> list[OrganizationProfile]:
return service.list_organizations(session=session, access_token=access_token) return service.list_organizations(session=session, access_token=access_token)
@@ -91,13 +86,12 @@ async def list_organizations(
@router.put( @router.put(
"/{account_id}", "/{account_id}",
operation_id="updateAccount", operation_id="updateAccount",
response_model=AccountProfile,
) )
async def update_account( async def update_account(
account_id: uuid.UUID, account_id: uuid.UUID,
payload: UpdateAccountRequest, payload: UpdateAccountRequest,
session: Session = Depends(get_session), session: SessionDep,
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile: ) -> AccountProfile:
return service.update_account( return service.update_account(
session=session, session=session,
@@ -114,8 +108,8 @@ async def update_account(
) )
async def delete_account( async def delete_account(
account_id: uuid.UUID, account_id: uuid.UUID,
session: Session = Depends(get_session), session: SessionDep,
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response: ) -> Response:
service.delete_account( service.delete_account(
session=session, session=session,
@@ -5,7 +5,7 @@ from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select from sqlmodel import Session, func, or_, select
from inse.auth import service as auth_service from inse.auth import service as auth_service
from inse.auth.model import AccessToken, Account, Organization, UserRole from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
from .model import ( from .model import (
AccountPage, AccountPage,
@@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
return False return False
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
organization_name = account.organization.name if account.organization else "" organization_name = account.organization.name if account.organization else ""
return AccountProfile( return AccountProfile(
id=account.id, id=account.id,
@@ -55,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
return account return account
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None: def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata) -> None:
if token.effective_role == UserRole.SUPER_ADMIN: if token.effective_role == UserRole.SUPER_ADMIN:
return return
if ( if (
@@ -95,14 +95,14 @@ def _ensure_email_available(
) )
def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile: def get_current_account(session: Session, access_token: AccessTokenMetadata) -> AccountProfile:
account = _get_account_or_404(session, access_token.effective_account_id) account = _get_account_or_404(session, access_token.effective_account_id)
return _account_to_profile(account, access_token) return _account_to_profile(account, access_token)
def list_accounts( def list_accounts(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
page: int, page: int,
page_size: int, page_size: int,
offset: Optional[int] = None, offset: Optional[int] = None,
@@ -157,7 +157,7 @@ def list_accounts(
def create_account( def create_account(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
payload: CreateAccountRequest, payload: CreateAccountRequest,
) -> AccountProfile: ) -> AccountProfile:
if not _is_admin(access_token.effective_role): if not _is_admin(access_token.effective_role):
@@ -207,7 +207,7 @@ def create_account(
def list_organizations( def list_organizations(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
) -> list[OrganizationProfile]: ) -> list[OrganizationProfile]:
if access_token.effective_role == UserRole.SUPER_ADMIN: if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec( organizations = session.exec(
@@ -233,7 +233,7 @@ def list_organizations(
def update_account( def update_account(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
account_id: uuid.UUID, account_id: uuid.UUID,
payload: UpdateAccountRequest, payload: UpdateAccountRequest,
) -> AccountProfile: ) -> AccountProfile:
@@ -307,7 +307,7 @@ def update_account(
def delete_account( def delete_account(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
account_id: uuid.UUID, account_id: uuid.UUID,
) -> None: ) -> None:
account = _get_account_or_404(session, account_id) account = _get_account_or_404(session, account_id)
+41 -31
View File
@@ -15,9 +15,9 @@ class UserRole(StrEnum):
class TokenType(StrEnum): class TokenType(StrEnum):
ID_TOKEN = "ID" ID_TOKEN = "ID_TOKEN"
REFRESH_TOKEN = "REFRESH" REFRESH_TOKEN = "REFRESH_TOKEN"
ACCESS_TOKEN = "ACCESS" ACCESS_TOKEN = "ACCESS_TOKEN"
class Durable(SQLModel): class Durable(SQLModel):
@@ -129,37 +129,20 @@ class Secret(SQLModel, table=True):
) )
class Token(BaseModel): class BaseTokenData(BaseModel):
token_type: TokenType = Field(
description="The type of the token (ID, Refresh, or Access).",
)
real_account_id: uuid.UUID = Field( real_account_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the real account associated with this token.", description="The unique identifier of the real account associated with this token.",
) )
expires_at: datetime = Field( expires_at: datetime = Field(
index=True,
nullable=False,
description="The timestamp indicating when the token will expire.", description="The timestamp indicating when the token will expire.",
) )
epoch: int = Field( epoch: int = Field(
default=0, default=0,
nullable=False,
description="The epoch value for the token. Used for versioning of tokens.", description="The epoch value for the token. Used for versioning of tokens.",
) )
user_fingerprint_hash: str = Field(
index=True,
nullable=False,
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
)
raw_token: str = Field(
index=False,
nullable=False,
description="The raw token string.",
)
class IdToken(Token): class IdTokenMetadata(BaseTokenData):
token_type: TokenType = Field( token_type: TokenType = Field(
default=TokenType.ID_TOKEN, default=TokenType.ID_TOKEN,
const=True, const=True,
@@ -167,24 +150,23 @@ class IdToken(Token):
) )
class AccessToken(Token): class AccessTokenMetadata(BaseTokenData):
token_type: TokenType = Field( token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN, default=TokenType.ACCESS_TOKEN,
const=True, const=True,
description="The type of the token, which is always ACCESS_TOKEN for this class.", description="The type of the token, which is always ACCESS_TOKEN for this class.",
) )
user_fingerprint_hash: str = Field(
description="A unique fingerprint of the user, used for additional security checks.",
)
effective_account_id: uuid.UUID = Field( effective_account_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
) )
effective_role: UserRole = Field( effective_role: UserRole = Field(
default=UserRole.USER, default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this access token grants within its organization.", description="The specific role this access token grants within its organization.",
) )
effective_organization_id: uuid.UUID = Field( effective_organization_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the organization associated with this access token.", description="The unique identifier of the organization associated with this access token.",
) )
@@ -197,22 +179,50 @@ class AccessToken(Token):
return self.effective_account_id != self.real_account_id return self.effective_account_id != self.real_account_id
class RefreshToken(AccessToken): class AccessToken(AccessTokenMetadata):
raw_token: str = Field(
description="The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.",
)
class RefreshTokenMetadata(BaseTokenData):
token_type: TokenType = Field( token_type: TokenType = Field(
default=TokenType.REFRESH_TOKEN, default=TokenType.REFRESH_TOKEN,
const=True, const=True,
description="The type of the token, which is always REFRESH_TOKEN for this class.", description="The type of the token, which is always REFRESH_TOKEN for this class.",
) )
effective_account_id: uuid.UUID = Field(
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
)
effective_role: UserRole = Field(
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
class RefreshToken(RefreshTokenMetadata):
raw_token: str = Field(
description="The raw string representation of the refresh token. This is the actual token that can be used to obtain new access tokens.",
)
class LoginResponse(BaseModel): class LoginResponse(BaseModel):
id_token: IdToken = Field(description="The ID token issued upon successful login.") id_token: IdTokenMetadata = Field(
description="The ID token issued upon successful login."
)
class AccessResponse(BaseModel): class AccessResponse(BaseModel):
access_token: AccessToken = Field( access_token: AccessToken = Field(
description="The access token issued upon successful authentication." description="The access token issued upon successful authentication."
) )
refresh_token: RefreshToken = Field(
description="The refresh token issued alongside the access token for obtaining new access tokens."
class OtkResponse(BaseModel):
status: str = Field(description="The status of the one-time code (OTC) request.")
account_id: uuid.UUID = Field(
description="The unique identifier of the account for which the OTC was requested."
) )
+13 -8
View File
@@ -12,9 +12,11 @@ from inse.database import SessionDep, get_session
from inse.auth.model import ( from inse.auth.model import (
AccessResponse, AccessResponse,
AccessToken, AccessToken,
IdToken, AccessTokenMetadata,
IdTokenMetadata,
LoginResponse, LoginResponse,
RefreshToken, OtkResponse,
RefreshTokenMetadata,
) )
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -40,7 +42,7 @@ async def request_otk(
session: SessionDep, session: SessionDep,
email: Annotated[str, Body(description="User's email address")], email: Annotated[str, Body(description="User's email address")],
password: Annotated[str, Body(description="User's password")], password: Annotated[str, Body(description="User's password")],
): ) -> OtkResponse:
return auth_service.request_otk(session=session, email=email, password=password) return auth_service.request_otk(session=session, email=email, password=password)
@@ -80,7 +82,7 @@ async def get_action_tokens(
effective_account_id: Annotated[ effective_account_id: Annotated[
uuid.UUID, Body(description="Effective account ID for the access token") uuid.UUID, Body(description="Effective account ID for the access token")
], ],
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], id_token: Annotated[IdTokenMetadata, auth_service.CurrentUserIdTokenPayloadDep],
) -> AccessResponse: ) -> AccessResponse:
logger.debug( logger.debug(
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s", "Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
@@ -108,11 +110,14 @@ async def get_action_tokens(
}, },
) )
async def refresh_access_token( async def refresh_access_token(
response: Response,
refresh_token: Annotated[ refresh_token: Annotated[
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep
], ],
) -> AccessToken: ) -> AccessToken:
return auth_service.refresh_access_token(refresh_token=refresh_token) return auth_service.refresh_access_token(
response=response, refresh_token=refresh_token
)
@router.post( @router.post(
@@ -125,7 +130,7 @@ async def refresh_access_token(
async def logout( async def logout(
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
access_token: Annotated[ access_token: Annotated[
AccessToken, AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep, auth_service.CurrentUserAccessTokenPayloadDep,
], ],
): ):
@@ -150,7 +155,7 @@ async def change_password(
Body(description="New password", min_length=8), Body(description="New password", min_length=8),
], ],
access_token: Annotated[ access_token: Annotated[
AccessToken, AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep, auth_service.CurrentUserAccessTokenPayloadDep,
], ],
): ):
+194 -183
View File
@@ -4,21 +4,23 @@ import json
import logging import logging
import secrets import secrets
import uuid import uuid
from typing import Annotated, Any, Dict, Literal, Optional from typing import Annotated, Any, Dict, Optional
import jwt import jwt
from argon2 import PasswordHasher from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from fastapi import Depends, HTTPException, Request, Response, status from fastapi import Cookie, Depends, HTTPException, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from inse.auth.model import ( from inse.auth.model import (
AccessResponse, AccessResponse,
AccessToken, AccessToken,
AccessTokenMetadata,
Account, Account,
IdToken, IdTokenMetadata,
LoginResponse, LoginResponse,
Organization, Organization,
RefreshToken, OtkResponse,
RefreshTokenMetadata,
Secret, Secret,
TokenType, TokenType,
UserRole, UserRole,
@@ -28,9 +30,9 @@ from inse.database import get_session
from sqlmodel import Session, select, func from sqlmodel import Session, select, func
from inse.auth.email_service import send_email from inse.auth.email_service import send_email
ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
OTK_EXPIRATION_MINUTES = 15 # 15 minutes OTK_EXPIRATION_MINUTES = 15 # 15 minutes
@@ -41,8 +43,11 @@ EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EPOCH_KEY = "epoch" EPOCH_KEY = "epoch"
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
ID_FP_COOKIE_KEY = "_Secure-Fgp-ID"
ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act" ACCESS_FP_COOKIE_KEY = "_Secure-Fgp-Acc"
ID_TOKEN_COOKIE_KEY = "id_token"
REFRESH_TOKEN_COOKIE_KEY = "refresh_token"
settings = get_settings() settings = get_settings()
@@ -155,7 +160,7 @@ def _verify_password(password: str, password_hash: str) -> bool:
return False return False
def request_otk(session: Session, email: str, password: str): def request_otk(session: Session, email: str, password: str) -> OtkResponse:
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid. """Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
Args: Args:
@@ -180,11 +185,7 @@ def request_otk(session: Session, email: str, password: str):
logger.debug("OTK request for email %s: account found: %s", email, account) logger.debug("OTK request for email %s: account found: %s", email, account)
if ( if account is None or account.deleted or account.id is None:
account is None
or account.deleted
or account.id is None
):
logger.warning("OTK request failed for email %s: account not found", email) logger.warning("OTK request failed for email %s: account not found", email)
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
@@ -247,7 +248,7 @@ def request_otk(session: Session, email: str, password: str):
else: else:
logger.info("OTK generated for account %s", account.id) logger.info("OTK generated for account %s", account.id)
return {"status": "ok", "account_id": str(account.id)} return OtkResponse(status="success", account_id=account.id)
def login( def login(
@@ -331,9 +332,9 @@ def login(
def _get_current_user_access_token_payload( def _get_current_user_access_token_payload(
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
request: Request,
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
) -> AccessToken: secure_fgp: Annotated[str | None, Cookie(alias=ACCESS_FP_COOKIE_KEY)] = None,
) -> AccessTokenMetadata:
"""Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. """Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
Args: Args:
@@ -344,18 +345,22 @@ def _get_current_user_access_token_payload(
Returns: Returns:
AccessToken: The verified access token payload. AccessToken: The verified access token payload.
""" """
if secure_fgp is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Access fingerprint cookie is missing",
)
token = credentials.credentials token = credentials.credentials
access_token_payload = _verify_fp_token( access_token_payload = _verify_access_token_fp(
request=request, secure_fgp=secure_fgp,
cookie_key=ACT_FP_COOKIE_KEY, raw_access_token=token,
token=token,
session=session, session=session,
) )
# If reaches here, the access token is valid and the fingerprint matches # If reaches here, the access token is valid and the fingerprint matches
return AccessToken( return AccessTokenMetadata(
real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]), real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp( expires_at=datetime.datetime.fromtimestamp(
@@ -367,15 +372,13 @@ def _get_current_user_access_token_payload(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
), ),
user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY], user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY],
raw_token=token,
) )
def _get_current_user_refresh_token_payload( def _get_current_user_refresh_token_payload(
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
request: Request, token: Annotated[str | None, Cookie(alias=REFRESH_TOKEN_COOKIE_KEY)] = None,
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], ) -> RefreshTokenMetadata:
) -> RefreshToken:
"""Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. """Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
Args: Args:
@@ -384,18 +387,20 @@ def _get_current_user_refresh_token_payload(
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token. credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token.
Returns: Returns:
RefreshToken: The verified refresh token payload. RefreshTokenData: The verified refresh token payload.
""" """
token = credentials.credentials if token is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Refresh token cookie is missing",
)
refresh_token_payload = _verify_fp_token( refresh_token_payload = _verify_refresh_token(
request=request, raw_refresh_token=token,
cookie_key=ACT_FP_COOKIE_KEY,
token=token,
session=session, session=session,
) )
# If reaches here, the refresh token is valid and the fingerprint matches # If reaches here, the refresh token is valid and the fingerprint matches
refresh_token = RefreshToken( refresh_token = RefreshTokenMetadata(
real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]), real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp( expires_at=datetime.datetime.fromtimestamp(
@@ -406,8 +411,6 @@ def _get_current_user_refresh_token_payload(
effective_organization_id=uuid.UUID( effective_organization_id=uuid.UUID(
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
), ),
user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY],
raw_token=token,
) )
logger.debug("Extracted refresh token payload: %s", refresh_token) logger.debug("Extracted refresh token payload: %s", refresh_token)
@@ -417,9 +420,8 @@ def _get_current_user_refresh_token_payload(
def _get_current_user_id_token_payload( def _get_current_user_id_token_payload(
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
request: Request, token: Annotated[str | None, Cookie(alias=ID_TOKEN_COOKIE_KEY)] = None,
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], ) -> IdTokenMetadata:
) -> IdToken:
"""Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. """Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
Args: Args:
@@ -430,30 +432,24 @@ def _get_current_user_id_token_payload(
Returns: Returns:
IdToken: The verified ID token payload. IdToken: The verified ID token payload.
""" """
logger.debug( if token is None:
"Verifying ID token for request %s with credentials %s", raise HTTPException(
request.url, status_code=status.HTTP_401_UNAUTHORIZED,
credentials, detail="ID token cookie is missing",
) )
token = credentials.credentials
logger.debug("Verifying ID token for request %s with token %s", request.url, token)
id_token_payload = _verify_fp_token( id_token_payload = _verify_id_token(
request=request, raw_id_token=token,
cookie_key=ID_FP_COOKIE_KEY,
token=token,
session=session, session=session,
) )
# If reaches here, the ID token is valid and the fingerprint matches # If reaches here, the ID token is valid and the fingerprint matches
return IdToken( return IdTokenMetadata(
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]), real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp( expires_at=datetime.datetime.fromtimestamp(
id_token_payload["exp"], tz=datetime.timezone.utc id_token_payload["exp"], tz=datetime.timezone.utc
), ),
epoch=id_token_payload[EPOCH_KEY], epoch=id_token_payload[EPOCH_KEY],
user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY],
raw_token=token,
) )
@@ -582,26 +578,10 @@ def _is_valid_impersonation(
def get_access_token( def get_access_token(
response: Response, response: Response,
session: Session, session: Session,
id_token: IdToken, id_token: IdTokenMetadata,
real_account_id: uuid.UUID, real_account_id: uuid.UUID,
effective_account_id: Optional[uuid.UUID] = None, effective_account_id: Optional[uuid.UUID] = None,
) -> AccessResponse: ) -> AccessResponse:
"""Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies.
Args:
request (Request): The FastAPI request object containing the cookies.
response (Response): The FastAPI response object to which the cookies will be added.
id_token (str): The ID token to verify.
real_account_id (uuid.UUID): The unique identifier of the real account associated with this token.
effective_account_id (Optional[uuid.UUID], optional): The unique identifier of the effective account associated with this token. If not provided, it defaults to the real account ID.
Raises:
HTTPException: If the ID token is invalid, expired, or does not match the real account ID.
HTTPException: If impersonation is not allowed.
Returns:
AccessResponse: An object containing the generated access and refresh tokens.
"""
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here. # IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
if real_account_id != id_token.real_account_id: if real_account_id != id_token.real_account_id:
@@ -616,16 +596,15 @@ def get_access_token(
if effective_account_id is None: if effective_account_id is None:
effective_account_id = real_account_id effective_account_id = real_account_id
elif effective_account_id != real_account_id: elif effective_account_id != real_account_id and not _is_valid_impersonation(
if not _is_valid_impersonation( session=session,
session=session, real_account_id=real_account_id,
real_account_id=real_account_id, effective_account_id=effective_account_id,
effective_account_id=effective_account_id, ):
): raise HTTPException(
raise HTTPException( status_code=status.HTTP_403_FORBIDDEN,
status_code=status.HTTP_403_FORBIDDEN, detail="Impersonation not allowed",
detail="Impersonation not allowed", )
)
role = _get_account_role(session=session, account_id=effective_account_id) role = _get_account_role(session=session, account_id=effective_account_id)
epoch = _get_account_epoch(account_id=effective_account_id, session=session) epoch = _get_account_epoch(account_id=effective_account_id, session=session)
@@ -633,7 +612,7 @@ def get_access_token(
session=session, account_id=effective_account_id session=session, account_id=effective_account_id
) )
user_fingerprint_hash = _set_act_fp_cookie(response=response) user_fingerprint_hash = _set_access_fp_cookie(response=response)
access_token = _build_access_token( access_token = _build_access_token(
real_account_id=real_account_id, real_account_id=real_account_id,
@@ -643,77 +622,96 @@ def get_access_token(
epoch=epoch, epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash, user_fingerprint_hash=user_fingerprint_hash,
) )
refresh_token = _build_refresh_token( _set_refresh_token(
response=response,
real_account_id=real_account_id, real_account_id=real_account_id,
effective_account_id=effective_account_id, effective_account_id=effective_account_id,
effective_role=role, effective_role=role,
effective_organization_id=organization_id, effective_organization_id=organization_id,
epoch=epoch, epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
) )
return AccessResponse( return AccessResponse(
access_token=access_token, access_token=access_token,
refresh_token=refresh_token,
) )
def _set_id_fp_cookie(response: Response) -> str: def _set_id_token_cookie(response: Response, raw_id_token: str) -> None:
"""Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint. """Sets a secure cookie for the ID token.
Args: Args:
response (Response): The FastAPI response object to which the cookie will be added. response (Response): The FastAPI response object to which the cookie will be added.
raw_id_token (str): The raw string representation of the ID token.
Returns:
str: The hashed value of the fingerprint.
""" """
return _set_fingerprint_cookie( _set_token_cookie(
response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 response=response,
cookie_name=ID_TOKEN_COOKIE_KEY,
token=raw_id_token,
max_age=ID_TOKEN_EXPIRATION_MINUTES * 60,
) )
def _set_act_fp_cookie(response: Response) -> str: def _set_refresh_token_cookie(response: Response, raw_refresh_token: str) -> None:
"""Sets a secure cookie for the refresh token.
Args:
response (Response): The FastAPI response object to which the cookie will be added.
raw_refresh_token (str): The raw string representation of the refresh token.
"""
_set_token_cookie(
response=response,
cookie_name=REFRESH_TOKEN_COOKIE_KEY,
token=raw_refresh_token,
max_age=REFRESH_TOKEN_EXPIRATION_MINUTES * 60,
)
def _set_token_cookie(
response: Response, cookie_name: str, token: str, max_age: int
) -> None:
"""Sets a secure cookie for the specified token.
Args:
response (Response): The FastAPI response object to which the cookie will be added.
cookie_name (str): The name of the cookie to set.
token (str): The raw string representation of the token.
max_age (int): The maximum age of the cookie in seconds.
"""
secure = False if settings.environment == "dev" else True
response.set_cookie(
key=cookie_name,
value=token,
httponly=True,
secure=secure,
samesite="strict",
max_age=max_age,
)
def _set_access_fp_cookie(response: Response) -> str:
"""Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint. """Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint.
Args: Args:
response (Response): The FastAPI response object to which the cookie will be added. response (Response): The FastAPI response object to which the cookie will be added.
Returns:
str: The hashed value of the fingerprint.
"""
return _set_fingerprint_cookie(
response, ACT_FP_COOKIE_KEY
) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed.
def _set_fingerprint_cookie(
response: Response,
key: Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"],
max_age: Optional[int] = None,
) -> str:
"""Sets a secure fingerprint cookie and returns the hashed value of the fingerprint.
Args:
response (Response): The FastAPI response object to which the cookie will be added.
key (Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"]): The name of the cookie to set.
max_age (Optional[int], optional): The maximum age of the cookie in seconds. Defaults to None.
Returns: Returns:
str: The hashed value of the fingerprint. str: The hashed value of the fingerprint.
""" """
user_fingerprint = secrets.token_hex(50) user_fingerprint = secrets.token_hex(50)
secure = False if settings.environment == "dev" else True secure = False if settings.environment == "dev" else True
response.set_cookie( response.set_cookie(
key=key, key=ACCESS_FP_COOKIE_KEY,
value=user_fingerprint, value=user_fingerprint,
httponly=True, httponly=True,
secure=secure, secure=secure,
samesite="strict", samesite="strict",
max_age=max_age, max_age=None, # Setting no max age to make it a session cookie, which will be deleted when the browser is closed.
) )
return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest()
def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: def refresh_access_token(
response: Response, refresh_token: RefreshTokenMetadata
) -> AccessToken:
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
Args: Args:
@@ -726,25 +724,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> AccessToken:
""" """
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
return _refresh_access_token( user_fingerprint_hash = _set_access_fp_cookie(response=response)
refresh_token=refresh_token,
)
def _refresh_access_token(
refresh_token: RefreshToken,
) -> AccessToken:
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
Args:
request (Request): The FastAPI request object containing the cookies.
refresh_token (RefreshToken): The refresh token to verify.
current_user_epoch (int): The epoch value for the tokens.
Returns:
AccessToken: The refreshed access token.
"""
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
return _build_access_token( return _build_access_token(
real_account_id=refresh_token.real_account_id, real_account_id=refresh_token.real_account_id,
@@ -752,7 +732,7 @@ def _refresh_access_token(
effective_role=refresh_token.effective_role, effective_role=refresh_token.effective_role,
effective_organization_id=refresh_token.effective_organization_id, effective_organization_id=refresh_token.effective_organization_id,
epoch=refresh_token.epoch, epoch=refresh_token.epoch,
user_fingerprint_hash=refresh_token.user_fingerprint_hash, user_fingerprint_hash=user_fingerprint_hash,
) )
@@ -760,7 +740,7 @@ def _build_id_token(
response: Response, response: Response,
real_account_id: uuid.UUID, real_account_id: uuid.UUID,
epoch: int, epoch: int,
) -> IdToken: ) -> IdTokenMetadata:
"""Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie. """Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie.
Args: Args:
@@ -775,34 +755,31 @@ def _build_id_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=ID_TOKEN_EXPIRATION_MINUTES minutes=ID_TOKEN_EXPIRATION_MINUTES
) )
user_fingerprint_hash = _set_id_fp_cookie(response)
payload = { payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id), REAL_ACCOUNT_ID_KEY: str(real_account_id),
EPOCH_KEY: epoch, EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
} }
raw_token = _build_token( raw_token = _build_token(
payload=payload, payload=payload,
expiration_datetime=expires_at, expiration_datetime=expires_at,
token_type=TokenType.ID_TOKEN, token_type=TokenType.ID_TOKEN,
) )
return IdToken( _set_id_token_cookie(response=response, raw_id_token=raw_token)
return IdTokenMetadata(
real_account_id=real_account_id, real_account_id=real_account_id,
expires_at=expires_at, expires_at=expires_at,
epoch=epoch, epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
raw_token=raw_token,
) )
def _build_refresh_token( def _set_refresh_token(
response: Response,
real_account_id: uuid.UUID, real_account_id: uuid.UUID,
effective_account_id: uuid.UUID, effective_account_id: uuid.UUID,
effective_role: UserRole, effective_role: UserRole,
effective_organization_id: uuid.UUID, effective_organization_id: uuid.UUID,
epoch: int, epoch: int,
user_fingerprint_hash: str, ) -> RefreshTokenMetadata:
) -> RefreshToken:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. """Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
Args: Args:
@@ -815,7 +792,7 @@ def _build_refresh_token(
user_fingerprint_hash (str): The hashed value of the user's fingerprint. user_fingerprint_hash (str): The hashed value of the user's fingerprint.
Returns: Returns:
RefreshToken: The generated refresh token object. RefreshTokenMetadata: The generated refresh token object.
""" """
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
@@ -826,7 +803,6 @@ def _build_refresh_token(
EFFECTIVE_ROLE_KEY: effective_role.value, EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id), EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch, EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
} }
raw_token = _build_token( raw_token = _build_token(
@@ -834,16 +810,14 @@ def _build_refresh_token(
expiration_datetime=expires_at, expiration_datetime=expires_at,
token_type=TokenType.REFRESH_TOKEN, token_type=TokenType.REFRESH_TOKEN,
) )
_set_refresh_token_cookie(response=response, raw_refresh_token=raw_token)
return RefreshToken( return RefreshTokenMetadata(
real_account_id=real_account_id, real_account_id=real_account_id,
effective_account_id=effective_account_id, effective_account_id=effective_account_id,
expires_at=expires_at, expires_at=expires_at,
epoch=epoch, epoch=epoch,
effective_role=effective_role, effective_role=effective_role,
effective_organization_id=effective_organization_id, effective_organization_id=effective_organization_id,
user_fingerprint_hash=user_fingerprint_hash,
raw_token=raw_token,
) )
@@ -930,18 +904,57 @@ def _build_token(
return token return token
def _verify_fp_token( def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
request: Request, """Verifies the provided ID token and returns the decoded payload if valid.
cookie_key: str,
token: str,
session: Session,
) -> Dict[str, Any]:
"""Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
Args: Args:
request (Request): The FastAPI request object containing the cookies. raw_id_token (str): The JWT ID token to verify.
cookie_key (str): The name of the cookie that contains the fingerprint. session (Session): The database session.
token (str): The JWT token to verify.
Raises:
ValueError: If the token HMAC key is not set in the configuration.
HTTPException: If the token has expired.
HTTPException: If the token is invalid.
HTTPException: If the token's epoch does not match the current user epoch.
Returns:
Dict[str, Any]: The decoded payload of the JWT ID token if verification is successful.
"""
payload = _extract_valid_token_payload(session, raw_id_token)
return payload
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]:
"""Verifies the provided refresh token and returns the decoded payload if valid.
Args:
raw_refresh_token (str): The JWT refresh token to verify.
session (Session): The database session.
Raises:
ValueError: If the token HMAC key is not set in the configuration.
HTTPException: If the token has expired.
HTTPException: If the token is invalid.
HTTPException: If the token's epoch does not match the current user epoch.
Returns:
Dict[str, Any]: The decoded payload of the JWT refresh token if verification is successful.
"""
payload = _extract_valid_token_payload(session, raw_refresh_token)
return payload
def _verify_access_token_fp(
secure_fgp: str,
raw_access_token: str,
session: Session,
) -> Dict[str, Any]:
"""Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
Args:
secure_fgp (str): The secure fingerprint value.
raw_access_token (str): The JWT token to verify.
session (Session): The database session.
Raises: Raises:
ValueError: If the token HMAC key is not set in the configuration. ValueError: If the token HMAC key is not set in the configuration.
@@ -953,19 +966,29 @@ def _verify_fp_token(
Returns: Returns:
Dict[str, Any]: The decoded payload of the JWT token if verification is successful. Dict[str, Any]: The decoded payload of the JWT token if verification is successful.
""" """
if not settings.token_hmac_key:
raise ValueError("Token HMAC key is not set in the configuration.")
secure_fgp = request.cookies.get(cookie_key)
if not secure_fgp:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Fingerprint cookie missing",
)
fingerprint_bytes = secure_fgp.encode("utf-8") fingerprint_bytes = secure_fgp.encode("utf-8")
expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest() expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest()
payload = _extract_valid_token_payload(session, raw_access_token)
token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY)
if (
not token_fingerprint_hash
or token_fingerprint_hash != expected_fingerprint_hash
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid context fingerprint",
)
return payload
def _extract_valid_token_payload(session: Session, token: str):
if not settings.token_hmac_key:
raise ValueError("Token HMAC key is not set in the configuration.")
try: try:
payload = jwt.decode( payload = jwt.decode(
token, token,
@@ -974,23 +997,12 @@ def _verify_fp_token(
issuer=settings.token_issuer_id, issuer=settings.token_issuer_id,
) )
token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY)
if (
not token_fingerprint_hash
or token_fingerprint_hash != expected_fingerprint_hash
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid context fingerprint",
)
real_account_id = payload.get(REAL_ACCOUNT_ID_KEY) real_account_id = payload.get(REAL_ACCOUNT_ID_KEY)
if not real_account_id: if not real_account_id:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token missing real account ID", detail="Token missing real account ID",
) )
epoch_account_id = uuid.UUID(real_account_id) epoch_account_id = uuid.UUID(real_account_id)
effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY) effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY)
@@ -1013,7 +1025,6 @@ def _verify_fp_token(
) )
return payload return payload
except jwt.ExpiredSignatureError: except jwt.ExpiredSignatureError:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
@@ -1055,7 +1066,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
return account return account
def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]:
"""Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account. """Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account.
Args: Args:
@@ -1079,7 +1090,7 @@ def logout(session: Session, access_token: AccessToken) -> Dict[str, str]:
def change_password( def change_password(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
current_password: str, current_password: str,
new_password: str, new_password: str,
) -> Dict[str, str]: ) -> Dict[str, str]:
+118 -111
View File
@@ -14,9 +14,10 @@ from inse.auth.model import (
Account, Account,
Organization, Organization,
Secret, Secret,
IdToken,
AccessToken, AccessToken,
RefreshToken, IdTokenMetadata,
AccessTokenMetadata,
RefreshTokenMetadata,
UserRole, UserRole,
) )
@@ -61,6 +62,19 @@ def create_org_and_account(
return org, acc return org, acc
def _get_cookie_value(response: Response, cookie_name: str) -> str:
for header_name, header_value in getattr(response, "raw_headers", []):
if header_name.lower() == b"set-cookie":
cookie_header = header_value.decode("latin-1")
if cookie_header.startswith(f"{cookie_name}="):
return cookie_header.split(";", 1)[0].split("=", 1)[1]
header = response.headers.get("set-cookie")
assert header is not None
assert header.startswith(f"{cookie_name}=")
return header.split(";", 1)[0].split("=", 1)[1]
def test_hash_and_verify_password(): def test_hash_and_verify_password():
pw = "s3cret-password" pw = "s3cret-password"
h = auth_service._hash_password(pw) h = auth_service._hash_password(pw)
@@ -80,8 +94,8 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
resp = auth_service.request_otk(in_memory_session, email, password) resp = auth_service.request_otk(in_memory_session, email, password)
assert resp["status"] == "ok" assert resp.status == "success"
assert resp["account_id"] == str(acc.id) assert resp.account_id == acc.id
secret = in_memory_session.exec( secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id) select(Secret).where(Secret.account_id == acc.id)
@@ -93,9 +107,12 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
login_result = auth_service.login( login_result = auth_service.login(
in_memory_session, response, acc.id, secret.secret_value in_memory_session, response, acc.id, secret.secret_value
) )
assert isinstance(login_result.id_token, IdToken) assert isinstance(login_result.id_token, IdTokenMetadata)
assert login_result.id_token.real_account_id == acc.id assert login_result.id_token.real_account_id == acc.id
assert login_result.id_token.user_fingerprint_hash is not None
raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY)
payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session)
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
@@ -108,35 +125,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
response = Response() response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch) secure_fgp_hash = auth_service._set_access_fp_cookie(response)
assert isinstance(id_token, IdToken) secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY)
access_token = auth_service._build_access_token(
real_account_id=acc.id,
effective_account_id=acc.id,
effective_role=acc.role,
effective_organization_id=acc.organization_id,
epoch=acc.epoch,
user_fingerprint_hash=secure_fgp_hash,
)
assert isinstance(access_token, AccessToken)
cookie_header = None payload = auth_service._verify_access_token_fp(
for header, value in response.headers.items(): secure_fgp=secure_fgp,
if header.lower() == "set-cookie": raw_access_token=access_token.raw_token,
cookie_header = value
break
assert cookie_header is not None
cookie_value = cookie_header.split("=")[1].split(";")[0]
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
payload = auth_service._verify_fp_token(
request=req,
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
session=in_memory_session, session=in_memory_session,
) )
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
with pytest.raises(Exception): with pytest.raises(Exception):
auth_service._verify_fp_token( auth_service._verify_access_token_fp(
request=DummyReq({}), secure_fgp="bad-fingerprint",
cookie_key=auth_service.ID_FP_COOKIE_KEY, raw_access_token=access_token.raw_token,
token=id_token.raw_token,
session=in_memory_session, session=in_memory_session,
) )
@@ -158,11 +169,30 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
access_response = auth_service.get_access_token( access_response = auth_service.get_access_token(
response, in_memory_session, id_token, acc.id response, in_memory_session, id_token, acc.id
) )
assert isinstance(access_response.access_token, AccessToken) assert isinstance(access_response.access_token, AccessTokenMetadata)
assert isinstance(access_response.refresh_token, RefreshToken)
refreshed = auth_service.refresh_access_token(access_response.refresh_token) raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
assert isinstance(refreshed, AccessToken) refresh_payload = auth_service._verify_refresh_token(
raw_refresh_token=raw_refresh_token,
session=in_memory_session,
)
refresh_token = RefreshTokenMetadata(
real_account_id=uuid.UUID(refresh_payload[auth_service.REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
),
expires_at=_dt.datetime.fromtimestamp(
refresh_payload["exp"], tz=_dt.timezone.utc
),
epoch=refresh_payload[auth_service.EPOCH_KEY],
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
effective_organization_id=uuid.UUID(
refresh_payload[auth_service.EFFECTIVE_ORGANIZATION_ID_KEY]
),
)
refreshed = auth_service.refresh_access_token(Response(), refresh_token)
assert isinstance(refreshed, AccessTokenMetadata)
assert refreshed.real_account_id == access_response.access_token.real_account_id assert refreshed.real_account_id == access_response.access_token.real_account_id
@@ -233,6 +263,7 @@ def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_sess
in_memory_session.add(account) in_memory_session.add(account)
in_memory_session.commit() in_memory_session.commit()
assert account.id is not None
with pytest.raises(HTTPException) as error: with pytest.raises(HTTPException) as error:
auth_service._get_active_account(in_memory_session, account.id) auth_service._get_active_account(in_memory_session, account.id)
@@ -268,24 +299,20 @@ def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
response = Response() response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch) secure_fgp_hash = auth_service._set_access_fp_cookie(response)
access_token = auth_service._build_access_token(
cookie_header = None real_account_id=acc.id,
for header, value in response.headers.items(): effective_account_id=acc.id,
if header.lower() == "set-cookie": effective_role=acc.role,
cookie_header = value effective_organization_id=acc.organization_id,
break epoch=acc.epoch,
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore user_fingerprint_hash=secure_fgp_hash,
)
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
auth_service._verify_fp_token( auth_service._verify_access_token_fp(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore secure_fgp="badcookie",
cookie_key=auth_service.ID_FP_COOKIE_KEY, raw_access_token=access_token.raw_token,
token=id_token.raw_token,
session=in_memory_session, session=in_memory_session,
) )
@@ -300,28 +327,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
response = Response() response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch) secure_fgp_hash = auth_service._set_access_fp_cookie(response)
secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY)
cookie_header = None access_token = auth_service._build_access_token(
for header, value in response.headers.items(): real_account_id=acc.id,
if header.lower() == "set-cookie": effective_account_id=acc.id,
cookie_header = value effective_role=acc.role,
break effective_organization_id=acc.organization_id,
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore epoch=acc.epoch,
user_fingerprint_hash=secure_fgp_hash,
class DummyReq: )
def __init__(self, cookies):
self.cookies = cookies
acc.epoch += 1 acc.epoch += 1
in_memory_session.add(acc) in_memory_session.add(acc)
in_memory_session.commit() in_memory_session.commit()
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
auth_service._verify_fp_token( auth_service._verify_access_token_fp(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore secure_fgp=secure_fgp,
cookie_key=auth_service.ID_FP_COOKIE_KEY, raw_access_token=access_token.raw_token,
token=id_token.raw_token,
session=in_memory_session, session=in_memory_session,
) )
@@ -336,25 +360,21 @@ def test_invalid_token_signature_raises(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
response = Response() response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch) secure_fgp = auth_service._set_access_fp_cookie(response)
access_token = auth_service._build_access_token(
real_account_id=acc.id,
effective_account_id=acc.id,
effective_role=acc.role,
effective_organization_id=acc.organization_id,
epoch=acc.epoch,
user_fingerprint_hash=secure_fgp,
)
cookie_header = None bad_token = access_token.raw_token + "x"
for header, value in response.headers.items():
if header.lower() == "set-cookie":
cookie_header = value
break
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
bad_token = id_token.raw_token + "x"
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
auth_service._verify_fp_token( auth_service._verify_access_token_fp(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore secure_fgp=secure_fgp,
cookie_key=auth_service.ID_FP_COOKIE_KEY, raw_access_token=bad_token,
token=bad_token,
session=in_memory_session, session=in_memory_session,
) )
@@ -391,7 +411,7 @@ def test_impersonation_rules(in_memory_session, settings_backup):
real_acc.id, real_acc.id,
effective_account_id=eff_acc.id, effective_account_id=eff_acc.id,
) )
assert isinstance(access_resp.access_token, AccessToken) assert isinstance(access_resp.access_token, AccessTokenMetadata)
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
@@ -425,7 +445,7 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
login_res = auth_service.login( login_res = auth_service.login(
in_memory_session, Response(), acc.id, secret2.secret_value in_memory_session, Response(), acc.id, secret2.secret_value
) )
assert isinstance(login_res.id_token, IdToken) assert isinstance(login_res.id_token, IdTokenMetadata)
def test_otk_deleted_after_login(in_memory_session, settings_backup): def test_otk_deleted_after_login(in_memory_session, settings_backup):
@@ -461,7 +481,7 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
response = Response() response = Response()
raw = auth_service._set_act_fp_cookie(response) raw_hash = auth_service._set_access_fp_cookie(response)
access_token = auth_service._build_access_token( access_token = auth_service._build_access_token(
real_account_id=acc.id, real_account_id=acc.id,
@@ -469,18 +489,13 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup):
effective_role=acc.role, effective_role=acc.role,
effective_organization_id=acc.organization_id, effective_organization_id=acc.organization_id,
epoch=acc.epoch, epoch=acc.epoch,
user_fingerprint_hash=raw, user_fingerprint_hash=raw_hash,
) )
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
auth_service._verify_fp_token( auth_service._verify_access_token_fp(
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore secure_fgp="wrongcookie",
cookie_key=auth_service.ACT_FP_COOKIE_KEY, raw_access_token=access_token.raw_token,
token=access_token.raw_token,
session=in_memory_session, session=in_memory_session,
) )
@@ -495,34 +510,26 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup):
assert acc.id is not None assert acc.id is not None
response = Response() response = Response()
cookie_raw = auth_service._set_id_fp_cookie(response)
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5) past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
payload = { payload = {
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id), auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
auth_service.EFFECTIVE_ACCOUNT_ID_KEY: str(acc.id),
auth_service.EFFECTIVE_ROLE_KEY: acc.role.value,
auth_service.EFFECTIVE_ORGANIZATION_ID_KEY: str(acc.organization_id),
auth_service.EPOCH_KEY: acc.epoch, auth_service.EPOCH_KEY: acc.epoch,
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw, auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash,
} }
bad_token = auth_service._build_token( bad_token = auth_service._build_token(
payload=payload, payload=payload,
expiration_datetime=past, expiration_datetime=past,
token_type=auth_service.TokenType.ID_TOKEN, token_type=auth_service.TokenType.ACCESS_TOKEN,
) )
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
auth_service._verify_fp_token( auth_service._verify_access_token_fp(
request=DummyReq( secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY),
{ raw_access_token=bad_token,
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
.split("=")[1]
.split(";")[0]
}
), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=bad_token,
session=in_memory_session, session=in_memory_session,
) )
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session from sqlmodel import Session
from inse.auth import service as auth_service from inse.auth import service as auth_service
from inse.auth.model import AccessToken from inse.auth.model import AccessTokenMetadata
from inse.database import get_session from inse.database import get_session
from inse.tags import Tags from inse.tags import Tags
@@ -26,7 +26,7 @@ async def get_organizations(
page_size: int = Query(default=25, ge=1, le=100), page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0), offset: Optional[int] = Query(default=None, ge=0),
session: Session = Depends(get_session), session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationPage: ) -> OrganizationPage:
return service.get_organizations( return service.get_organizations(
session=session, session=session,
@@ -46,7 +46,7 @@ async def get_organizations(
async def create_organization( async def create_organization(
payload: CreateOrganizationRequest, payload: CreateOrganizationRequest,
session: Session = Depends(get_session), session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile: ) -> OrganizationProfile:
return service.create_organization(session, access_token, payload) return service.create_organization(session, access_token, payload)
@@ -60,7 +60,7 @@ async def update_organization(
organization_id: uuid.UUID, organization_id: uuid.UUID,
payload: UpdateOrganizationRequest, payload: UpdateOrganizationRequest,
session: Session = Depends(get_session), session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile: ) -> OrganizationProfile:
return service.update_organization( return service.update_organization(
session, access_token, organization_id, payload session, access_token, organization_id, payload
@@ -75,7 +75,7 @@ async def update_organization(
async def delete_organization( async def delete_organization(
organization_id: uuid.UUID, organization_id: uuid.UUID,
session: Session = Depends(get_session), session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response: ) -> Response:
service.delete_organization(session, access_token, organization_id) service.delete_organization(session, access_token, organization_id)
return Response(status_code=status.HTTP_204_NO_CONTENT) return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -4,7 +4,7 @@ from typing import Optional
from fastapi import HTTPException, status from fastapi import HTTPException, status
from sqlmodel import Session, func, select from sqlmodel import Session, func, select
from inse.auth.model import AccessToken, Account, Organization, UserRole from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
from .model import ( from .model import (
CreateOrganizationRequest, CreateOrganizationRequest,
@@ -14,7 +14,7 @@ from .model import (
) )
def _require_super_admin(access_token: AccessToken) -> None: def _require_super_admin(access_token: AccessTokenMetadata) -> None:
if access_token.effective_role != UserRole.SUPER_ADMIN: if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
@@ -109,7 +109,7 @@ def _deactivate_organization_accounts(
def get_organizations( def get_organizations(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
page: int, page: int,
page_size: int, page_size: int,
offset: Optional[int] = None, offset: Optional[int] = None,
@@ -145,7 +145,7 @@ def get_organizations(
def create_organization( def create_organization(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
payload: CreateOrganizationRequest, payload: CreateOrganizationRequest,
) -> OrganizationProfile: ) -> OrganizationProfile:
_require_super_admin(access_token) _require_super_admin(access_token)
@@ -164,7 +164,7 @@ def create_organization(
def update_organization( def update_organization(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
organization_id: uuid.UUID, organization_id: uuid.UUID,
payload: UpdateOrganizationRequest, payload: UpdateOrganizationRequest,
) -> OrganizationProfile: ) -> OrganizationProfile:
@@ -191,7 +191,7 @@ def update_organization(
def delete_organization( def delete_organization(
session: Session, session: Session,
access_token: AccessToken, access_token: AccessTokenMetadata,
organization_id: uuid.UUID, organization_id: uuid.UUID,
) -> None: ) -> None:
_require_super_admin(access_token) _require_super_admin(access_token)
+2 -2
View File
@@ -113,7 +113,7 @@ model/hEUReportSummary.ts
model/hEUTopic.ts model/hEUTopic.ts
model/hEUWebLink.ts model/hEUWebLink.ts
model/hTTPValidationError.ts model/hTTPValidationError.ts
model/idToken.ts model/idTokenMetadata.ts
model/inseAccountManagementModelOrganizationProfile.ts model/inseAccountManagementModelOrganizationProfile.ts
model/inseOrganizationManagementModelOrganizationProfile.ts model/inseOrganizationManagementModelOrganizationProfile.ts
model/institution.ts model/institution.ts
@@ -149,6 +149,7 @@ model/openAccess.ts
model/orgPatentEntry.ts model/orgPatentEntry.ts
model/orgPatentsResponse.ts model/orgPatentsResponse.ts
model/organizationPage.ts model/organizationPage.ts
model/otkResponse.ts
model/patentEntry.ts model/patentEntry.ts
model/patentsByAuthorResponse.ts model/patentsByAuthorResponse.ts
model/patentsByInstitutionResponse.ts model/patentsByInstitutionResponse.ts
@@ -160,7 +161,6 @@ model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts model/publicationIdsByAuthorPosition.ts
model/publicationsByAuthorResponse.ts model/publicationsByAuthorResponse.ts
model/rankingResponse.ts model/rankingResponse.ts
model/refreshToken.ts
model/score.ts model/score.ts
model/sortDirection.ts model/sortDirection.ts
model/tokenType.ts model/tokenType.ts
+1 -16
View File
@@ -26,19 +26,4 @@ export * from './topics.service';
import { TopicsService } from './topics.service'; import { TopicsService } from './topics.service';
export * from './works.service'; export * from './works.service';
import { WorksService } from './works.service'; import { WorksService } from './works.service';
export const APIS = [ export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
AuthService,
CompanyConnectionsService,
FundingService,
INSEServiceService,
InstitutionsService,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonNetworkService,
PersonsService,
ProjectsService,
TopicsService,
WorksService,
];
+56 -50
View File
@@ -41,6 +41,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco
// @ts-ignore // @ts-ignore
import { LoginResponse } from '../model/loginResponse'; import { LoginResponse } from '../model/loginResponse';
// @ts-ignore // @ts-ignore
import { OtkResponse } from '../model/otkResponse';
// @ts-ignore
import { UpdateAccountRequest } from '../model/updateAccountRequest'; import { UpdateAccountRequest } from '../model/updateAccountRequest';
// @ts-ignore // @ts-ignore
@@ -64,13 +66,14 @@ export class AuthService extends BaseService {
* Change the user\'s password and invalidate existing tokens. * Change the user\'s password and invalidate existing tokens.
* @endpoint post /api/auth/v2/change-password * @endpoint post /api/auth/v2/change-password
* @param bodyChangePassword * @param bodyChangePassword
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>; public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>; public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>; public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyChangePassword === null || bodyChangePassword === undefined) { if (bodyChangePassword === null || bodyChangePassword === undefined) {
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.'); throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
} }
@@ -132,13 +135,14 @@ export class AuthService extends BaseService {
* Create Account * Create Account
* @endpoint post /api/accounts * @endpoint post /api/accounts
* @param createAccountRequest * @param createAccountRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>; public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>; public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>; public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (createAccountRequest === null || createAccountRequest === undefined) { if (createAccountRequest === null || createAccountRequest === undefined) {
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.'); throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
} }
@@ -200,13 +204,14 @@ export class AuthService extends BaseService {
* Delete Account * Delete Account
* @endpoint delete /api/accounts/{account_id} * @endpoint delete /api/accounts/{account_id}
* @param accountId * @param accountId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>; public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>; public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>; public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (accountId === null || accountId === undefined) { if (accountId === null || accountId === undefined) {
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.'); throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
} }
@@ -259,22 +264,20 @@ export class AuthService extends BaseService {
* Retrieve an access token for the authenticated user. * Retrieve an access token for the authenticated user.
* @endpoint post /api/auth/v2/access * @endpoint post /api/auth/v2/access
* @param bodyGetAccessToken * @param bodyGetAccessToken
* @param idToken
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>; public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>; public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>; public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) { if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.'); throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
} }
let localVarHeaders = this.defaultHeaders; let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json' 'application/json'
]); ]);
@@ -326,13 +329,14 @@ export class AuthService extends BaseService {
/** /**
* Get Current Account * Get Current Account
* @endpoint get /api/accounts/me * @endpoint get /api/accounts/me
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>; public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>; public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>; public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders; let localVarHeaders = this.defaultHeaders;
@@ -431,13 +435,14 @@ export class AuthService extends BaseService {
/** /**
* List Organizations * List Organizations
* @endpoint get /api/accounts/organizations * @endpoint get /api/accounts/organizations
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>; public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>; public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>; public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders; let localVarHeaders = this.defaultHeaders;
@@ -490,13 +495,14 @@ export class AuthService extends BaseService {
* @param offset * @param offset
* @param search * @param search
* @param organizationId * @param organizationId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>; public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>; public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>; public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -624,13 +630,14 @@ export class AuthService extends BaseService {
* Logout * Logout
* Logout the authenticated user. * Logout the authenticated user.
* @endpoint post /api/auth/v2/logout * @endpoint post /api/auth/v2/logout
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>; public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>; public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>; public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders; let localVarHeaders = this.defaultHeaders;
@@ -679,19 +686,17 @@ export class AuthService extends BaseService {
* Refresh Access Token * Refresh Access Token
* Refresh the access token using a valid refresh token. * Refresh the access token using a valid refresh token.
* @endpoint post /api/auth/v2/refresh * @endpoint post /api/auth/v2/refresh
* @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 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. * @param reportProgress flag to report request and response progress.
*/ */
public refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>; public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>; public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>; public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders; let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json' 'application/json'
]); ]);
@@ -738,9 +743,9 @@ export class AuthService extends BaseService {
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OtkResponse>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OtkResponse>>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OtkResponse>>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyRequestOtk === null || bodyRequestOtk === undefined) { if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.'); throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
@@ -782,7 +787,7 @@ export class AuthService extends BaseService {
let localVarPath = `/api/auth/v2/request-otk`; let localVarPath = `/api/auth/v2/request-otk`;
const { basePath, withCredentials } = this.configuration; const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`, return this.httpClient.request<OtkResponse>('post', `${basePath}${localVarPath}`,
{ {
context: localVarHttpContext, context: localVarHttpContext,
body: bodyRequestOtk, body: bodyRequestOtk,
@@ -801,13 +806,14 @@ export class AuthService extends BaseService {
* @endpoint put /api/accounts/{account_id} * @endpoint put /api/accounts/{account_id}
* @param accountId * @param accountId
* @param updateAccountRequest * @param updateAccountRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>; public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>; public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>; public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (accountId === null || accountId === undefined) { if (accountId === null || accountId === undefined) {
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.'); throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
} }
+174 -324
View File
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,355 +9,205 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { import { HttpClient, HttpHeaders, HttpParams,
HttpClient, HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
HttpHeaders, } from '@angular/common/http';
HttpParams, import { CustomHttpParameterCodec } from '../encoder';
HttpResponse, import { Observable } from 'rxjs';
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root'
}) })
export class INSEServiceService extends BaseService { export class INSEServiceService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/** constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
* Builds the topic hierarchy cache. super(basePath, configuration);
* @endpoint get /api/inse-service/topics/cache
* @param pageSize Page size for each search page.
* @param saveJson Persist cache JSON to data folder.
* @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 buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<object>;
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<object>>;
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<object>>;
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>pageSize,
'page_size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>saveJson,
'save_json',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
const localVarHttpContext: HttpContext = /**
options?.context ?? new HttpContext(); * Builds the topic hierarchy cache.
* @endpoint get /api/inse-service/topics/cache
* @param pageSize Page size for each search page.
* @param saveJson Persist cache JSON to data folder.
* @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
const localVarTransferCache: boolean = options?.transferCache ?? true; let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>saveJson, 'save_json');
let responseType_: 'text' | 'json' | 'blob' = 'json'; let localVarHeaders = this.defaultHeaders;
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/cache`; const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
const { basePath, withCredentials } = this.configuration; 'application/json'
return this.httpClient.request<object>( ]);
'get', if (localVarHttpHeaderAcceptSelected !== undefined) {
`${basePath}${localVarPath}`, localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
{ }
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/** const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
* Counts topic hierarchy occurrences from cache.
* @endpoint get /api/inse-service/topics/count
* @param topic Topic names (repeat parameter).
* @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 countTopicHierarchy(
topic: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<object>;
public countTopicHierarchy(
topic: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<object>>;
public countTopicHierarchy(
topic: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<object>>;
public countTopicHierarchy(
topic: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (topic === null || topic === undefined) {
throw new Error(
'Required parameter topic was null or undefined when calling countTopicHierarchy.',
);
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); const localVarTransferCache: boolean = options?.transferCache ?? true;
if (topic) {
topic.forEach((element) => {
localVarQueryParameters = this.addToHttpParams( let responseType_: 'text' | 'json' | 'blob' = 'json';
localVarQueryParameters, if (localVarHttpHeaderAcceptSelected) {
<any>element, if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
'topic', responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/cache`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
); );
});
} }
let localVarHeaders = this.defaultHeaders; /**
* Counts topic hierarchy occurrences from cache.
* @endpoint get /api/inse-service/topics/count
* @param topic Topic names (repeat parameter).
* @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 countTopicHierarchy(topic: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public countTopicHierarchy(topic: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public countTopicHierarchy(topic: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public countTopicHierarchy(topic: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (topic === null || topic === undefined) {
throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.');
}
const localVarHttpHeaderAcceptSelected: string | undefined = let localVarQueryParameters = new HttpParams({encoder: this.encoder});
options?.httpHeaderAccept ?? if (topic) {
this.configuration.selectHeaderAccept(['application/json']); topic.forEach((element) => {
if (localVarHttpHeaderAcceptSelected !== undefined) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
localVarHeaders = localVarHeaders.set( <any>element, 'topic');
'Accept', })
localVarHttpHeaderAcceptSelected, }
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/topics/count`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext = /**
options?.context ?? new HttpContext(); * Returns the nested topic hierarchy (Domains -&gt; Fields -&gt; Subfields -&gt; Topics).
* @endpoint get /api/inse-service/topics/hierarchy
* @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
const localVarTransferCache: boolean = options?.transferCache ?? true; let localVarHeaders = this.defaultHeaders;
let responseType_: 'text' | 'json' | 'blob' = 'json'; const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
if (localVarHttpHeaderAcceptSelected) { 'application/json'
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { ]);
responseType_ = 'text'; if (localVarHttpHeaderAcceptSelected !== undefined) {
} else if ( localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) }
) {
responseType_ = 'json'; const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
} else {
responseType_ = 'blob'; const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/inse-service/topics/count`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns the nested topic hierarchy (Domains -&gt; Fields -&gt; Subfields -&gt; Topics).
* @endpoint get /api/inse-service/topics/hierarchy
* @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 getTopicHierarchy(
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<object>;
public getTopicHierarchy(
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<object>>;
public getTopicHierarchy(
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<object>>;
public getTopicHierarchy(
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+20 -16
View File
@@ -47,13 +47,14 @@ export class OrganizationService extends BaseService {
* Create Organization * Create Organization
* @endpoint post /api/organizations * @endpoint post /api/organizations
* @param createOrganizationRequest * @param createOrganizationRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>; public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>; public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>; public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (createOrganizationRequest === null || createOrganizationRequest === undefined) { if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.'); throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
} }
@@ -115,13 +116,14 @@ export class OrganizationService extends BaseService {
* Delete Organization * Delete Organization
* @endpoint delete /api/organizations/{organization_id} * @endpoint delete /api/organizations/{organization_id}
* @param organizationId * @param organizationId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public deleteOrganisation(organizationId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>; public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>; public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>; public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (organizationId === null || organizationId === undefined) { if (organizationId === null || organizationId === undefined) {
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.'); throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
} }
@@ -175,13 +177,14 @@ export class OrganizationService extends BaseService {
* @param page * @param page
* @param pageSize * @param pageSize
* @param offset * @param offset
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>; public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>; public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>; public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -240,13 +243,14 @@ export class OrganizationService extends BaseService {
* @endpoint put /api/organizations/{organization_id} * @endpoint put /api/organizations/{organization_id}
* @param organizationId * @param organizationId
* @param updateOrganizationRequest * @param updateOrganizationRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @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. * @param reportProgress flag to report request and response progress.
*/ */
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>; public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>; public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>; public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (organizationId === null || organizationId === undefined) { if (organizationId === null || organizationId === undefined) {
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
} }
+315 -640
View File
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,18 +9,12 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { import { HttpClient, HttpHeaders, HttpParams,
HttpClient, HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
HttpHeaders, } from '@angular/common/http';
HttpParams, import { CustomHttpParameterCodec } from '../encoder';
HttpResponse, import { Observable } from 'rxjs';
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { AllPatentsResponse } from '../model/allPatentsResponse'; import { AllPatentsResponse } from '../model/allPatentsResponse';
@@ -36,657 +30,338 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root'
}) })
export class PatentsService extends BaseService { export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/** constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
* Get all patents with pagination and search. super(basePath, configuration);
* @endpoint get /api/inse-service/patents
* @param page
* @param size
* @param search
* @param source
* @param sortBy
* @param sortDirection
* @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 getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<AllPatentsResponse>;
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<AllPatentsResponse>>;
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<AllPatentsResponse>>;
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>size,
'size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>search,
'search',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>source,
'source',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortBy,
'sort_by',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortDirection,
'sort_direction',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
const localVarHttpContext: HttpContext = /**
options?.context ?? new HttpContext(); * Get all patents with pagination and search.
* @endpoint get /api/inse-service/patents
* @param page
* @param size
* @param search
* @param source
* @param sortBy
* @param sortDirection
* @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 getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AllPatentsResponse>;
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AllPatentsResponse>>;
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AllPatentsResponse>>;
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
const localVarTransferCache: boolean = options?.transferCache ?? true; let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>search, 'search');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>source, 'source');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortDirection, 'sort_direction');
let responseType_: 'text' | 'json' | 'blob' = 'json'; let localVarHeaders = this.defaultHeaders;
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
responseType_ = 'text'; 'application/json'
} else if ( ]);
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) if (localVarHttpHeaderAcceptSelected !== undefined) {
) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
responseType_ = 'json'; }
} else {
responseType_ = 'blob'; const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
}
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AllPatentsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/inse-service/patents`; /**
const { basePath, withCredentials } = this.configuration; * Get pre-indexed org patents for an institution.
return this.httpClient.request<AllPatentsResponse>( * @endpoint get /api/inse-service/institutions/{id}/org-patents
'get', * @param id
`${basePath}${localVarPath}`, * @param matchType Filter patents by match type.
{ * @param page
context: localVarHttpContext, * @param size
params: localVarQueryParameters, * @param source
responseType: <any>responseType_, * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
...(withCredentials ? { withCredentials } : {}), * @param reportProgress flag to report request and response progress.
headers: localVarHeaders, */
observe: observe, public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrgPatentsResponse>;
...(localVarTransferCache !== undefined public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrgPatentsResponse>>;
? { transferCache: localVarTransferCache } public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrgPatentsResponse>>;
: {}), public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
reportProgress: reportProgress, if (id === null || id === undefined) {
}, throw new Error('Required parameter id was null or undefined when calling getOrgPatentsByInstitution.');
); }
}
/** let localVarQueryParameters = new HttpParams({encoder: this.encoder});
* Get pre-indexed org patents for an institution. localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
* @endpoint get /api/inse-service/institutions/{id}/org-patents <any>matchType, 'match_type');
* @param id localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
* @param matchType Filter patents by match type. <any>page, 'page');
* @param page localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
* @param size <any>size, 'size');
* @param source localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. <any>source, 'source');
* @param reportProgress flag to report request and response progress.
*/ let localVarHeaders = this.defaultHeaders;
public getOrgPatentsByInstitution(
id: string, const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
matchType?: 'institution' | 'name' | 'both' | 'all', 'application/json'
page?: number, ]);
size?: number, if (localVarHttpHeaderAcceptSelected !== undefined) {
source?: string, localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
observe?: 'body', }
reportProgress?: boolean,
options?: { const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
httpHeaderAccept?: 'application/json';
context?: HttpContext; const localVarTransferCache: boolean = options?.transferCache ?? true;
transferCache?: boolean;
},
): Observable<OrgPatentsResponse>; let responseType_: 'text' | 'json' | 'blob' = 'json';
public getOrgPatentsByInstitution( if (localVarHttpHeaderAcceptSelected) {
id: string, if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
matchType?: 'institution' | 'name' | 'both' | 'all', responseType_ = 'text';
page?: number, } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
size?: number, responseType_ = 'json';
source?: string, } else {
observe?: 'response', responseType_ = 'blob';
reportProgress?: boolean, }
options?: { }
httpHeaderAccept?: 'application/json';
context?: HttpContext; let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/org-patents`;
transferCache?: boolean; const { basePath, withCredentials } = this.configuration;
}, return this.httpClient.request<OrgPatentsResponse>('get', `${basePath}${localVarPath}`,
): Observable<HttpResponse<OrgPatentsResponse>>; {
public getOrgPatentsByInstitution( context: localVarHttpContext,
id: string, params: localVarQueryParameters,
matchType?: 'institution' | 'name' | 'both' | 'all', responseType: <any>responseType_,
page?: number, ...(withCredentials ? { withCredentials } : {}),
size?: number, headers: localVarHeaders,
source?: string, observe: observe,
observe?: 'events', ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress?: boolean, reportProgress: reportProgress
options?: { }
httpHeaderAccept?: 'application/json'; );
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<OrgPatentsResponse>>;
public getOrgPatentsByInstitution(
id: string,
matchType?: 'institution' | 'name' | 'both' | 'all',
page?: number,
size?: number,
source?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (id === null || id === undefined) {
throw new Error(
'Required parameter id was null or undefined when calling getOrgPatentsByInstitution.',
);
} }
let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); /**
localVarQueryParameters = this.addToHttpParams( * Returns one publication by OpenAlex ID or DOI.
localVarQueryParameters, * @endpoint get /api/inse-service/patents/{identifier}
<any>matchType, * @param identifier
'match_type', * @param prefix Application Prefix (EP or US)
); * @param title Do we want to fallback to title search if ID and DOI dont work?
localVarQueryParameters = this.addToHttpParams( * @param fillingDate Filling date in YYYY-MM-DD format
localVarQueryParameters, * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
<any>page, * @param reportProgress flag to report request and response progress.
'page', */
); public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
localVarQueryParameters = this.addToHttpParams( public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentEntry>>;
localVarQueryParameters, public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentEntry>>;
<any>size, public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
'size', if (identifier === null || identifier === undefined) {
); throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.');
localVarQueryParameters = this.addToHttpParams( }
localVarQueryParameters,
<any>source,
'source',
);
let localVarHeaders = this.defaultHeaders; let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>prefix, 'prefix');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>fillingDate, 'filling_date');
const localVarHttpHeaderAcceptSelected: string | undefined = let localVarHeaders = this.defaultHeaders;
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']); const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
if (localVarHttpHeaderAcceptSelected !== undefined) { 'application/json'
localVarHeaders = localVarHeaders.set( ]);
'Accept', if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHttpHeaderAcceptSelected, localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
); }
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/patents/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentEntry>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext = /**
options?.context ?? new HttpContext(); * Get patents matched to an author by name.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @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 getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
}
const localVarTransferCache: boolean = options?.transferCache ?? true; let localVarHeaders = this.defaultHeaders;
let responseType_: 'text' | 'json' | 'blob' = 'json'; const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
if (localVarHttpHeaderAcceptSelected) { 'application/json'
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { ]);
responseType_ = 'text'; if (localVarHttpHeaderAcceptSelected !== undefined) {
} else if ( localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) }
) {
responseType_ = 'json'; const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
} else {
responseType_ = 'blob'; const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/org-patents`; /**
const { basePath, withCredentials } = this.configuration; * Get patents matched to an institution by assignee name.
return this.httpClient.request<OrgPatentsResponse>( * @endpoint get /api/inse-service/institutions/{id}/patents
'get', * @param id
`${basePath}${localVarPath}`, * @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.
context: localVarHttpContext, */
params: localVarQueryParameters, public getPatentsByInstitution(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByInstitutionResponse>;
responseType: <any>responseType_, public getPatentsByInstitution(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByInstitutionResponse>>;
...(withCredentials ? { withCredentials } : {}), public getPatentsByInstitution(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByInstitutionResponse>>;
headers: localVarHeaders, public getPatentsByInstitution(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
observe: observe, if (id === null || id === undefined) {
...(localVarTransferCache !== undefined throw new Error('Required parameter id was null or undefined when calling getPatentsByInstitution.');
? { transferCache: localVarTransferCache } }
: {}),
reportProgress: reportProgress,
},
);
}
/** let localVarHeaders = this.defaultHeaders;
* Returns one publication by OpenAlex ID or DOI.
* @endpoint get /api/inse-service/patents/{identifier} const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
* @param identifier 'application/json'
* @param prefix Application Prefix (EP or US) ]);
* @param title Do we want to fallback to title search if ID and DOI dont work? if (localVarHttpHeaderAcceptSelected !== undefined) {
* @param fillingDate Filling date in YYYY-MM-DD format localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
* @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.
*/ const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
public getPatentByIdOrTitle(
identifier: string, const localVarTransferCache: boolean = options?.transferCache ?? true;
prefix?: string,
title?: string,
fillingDate?: string, let responseType_: 'text' | 'json' | 'blob' = 'json';
observe?: 'body', if (localVarHttpHeaderAcceptSelected) {
reportProgress?: boolean, if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
options?: { responseType_ = 'text';
httpHeaderAccept?: 'application/json'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
context?: HttpContext; responseType_ = 'json';
transferCache?: boolean; } else {
}, responseType_ = 'blob';
): Observable<PatentEntry>; }
public getPatentByIdOrTitle( }
identifier: string,
prefix?: string, let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
title?: string, const { basePath, withCredentials } = this.configuration;
fillingDate?: string, return this.httpClient.request<PatentsByInstitutionResponse>('get', `${basePath}${localVarPath}`,
observe?: 'response', {
reportProgress?: boolean, context: localVarHttpContext,
options?: { responseType: <any>responseType_,
httpHeaderAccept?: 'application/json'; ...(withCredentials ? { withCredentials } : {}),
context?: HttpContext; headers: localVarHeaders,
transferCache?: boolean; observe: observe,
}, ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
): Observable<HttpResponse<PatentEntry>>; reportProgress: reportProgress
public getPatentByIdOrTitle( }
identifier: string, );
prefix?: string,
title?: string,
fillingDate?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentEntry>>;
public getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
fillingDate?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (identifier === null || identifier === undefined) {
throw new Error(
'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
);
} }
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>prefix,
'prefix',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>title,
'title',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>fillingDate,
'filling_date',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentEntry>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get patents matched to an author by name.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @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 getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get patents matched to an institution by assignee name.
* @endpoint get /api/inse-service/institutions/{id}/patents
* @param id
* @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 getPatentsByInstitution(
id: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentsByInstitutionResponse>;
public getPatentsByInstitution(
id: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentsByInstitutionResponse>>;
public getPatentsByInstitution(
id: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentsByInstitutionResponse>>;
public getPatentsByInstitution(
id: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (id === null || id === undefined) {
throw new Error(
'Required parameter id was null or undefined when calling getPatentsByInstitution.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? 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/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByInstitutionResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+171 -197
View File
@@ -1,219 +1,193 @@
import { import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
HttpHeaders,
HttpParams,
HttpParameterCodec,
} from '@angular/common/http';
import { Param } from './param'; import { Param } from './param';
export interface ConfigurationParameters { export interface ConfigurationParameters {
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
apiKeys?: { [key: string]: string }; apiKeys?: {[ key: string ]: string};
username?: string; username?: string;
password?: string; password?: string;
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
accessToken?: string | (() => string); accessToken?: string | (() => string);
basePath?: string; basePath?: string;
withCredentials?: boolean; withCredentials?: boolean;
/** /**
* Takes care of encoding query- and form-parameters. * Takes care of encoding query- and form-parameters.
*/ */
encoder?: HttpParameterCodec; encoder?: HttpParameterCodec;
/** /**
* Override the default method for encoding path parameters in various * Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>. * <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p> * <p>
* See {@link README.md} for more details * See {@link README.md} for more details
* </p> * </p>
*/ */
encodeParam?: (param: Param) => string; encodeParam?: (param: Param) => string;
/** /**
* The keys are the names in the securitySchemes section of the OpenAPI * The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication * document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'. * minus any standard prefixes such as 'Basic' or 'Bearer'.
*/ */
credentials?: { [key: string]: string | (() => string | undefined) }; credentials?: {[ key: string ]: string | (() => string | undefined)};
} }
export class Configuration { export class Configuration {
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
apiKeys?: { [key: string]: string }; apiKeys?: {[ key: string ]: string};
username?: string; username?: string;
password?: string; password?: string;
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
accessToken?: string | (() => string); accessToken?: string | (() => string);
basePath?: string; basePath?: string;
withCredentials?: boolean; withCredentials?: boolean;
/** /**
* Takes care of encoding query- and form-parameters. * Takes care of encoding query- and form-parameters.
*/ */
encoder?: HttpParameterCodec; encoder?: HttpParameterCodec;
/** /**
* Encoding of various path parameter * Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>. * <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p> * <p>
* See {@link README.md} for more details * See {@link README.md} for more details
* </p> * </p>
*/ */
encodeParam: (param: Param) => string; encodeParam: (param: Param) => string;
/** /**
* The keys are the names in the securitySchemes section of the OpenAPI * The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication * document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'. * minus any standard prefixes such as 'Basic' or 'Bearer'.
*/ */
credentials: { [key: string]: string | (() => string | undefined) }; credentials: {[ key: string ]: string | (() => string | undefined)};
constructor({ constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) {
accessToken, if (apiKeys) {
apiKeys, this.apiKeys = apiKeys;
basePath, }
credentials, if (username !== undefined) {
encodeParam, this.username = username;
encoder, }
password, if (password !== undefined) {
username, this.password = password;
withCredentials, }
}: ConfigurationParameters = {}) { if (accessToken !== undefined) {
if (apiKeys) { this.accessToken = accessToken;
this.apiKeys = apiKeys; }
} if (basePath !== undefined) {
if (username !== undefined) { this.basePath = basePath;
this.username = username; }
} if (withCredentials !== undefined) {
if (password !== undefined) { this.withCredentials = withCredentials;
this.password = password; }
} if (encoder) {
if (accessToken !== undefined) { this.encoder = encoder;
this.accessToken = accessToken; }
} this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param));
if (basePath !== undefined) { this.credentials = credentials ?? {};
this.basePath = basePath;
}
if (withCredentials !== undefined) {
this.withCredentials = withCredentials;
}
if (encoder) {
this.encoder = encoder;
}
this.encodeParam =
encodeParam ?? ((param) => this.defaultEncodeParam(param));
this.credentials = credentials ?? {};
// init default HTTPBearer credential // init default HTTPBearer credential
if (!this.credentials['HTTPBearer']) { if (!this.credentials['HTTPBearer']) {
this.credentials['HTTPBearer'] = () => { this.credentials['HTTPBearer'] = () => {
return typeof this.accessToken === 'function' return typeof this.accessToken === 'function'
? this.accessToken() ? this.accessToken()
: this.accessToken; : this.accessToken;
}; };
} }
}
/**
* Select the correct content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param contentTypes - the array of content types that are available for selection
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType(contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
} }
const type = contentTypes.find((x: string) => this.isJsonMime(x)); /**
if (type === undefined) { * Select the correct content-type to use for a request.
return contentTypes[0]; * Uses {@link Configuration#isJsonMime} to determine the correct content-type.
} * If no content type is found return the first found type if the contentTypes is not empty
return type; * @param contentTypes - the array of content types that are available for selection
} * @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType (contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
}
/** const type = contentTypes.find((x: string) => this.isJsonMime(x));
* Select the correct accept content-type to use for a request. if (type === undefined) {
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. return contentTypes[0];
* If no content type is found return the first found type if the contentTypes is not empty }
* @param accepts - the array of content types that are available for selection. return type;
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
} }
const type = accepts.find((x: string) => this.isJsonMime(x)); /**
if (type === undefined) { * Select the correct accept content-type to use for a request.
return accepts[0]; * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
}
return type;
} }
return type;
}
/** /**
* Check if the given MIME is a JSON MIME. * Check if the given MIME is a JSON MIME.
* JSON MIME examples: * JSON MIME examples:
* application/json * application/json
* application/json; charset=UTF8 * application/json; charset=UTF8
* APPLICATION/JSON * APPLICATION/JSON
* application/vnd.company+json * application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions) * @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise. * @return True if the given MIME is JSON, false otherwise.
*/ */
public isJsonMime(mime: string): boolean { public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp( const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
'^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
'i', }
);
return (
mime !== null &&
(jsonMime.test(mime) ||
mime.toLowerCase() === 'application/json-patch+json')
);
}
public lookupCredential(key: string): string | undefined { public lookupCredential(key: string): string | undefined {
const value = this.credentials[key]; const value = this.credentials[key];
return typeof value === 'function' ? value() : value; return typeof value === 'function'
} ? value()
: value;
}
public addCredentialToHeaders( public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders {
credentialKey: string, const value = this.lookupCredential(credentialKey);
headerName: string, return value
headers: HttpHeaders, ? headers.set(headerName, (prefix ?? '') + value)
prefix?: string, : headers;
): HttpHeaders { }
const value = this.lookupCredential(credentialKey);
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
}
public addCredentialToQuery( public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
credentialKey: string, const value = this.lookupCredential(credentialKey);
paramName: string, return value
query: HttpParams, ? query.set(paramName, value)
): HttpParams { : query;
const value = this.lookupCredential(credentialKey); }
return value ? query.set(paramName, value) : query;
}
private defaultEncodeParam(param: Param): string { private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration // This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions. // and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style. // It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format. // Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly. // All other styles and Date-formats are probably handled incorrectly.
// //
// But: if that's all you need (i.e.: the most common use-case): no need for customization! // But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = const value = param.dataFormat === 'date-time' && param.value instanceof Date
param.dataFormat === 'date-time' && param.value instanceof Date ? (param.value as Date).toISOString()
? (param.value as Date).toISOString() : param.value;
: param.value;
return encodeURIComponent(String(value)); return encodeURIComponent(String(value));
} }
} }
@@ -7,7 +7,6 @@
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
import { RefreshToken } from './refreshToken';
import { AccessToken } from './accessToken'; import { AccessToken } from './accessToken';
@@ -16,9 +15,5 @@ export interface AccessResponse {
* The access token issued upon successful authentication. * The access token issued upon successful authentication.
*/ */
access_token: AccessToken; access_token: AccessToken;
/**
* The refresh token issued alongside the access token for obtaining new access tokens.
*/
refresh_token: RefreshToken;
} }
+9 -9
View File
@@ -12,10 +12,6 @@ import { UserRole } from './userRole';
export interface AccessToken { export interface AccessToken {
/**
* The type of the token, which is always ACCESS_TOKEN for this class.
*/
token_type?: TokenType;
/** /**
* The unique identifier of the real account associated with this token. * The unique identifier of the real account associated with this token.
*/ */
@@ -29,13 +25,13 @@ export interface AccessToken {
*/ */
epoch?: number; epoch?: number;
/** /**
* A hash of the user\'s fingerprint to ensure the token is used by the same user. * The type of the token, which is always ACCESS_TOKEN for this class.
*/
token_type?: TokenType;
/**
* A unique fingerprint of the user, used for additional security checks.
*/ */
user_fingerprint_hash: string; user_fingerprint_hash: string;
/**
* The raw token string.
*/
raw_token: string;
/** /**
* The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.
*/ */
@@ -48,6 +44,10 @@ export interface AccessToken {
* The unique identifier of the organization associated with this access token. * The unique identifier of the organization associated with this access token.
*/ */
effective_organization_id: string; effective_organization_id: string;
/**
* The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.
*/
raw_token: string;
} }
export namespace AccessToken { export namespace AccessToken {
} }
@@ -26,3 +26,4 @@ export interface AccountProfile {
export namespace AccountProfile { export namespace AccountProfile {
} }
+12 -10
View File
@@ -1,20 +1,22 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface BodyRequestOtk {
/** export interface BodyRequestOtk {
* User\'s email address /**
*/ * User\'s email address
email: string; */
/** email: string;
* User\'s password /**
*/ * User\'s password
password: string; */
password: string;
} }
@@ -1,14 +1,16 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface CreateOrganizationRequest {
name: string; export interface CreateOrganizationRequest {
other_inst_id?: string | null; name: string;
other_inst_id?: string | null;
} }
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -10,17 +10,19 @@
import { ExtractedKeywordsLLM } from './extractedKeywordsLLM'; import { ExtractedKeywordsLLM } from './extractedKeywordsLLM';
import { ExtractedKeywords } from './extractedKeywords'; import { ExtractedKeywords } from './extractedKeywords';
export interface ExtractedKeywordsResponse {
results_llm?: ExtractedKeywordsLLM | null; export interface ExtractedKeywordsResponse {
results?: ExtractedKeywords | null; results_llm?: ExtractedKeywordsLLM | null;
/** results?: ExtractedKeywords | null;
* The source of the input text, e.g., \'url\', \'text\', or \'keywords\'. /**
*/ * The source of the input text, e.g., \'url\', \'text\', or \'keywords\'.
source: string; */
source_url?: string | null; source: string;
/** source_url?: string | null;
* The actual content from which keywords were extracted. /**
*/ * The actual content from which keywords were extracted.
source_content: string; */
duration?: number | null; source_content: string;
duration?: number | null;
} }
@@ -10,11 +10,7 @@
import { TokenType } from './tokenType'; import { TokenType } from './tokenType';
export interface IdToken { export interface IdTokenMetadata {
/**
* The type of the token, which is always ID_TOKEN for this class.
*/
token_type?: TokenType;
/** /**
* The unique identifier of the real account associated with this token. * The unique identifier of the real account associated with this token.
*/ */
@@ -28,15 +24,11 @@ export interface IdToken {
*/ */
epoch?: number; epoch?: number;
/** /**
* A hash of the user\'s fingerprint to ensure the token is used by the same user. * The type of the token, which is always ID_TOKEN for this class.
*/ */
user_fingerprint_hash: string; token_type?: TokenType;
/**
* The raw token string.
*/
raw_token: string;
} }
export namespace IdToken { export namespace IdTokenMetadata {
} }
@@ -1,15 +1,17 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface InseAccountManagementModelOrganizationProfile {
id: string; export interface InseAccountManagementModelOrganizationProfile {
name: string; id: string;
openalex_institution_id?: string | null; name: string;
openalex_institution_id?: string | null;
} }
@@ -1,17 +1,19 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface InseOrganizationManagementModelOrganizationProfile {
id: string; export interface InseOrganizationManagementModelOrganizationProfile {
name: string; id: string;
other_inst_id?: string | null; name: string;
deleted: boolean; other_inst_id?: string | null;
member_count: number; deleted: boolean;
member_count: number;
} }
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,7 +9,9 @@
*/ */
import { Topic } from './topic'; import { Topic } from './topic';
export interface KeywordTopicMatch {
keyword: string; export interface KeywordTopicMatch {
topic?: Topic | null; keyword: string;
topic?: Topic | null;
} }
@@ -1,16 +1,18 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface KeywordsTopicsRequest {
/** export interface KeywordsTopicsRequest {
* List of keywords/sentences to query by similarity. /**
*/ * List of keywords/sentences to query by similarity.
keywords: Array<string>; */
keywords: Array<string>;
} }
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,9 +9,11 @@
*/ */
import { KeywordTopicMatch } from './keywordTopicMatch'; import { KeywordTopicMatch } from './keywordTopicMatch';
export interface KeywordsTopicsResponse {
/** export interface KeywordsTopicsResponse {
* Top matching topics for each keyword in the requested list. /**
*/ * Top matching topics for each keyword in the requested list.
results: Array<KeywordTopicMatch>; */
results: Array<KeywordTopicMatch>;
} }
+9 -7
View File
@@ -1,17 +1,19 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
import { IdToken } from './idToken'; import { IdTokenMetadata } from './idTokenMetadata';
export interface LoginResponse {
/** export interface LoginResponse {
* The ID token issued upon successful login. /**
*/ * The ID token issued upon successful login.
id_token: IdToken; */
id_token: IdTokenMetadata;
} }
+6 -4
View File
@@ -1,14 +1,16 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface MatchedAuthor {
openalex_author_id: string; export interface MatchedAuthor {
author_name: string; openalex_author_id: string;
author_name: string;
} }
+2 -2
View File
@@ -89,7 +89,7 @@ export * from './hEUReportSummary';
export * from './hEUTopic'; export * from './hEUTopic';
export * from './hEUWebLink'; export * from './hEUWebLink';
export * from './hTTPValidationError'; export * from './hTTPValidationError';
export * from './idToken'; export * from './idTokenMetadata';
export * from './inseAccountManagementModelOrganizationProfile'; export * from './inseAccountManagementModelOrganizationProfile';
export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './inseOrganizationManagementModelOrganizationProfile';
export * from './institution'; export * from './institution';
@@ -124,6 +124,7 @@ export * from './openAccess';
export * from './orgPatentEntry'; export * from './orgPatentEntry';
export * from './orgPatentsResponse'; export * from './orgPatentsResponse';
export * from './organizationPage'; export * from './organizationPage';
export * from './otkResponse';
export * from './patentEntry'; export * from './patentEntry';
export * from './patentsByAuthorResponse'; export * from './patentsByAuthorResponse';
export * from './patentsByInstitutionResponse'; export * from './patentsByInstitutionResponse';
@@ -135,7 +136,6 @@ export * from './publicationDetailByFunder';
export * from './publicationIdsByAuthorPosition'; export * from './publicationIdsByAuthorPosition';
export * from './publicationsByAuthorResponse'; export * from './publicationsByAuthorResponse';
export * from './rankingResponse'; export * from './rankingResponse';
export * from './refreshToken';
export * from './score'; export * from './score';
export * from './sortDirection'; export * from './sortDirection';
export * from './tokenType'; export * from './tokenType';
+22
View File
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface OtkResponse {
/**
* The status of the one-time code (OTC) request.
*/
status: string;
/**
* The unique identifier of the account for which the OTC was requested.
*/
account_id: string;
}
-55
View File
@@ -1,55 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { TokenType } from './tokenType';
import { UserRole } from './userRole';
export interface RefreshToken {
/**
* The type of the token, which is always REFRESH_TOKEN for this class.
*/
token_type?: TokenType;
/**
* The unique identifier of the real account associated with this token.
*/
real_account_id: string;
/**
* The timestamp indicating when the token will expire.
*/
expires_at: string;
/**
* The epoch value for the token. Used for versioning of tokens.
*/
epoch?: number;
/**
* A hash of the user\'s fingerprint to ensure the token is used by the same user.
*/
user_fingerprint_hash: string;
/**
* The raw token string.
*/
raw_token: string;
/**
* The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.
*/
effective_account_id: string;
/**
* The specific role this access token grants within its organization.
*/
effective_role?: UserRole;
/**
* The unique identifier of the organization associated with this access token.
*/
effective_organization_id: string;
}
export namespace RefreshToken {
}
+3 -3
View File
@@ -10,9 +10,9 @@
export const TokenType = { export const TokenType = {
Id: 'ID', IdToken: 'ID_TOKEN',
Refresh: 'REFRESH', RefreshToken: 'REFRESH_TOKEN',
Access: 'ACCESS' AccessToken: 'ACCESS_TOKEN'
} as const; } as const;
export type TokenType = typeof TokenType[keyof typeof TokenType]; export type TokenType = typeof TokenType[keyof typeof TokenType];
@@ -23,3 +23,4 @@ export interface UpdateAccountRequest {
export namespace UpdateAccountRequest { export namespace UpdateAccountRequest {
} }
@@ -1,15 +1,17 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface UpdateOrganizationRequest {
name?: string | null; export interface UpdateOrganizationRequest {
other_inst_id?: string | null; name?: string | null;
deleted?: boolean | null; other_inst_id?: string | null;
deleted?: boolean | null;
} }
+2
View File
@@ -5,6 +5,7 @@ import {
Router, Router,
withComponentInputBinding, withComponentInputBinding,
withNavigationErrorHandler, withNavigationErrorHandler,
withRouterConfig,
} from '@angular/router'; } from '@angular/router';
import { routes } from './app.routes'; import { routes } from './app.routes';
@@ -37,6 +38,7 @@ export const appConfig: ApplicationConfig = {
provideRouter( provideRouter(
routes, routes,
withComponentInputBinding(), withComponentInputBinding(),
withRouterConfig({ onSameUrlNavigation: 'reload' }),
withNavigationErrorHandler((navigationError: NavigationError) => { withNavigationErrorHandler((navigationError: NavigationError) => {
const router = inject(Router); const router = inject(Router);
const errorService = inject(ErrorService); const errorService = inject(ErrorService);
+13 -1
View File
@@ -8,7 +8,6 @@ import { personResolver } from './resolvers/person.resolver';
import { institutionResolver } from './resolvers/institution.resolver'; import { institutionResolver } from './resolvers/institution.resolver';
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
import { personNewsResolver } from './resolvers/person-news.resolver';
import { institutionsResolver } from './resolvers/institutions.resolver'; import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver'; import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver'; import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver';
@@ -20,6 +19,9 @@ import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'
import { publicationResolver } from './resolvers/publication-resolver'; import { publicationResolver } from './resolvers/publication-resolver';
import { accountResolver } from './resolvers/account.resolver'; import { accountResolver } from './resolvers/account.resolver';
import { accountViewerGuard } from './shared/guards/account-viewer.guard'; import { accountViewerGuard } from './shared/guards/account-viewer.guard';
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver';
import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver';
export const routes: Routes = [ export const routes: Routes = [
{ {
@@ -114,6 +116,11 @@ export const routes: Routes = [
import('./modules/accounts/accounts.component').then( import('./modules/accounts/accounts.component').then(
(mod) => mod.AccountsComponent, (mod) => mod.AccountsComponent,
), ),
resolve: {
accountPage: accountsPageResolver,
organizations: accountsOrganizationResolver,
},
runGuardsAndResolvers: 'always',
}, },
{ {
path: 'organizations', path: 'organizations',
@@ -122,7 +129,12 @@ export const routes: Routes = [
import('./modules/organizations/organizations.component').then( import('./modules/organizations/organizations.component').then(
(mod) => mod.OrganizationsComponent, (mod) => mod.OrganizationsComponent,
), ),
resolve: {
organizationPage: organizationsOrganizationsResolver,
},
runGuardsAndResolvers: 'always',
}, },
{ {
path: 'news/:id', path: 'news/:id',
canActivate: [userGuard], canActivate: [userGuard],
@@ -145,18 +145,19 @@ export class AccountComponent {
if (!oldPassword || !newPassword) { if (!oldPassword || !newPassword) {
return; return;
} }
this._credentialService try {
.changePassword(oldPassword, newPassword) await this._credentialService.changePassword(
.subscribe({ oldPassword,
error: (error) => { newPassword,
console.error('Error changing password:', error); );
this._snackBar.open( } catch (error) {
'Das alte Passwort ist nicht korrekt. Bitte versuchen Sie es erneut.', console.error('Error changing password:', error);
'OK', this._snackBar.open(
{ duration: 7000 }, 'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
); 'OK',
}, { duration: 7000 },
}); );
}
}, },
}, },
}, },
@@ -16,22 +16,38 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select'; import { MatSelectModule } from '@angular/material/select';
import type { import {
AccountPayload,
AccountProfile, AccountProfile,
AccountRole, InseAccountManagementModelOrganizationProfile,
CreateAccountPayload, UserRole,
OrganizationProfile, } from '../../api';
} from '../../shared/services/account-management.service';
export type AccountDialogMode = 'create' | 'edit'; export type AccountDialogMode = 'create' | 'edit';
export interface AccountDialogData { export interface AccountDialogData {
mode: AccountDialogMode; mode: AccountDialogMode;
account?: AccountProfile; account?: AccountProfile;
organizations: OrganizationProfile[]; organizations: InseAccountManagementModelOrganizationProfile[];
canSelectOrganization: boolean; canSelectOrganization: boolean;
roles: AccountRole[]; roles: UserRole[];
}
export interface AccountPayload {
email?: string;
name?: string;
role?: UserRole;
organization_id?: string;
password?: string;
deleted?: boolean;
activated?: boolean;
}
export interface CreateAccountPayload {
email: string;
name: string;
role: UserRole;
organization_id: string;
password: string;
} }
export type AccountDialogResult = export type AccountDialogResult =
@@ -69,7 +85,7 @@ export class AccountDialogComponent {
name: new FormControl<string>(this.data.account?.name ?? '', [ name: new FormControl<string>(this.data.account?.name ?? '', [
Validators.required, Validators.required,
]), ]),
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [ role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
Validators.required, Validators.required,
]), ]),
organizationId: new FormControl<string>( organizationId: new FormControl<string>(
@@ -148,6 +164,6 @@ export class AccountDialogComponent {
} }
protected close(): void { protected close(): void {
this.dialogRef.close(undefined); this.dialogRef.close();
} }
} }
@@ -23,189 +23,73 @@
} }
</header> </header>
<form class="filters" [formGroup]="filterForm" (ngSubmit)="applyFilters()"> <section style="display: flex; gap: 1rem; align-items: center">
<mat-form-field appearance="outline"> <app-query-param-input
<mat-label>Name oder E-Mail</mat-label> queryParamKey="search"
<input matInput formControlName="search" /> label="Nach Name oder E-Mail suchen"
</mat-form-field> style="width: 35%" />
<app-query-param-selector
@if (credentialService.isEffectiveSuperAdmin()) { queryParamKey="organization_id"
<mat-form-field appearance="outline"> [options]="selectorOptions()"
<mat-label>Organisation</mat-label> label="Organisation"
<mat-select formControlName="organizationId"> [allowEmptyValue]="true"
<mat-option value="">Alle Organisationen</mat-option> style="width: 25%" />
@for (organization of organizations; track organization.id) {
<mat-option [value]="organization.id">
{{ organization.name }}
</mat-option>
}
</mat-select>
</mat-form-field>
}
<div class="filter-actions">
<button
mat-flat-button
color="primary"
type="submit"
matTooltip="Accounts mit den gewählten Filtern suchen">
<mat-icon>search</mat-icon>
Suchen
</button>
<button
mat-button
type="button"
matTooltip="Alle Suchfilter zurücksetzen"
(click)="resetFilters()">
Zurücksetzen
</button>
</div>
</form>
<section class="table-panel">
<div class="table-header">
<strong>{{ total }} Accounts</strong>
@if (isLoading) {
<span>Wird geladen...</span>
}
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Name</th>
<th>E-Mail</th>
<th>Organisation</th>
<th>Rolle</th>
<th>Status</th>
@if (!isReadOnly) {
<th>Aktionen</th>
}
</tr>
</thead>
<tbody>
@for (account of accounts; track account.id) {
<tr
[class.deleted]="account.deleted"
[class.deactivated]="!account.activated">
<td>
@if (isReadOnly) {
{{ account.name }}
} @else {
<button
class="link-button"
type="button"
[matTooltip]="'Account „' + account.name + '“ bearbeiten'"
(click)="startEdit(account)">
{{ account.name }}
</button>
}
</td>
<td>{{ account.email }}</td>
<td>{{ account.organization_name }}</td>
<td>
<span class="role">{{ account.role | role }}</span>
</td>
<td>
<span
class="status"
[class.status--deleted]="account.deleted"
[class.status--deactivated]="
!account.deleted && !account.activated
">
{{
account.deleted
? 'deleted'
: account.activated
? 'active'
: 'inactive'
}}
</span>
</td>
@if (!isReadOnly) {
<td>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Bearbeiten"
matTooltip="Account bearbeiten"
(click)="startEdit(account)">
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Impersonate"
matTooltip="Als dieser Account anmelden"
[disabled]="!canImpersonate(account)"
(click)="impersonate(account)">
<mat-icon>switch_account</mat-icon>
</button>
@if (credentialService.isEffectiveSuperAdmin()) {
<button
mat-icon-button
type="button"
[attr.aria-label]="
account.activated ? 'Deaktivieren' : 'Aktivieren'
"
[matTooltip]="
account.activated
? 'Account deaktivieren'
: 'Account aktivieren'
"
[disabled]="account.is_current || account.deleted"
(click)="toggleAccountActivation(account)">
<mat-icon>{{
account.activated ? 'person_off' : 'person_check'
}}</mat-icon>
</button>
}
<button
mat-icon-button
type="button"
aria-label="Löschen"
matTooltip="Account löschen"
[disabled]="account.is_current || account.deleted"
(click)="deleteAccount(account)">
<mat-icon>delete</mat-icon>
</button>
</div>
</td>
}
</tr>
} @empty {
<tr>
<td [attr.colspan]="isReadOnly ? 5 : 6" class="empty">
Keine Accounts gefunden.
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="pagination">
<button
mat-button
type="button"
matTooltip="Vorherige Seite anzeigen"
[disabled]="!canPageBack"
(click)="loadAccounts(page - 1)">
<mat-icon>chevron_left</mat-icon>
Zurück
</button>
<span>Seite {{ page + 1 }}</span>
<button
mat-button
type="button"
matTooltip="Nächste Seite anzeigen"
[disabled]="!canPageForward"
(click)="loadAccounts(page + 1)">
Weiter
<mat-icon>chevron_right</mat-icon>
</button>
</div>
</section> </section>
<mat-card appearance="outlined">
<mat-card-content>
<app-data-table [columns]="accountColumns" [data]="accountPage().items" />
</mat-card-content>
</mat-card>
<app-query-param-paginator [total]="accountPage().total" />
</section> </section>
<ng-template #accountRoleTmp let-row>
<span class="role">{{ row.role | role }}</span>
</ng-template>
<ng-template #accountStatusTmp let-row>
<span
class="status"
[class.status--deleted]="row.deleted"
[class.status--deactivated]="!row.deleted && !row.activated">
{{
(row.deleted ? 'deleted' : row.activated ? 'active' : 'inactive') | status
}}
</span>
</ng-template>
<ng-template #accountActionsTmp let-row>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Bearbeiten"
(click)="startEdit(row)">
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Impersonate"
[disabled]="!canImpersonate(row)"
(click)="impersonate(row)">
<mat-icon>switch_account</mat-icon>
</button>
<button
mat-icon-button
type="button"
[attr.aria-label]="row.activated ? 'Deaktivieren' : 'Aktivieren'"
[disabled]="row.is_current || row.deleted"
(click)="toggleAccountActivation(row)">
<mat-icon>{{ row.activated ? 'person_off' : 'person_check' }}</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Deaktivieren"
[disabled]="row.is_current || row.deleted"
(click)="deleteAccount(row)">
<mat-icon>delete</mat-icon>
</button>
</div>
</ng-template>
@@ -155,3 +155,8 @@ tr.deactivated:not(.deleted) {
flex-direction: column; flex-direction: column;
} }
} }
mat-card,
mat-paginator {
background-color: var(--sg-background);
}
@@ -1,6 +1,14 @@
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core'; import {
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; Component,
OnInit,
TemplateRef,
computed,
inject,
input,
viewChild,
} from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
@@ -10,19 +18,32 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { finalize } from 'rxjs';
import { AccountManagementService } from '../../shared/services/account-management.service';
import type {
AccountProfile,
AccountRole,
OrganizationProfile,
} from '../../shared/services/account-management.service';
import { CredentialService } from '../../shared/services/credential.service'; import { CredentialService } from '../../shared/services/credential.service';
import type { import type {
AccountDialogComponent, AccountDialogComponent,
AccountDialogResult, AccountDialogResult,
} from './account-dialog.component'; } from './account-dialog.component';
import { RolePipe } from '../../shared/pipes/role.pipe'; import { RolePipe } from '../../shared/pipes/role.pipe';
import {
GenericColumn,
DataTableComponent,
} from '../../shared/ui/data-table/data-table.component';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../shared/ui/query-param-selector/query-param-selector.component';
import { MatCardModule } from '@angular/material/card';
import {
AccountPage,
AccountProfile,
AuthService,
InseAccountManagementModelOrganizationProfile,
UserRole,
} from '../../api';
import { StatusPipe } from '../../shared/pipes/status.pipe';
@Component({ @Component({
selector: 'app-accounts', selector: 'app-accounts',
@@ -38,95 +59,92 @@ import { RolePipe } from '../../shared/pipes/role.pipe';
MatTooltipModule, MatTooltipModule,
MatDialogModule, MatDialogModule,
RolePipe, RolePipe,
DataTableComponent,
QueryParamPaginatorComponent,
QueryParamInputComponent,
QueryParamSelectorComponent,
MatCardModule,
StatusPipe
], ],
templateUrl: './accounts.component.html', templateUrl: './accounts.component.html',
styleUrl: './accounts.component.scss', styleUrl: './accounts.component.scss',
standalone: true, standalone: true,
}) })
export class AccountsComponent implements OnInit { export class AccountsComponent implements OnInit {
private readonly accountService = inject(AccountManagementService);
protected readonly credentialService = inject(CredentialService); protected readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar); private readonly snackBar = inject(MatSnackBar);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly dialog = inject(MatDialog); private readonly dialog = inject(MatDialog);
private readonly authService = inject(AuthService);
protected get isReadOnly(): boolean { protected get isReadOnly(): boolean {
return this.credentialService.isEffectiveManager(); return this.credentialService.isEffectiveManager();
} }
protected get availableRoles(): AccountRole[] { accountColumns: GenericColumn<AccountProfile>[] = [];
accountRoleTmp = viewChild.required<TemplateRef<any>>('accountRoleTmp');
accountStatusTmp = viewChild.required<TemplateRef<any>>('accountStatusTmp');
accountActionsTmp = viewChild.required<TemplateRef<any>>('accountActionsTmp');
availableRoles = computed<UserRole[]>(() => {
if (this.credentialService.isEffectiveSuperAdmin()) { if (this.credentialService.isEffectiveSuperAdmin()) {
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER']; return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
} }
return ['MANAGER', 'USER']; return ['MANAGER', 'USER'];
}
protected accounts: AccountProfile[] = [];
protected organizations: OrganizationProfile[] = [];
protected total = 0;
protected page = 0;
protected readonly pageSize = 10;
protected isLoading = false;
protected filterForm = new FormGroup({
search: new FormControl<string>(''),
organizationId: new FormControl<string>(''),
}); });
selectorOptions = computed<SelectorOption[]>(() => {
return this.organizations().map((org) => ({
value: org.id,
display_name: org.name,
}));
});
accountPage = input.required<AccountPage>();
organizations =
input.required<InseAccountManagementModelOrganizationProfile[]>();
ngOnInit(): void { ngOnInit(): void {
if (!this.isReadOnly) { this.accountColumns = [
this.loadOrganizations(); {
} id: 'name',
this.loadAccounts(); header: 'Name',
} type: 'accessor',
accessorKey: 'name',
protected loadAccounts(page = this.page): void {
this.page = page;
this.isLoading = true;
this.accountService
.listAccounts({
page: this.page,
pageSize: this.pageSize,
search: this.filterForm.controls.search.value?.trim() || undefined,
organizationId:
this.filterForm.controls.organizationId.value || undefined,
})
.pipe(finalize(() => (this.isLoading = false)))
.subscribe({
next: (result) => {
this.accounts = result.items;
this.total = result.total;
},
error: () => {
this.snackBar.open('Accounts konnten nicht geladen werden.', 'OK', {
duration: 5000,
});
},
});
}
protected loadOrganizations(): void {
this.accountService.listOrganizations().subscribe({
next: (organizations) => {
this.organizations = organizations;
}, },
error: () => { {
this.snackBar.open( id: 'email',
'Organisationen konnten nicht geladen werden.', header: 'E-Mail',
'OK', type: 'accessor',
{ duration: 5000 }, accessorKey: 'email',
);
}, },
}); {
} id: 'organization_name',
header: 'Organisation',
protected applyFilters(): void { type: 'accessor',
this.loadAccounts(0); accessorKey: 'organization_name',
} },
{
protected resetFilters(): void { id: 'role',
this.filterForm.reset({ search: '', organizationId: '' }); header: 'Rolle',
this.loadAccounts(0); type: 'accessor',
accessorKey: 'role',
cellTemplate: this.accountRoleTmp(),
},
{
id: 'status',
header: 'Status',
type: 'display',
cellTemplate: this.accountStatusTmp(),
},
{
id: 'actions',
header: 'Aktionen',
type: 'display',
cellTemplate: this.accountActionsTmp(),
},
];
} }
protected startCreate(): void { protected startCreate(): void {
@@ -140,15 +158,18 @@ export class AccountsComponent implements OnInit {
private saveDialogResult(result: AccountDialogResult): void { private saveDialogResult(result: AccountDialogResult): void {
const request = const request =
result.mode === 'create' result.mode === 'create'
? this.accountService.createAccount(result.payload) ? this.authService.createAccount(result.payload)
: this.accountService.updateAccount(result.accountId, result.payload); : this.authService.updateAccount(result.accountId, result.payload);
request.subscribe({ request.subscribe({
next: () => { next: () => {
this.snackBar.open('Account wurde gespeichert.', 'OK', { this.snackBar.open('Account wurde gespeichert.', 'OK', {
duration: 3000, duration: 3000,
}); });
this.loadAccounts(0); this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
}, },
error: (error) => { error: (error) => {
const message = const message =
@@ -170,9 +191,9 @@ export class AccountsComponent implements OnInit {
{ {
mode: 'create' | 'edit'; mode: 'create' | 'edit';
account?: AccountProfile; account?: AccountProfile;
organizations: OrganizationProfile[]; organizations: InseAccountManagementModelOrganizationProfile[];
canSelectOrganization: boolean; canSelectOrganization: boolean;
roles: AccountRole[]; roles: UserRole[];
}, },
AccountDialogResult | undefined AccountDialogResult | undefined
>(AccountDialogComponent, { >(AccountDialogComponent, {
@@ -180,9 +201,9 @@ export class AccountsComponent implements OnInit {
maxWidth: 'calc(100vw - 32px)', maxWidth: 'calc(100vw - 32px)',
data: { data: {
...data, ...data,
organizations: this.organizations, organizations: this.organizations(),
canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(), canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(),
roles: this.availableRoles, roles: this.availableRoles(),
}, },
}); });
@@ -199,12 +220,15 @@ export class AccountsComponent implements OnInit {
return; return;
} }
this.accountService.deleteAccount(account.id).subscribe({ this.authService.deleteAccount(account.id).subscribe({
next: () => { next: () => {
this.snackBar.open('Account wurde deaktiviert.', 'OK', { this.snackBar.open('Account wurde deaktiviert.', 'OK', {
duration: 3000, duration: 3000,
}); });
this.loadAccounts(); this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
}, },
error: () => { error: () => {
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', { this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
@@ -248,14 +272,17 @@ export class AccountsComponent implements OnInit {
account: AccountProfile, account: AccountProfile,
activated: boolean, activated: boolean,
): void { ): void {
this.accountService.updateAccount(account.id, { activated }).subscribe({ this.authService.updateAccount(account.id, { activated }).subscribe({
next: () => { next: () => {
this.snackBar.open( this.snackBar.open(
activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.', activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.',
'OK', 'OK',
{ duration: 3000 }, { duration: 3000 },
); );
this.loadAccounts(); this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
}, },
error: () => { error: () => {
this.snackBar.open( this.snackBar.open(
@@ -267,36 +294,24 @@ export class AccountsComponent implements OnInit {
}); });
} }
protected impersonate(account: AccountProfile): void { protected async impersonate(account: AccountProfile): Promise<void> {
if (!this.canImpersonate(account)) { if (!this.canImpersonate(account)) {
return; return;
} }
this.credentialService.impersonateAccount(account.id).subscribe({ try {
next: () => { await this.credentialService.impersonateAccount(account.id);
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
duration: 4000, duration: 4000,
}); });
this.router.navigate(['/dashboard']); this.router.navigate(['/dashboard']);
}, } catch (error) {
error: () => { console.error('Impersonation failed:', error);
this.snackBar.open( this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', {
'Impersonation konnte nicht gestartet werden.', duration: 5000,
'OK', });
{ return;
duration: 5000, }
},
);
},
});
}
protected get canPageBack(): boolean {
return this.page > 0;
}
protected get canPageForward(): boolean {
return (this.page + 1) * this.pageSize < this.total;
} }
protected canImpersonate(account: AccountProfile): boolean { protected canImpersonate(account: AccountProfile): boolean {
@@ -1,4 +1,4 @@
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, effect, OnDestroy } from '@angular/core';
import { import {
FormControl, FormControl,
FormGroup, FormGroup,
@@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input';
import { CredentialService } from '../../shared/services/credential.service'; import { CredentialService } from '../../shared/services/credential.service';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { finalize, Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router, RouterLink } from '@angular/router'; import { Router, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
@@ -34,7 +34,7 @@ type LoginStep = 'credentials' | 'otk';
styleUrl: './app-login.component.scss', styleUrl: './app-login.component.scss',
standalone: true, standalone: true,
}) })
export class AppLoginComponent implements OnInit, OnDestroy { export class AppLoginComponent implements OnDestroy {
credentialsForm = new FormGroup({ credentialsForm = new FormGroup({
email: new FormControl<string>('', [Validators.required, Validators.email]), email: new FormControl<string>('', [Validators.required, Validators.email]),
password: new FormControl<string>('', [ password: new FormControl<string>('', [
@@ -64,28 +64,21 @@ export class AppLoginComponent implements OnInit, OnDestroy {
protected credentialService: CredentialService, protected credentialService: CredentialService,
protected router: Router, protected router: Router,
protected snackBar: MatSnackBar, protected snackBar: MatSnackBar,
) {} ) {
effect(() => {
ngOnInit(): void { if (this.credentialService.isValidating()) {
this.subscription = this.credentialService.validating.subscribe( this.credentialsForm.disable();
(validating) => { this.otkForm.disable();
if (validating) { } else {
this.credentialsForm.disable(); this.credentialsForm.enable();
this.otkForm.disable(); this.otkForm.enable();
} else { this.checkEnter();
this.credentialsForm.enable(); }
this.otkForm.enable(); });
this.checkEnter();
}
},
);
if (!this.credentialService.validating.value) {
this.checkEnter();
}
} }
checkEnter(): void { checkEnter(): void {
if (this.credentialService.isAuthenticated.value) { if (this.credentialService.isAuthenticated()) {
this.router.navigate(['/dashboard']); this.router.navigate(['/dashboard']);
} }
} }
@@ -110,39 +103,35 @@ export class AppLoginComponent implements OnInit, OnDestroy {
const email = this.credentialsForm.controls.email.value ?? ''; const email = this.credentialsForm.controls.email.value ?? '';
const password = this.credentialsForm.controls.password.value ?? ''; const password = this.credentialsForm.controls.password.value ?? '';
this.credentialService this.credentialService.requestOtk(email, password).subscribe({
.requestOtk(email, password) next: (otkResponse) => {
.pipe( const accountId = otkResponse.account_id;
finalize(() => { this.accountId = accountId;
this.isSubmitting = false; this.currentStep = 'otk';
this.credentialsForm.enable(); this.otkForm.reset();
}), this.startCountdown();
) this.snackBar.open(
.subscribe({ 'OTK-Code wurde an die E-Mail-Adresse gesendet.',
next: (accountId) => { 'OK',
if (!accountId) { {
return; duration: 4000,
} },
);
this.accountId = accountId; },
this.currentStep = 'otk'; error: (error: unknown) => {
this.otkForm.reset(); this.snackBar.open(
this.startCountdown(); this.getLoginErrorMessage(error as HttpErrorResponse),
this.snackBar.open( 'OK',
'OTK-Code wurde an die E-Mail-Adresse gesendet.', {
'OK',
{
duration: 4000,
},
);
},
error: (error: HttpErrorResponse) => {
this.credentialService.clearLocalAuthState();
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
duration: 5000, duration: 5000,
}); },
}, );
}); },
complete: () => {
this.isSubmitting = false;
this.credentialsForm.enable();
},
});
} }
resendCode() { resendCode() {
@@ -178,29 +167,32 @@ export class AppLoginComponent implements OnInit, OnDestroy {
this.isSubmitting = true; this.isSubmitting = true;
this.otkForm.disable(); this.otkForm.disable();
const email = this.credentialsForm.controls.email.value ?? '';
const code = this.otkForm.controls.code.value ?? ''; const code = this.otkForm.controls.code.value ?? '';
this.credentialService this.credentialService.loginWithOtk(this.accountId, code).subscribe({
.loginWithOtk(this.accountId, email, code) next: () => {
.pipe( this.credentialService.reauthenticateViaIdToken().subscribe({
finalize(() => { next: () => {
this.isSubmitting = false; this.checkEnter();
this.otkForm.enable(); this.stopCountdown();
}), this.router.navigate(['/dashboard']);
) },
.subscribe({ });
next: () => { },
this.stopCountdown(); error: (error: unknown) => {
this.router.navigate(['/dashboard']); this.snackBar.open(
}, this.getLoginErrorMessage(error as HttpErrorResponse),
error: (error: HttpErrorResponse) => { 'OK',
this.credentialService.clearLocalAuthState(); {
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
duration: 5000, duration: 5000,
}); },
}, );
}); },
complete: () => {
this.isSubmitting = false;
this.otkForm.enable();
},
});
} }
editCredentials() { editCredentials() {
@@ -240,6 +232,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
} }
private getLoginErrorMessage(error: HttpErrorResponse): string { private getLoginErrorMessage(error: HttpErrorResponse): string {
console.error('Login error:', error);
if (error.status === 401) { if (error.status === 401) {
return 'E-Mail, Passwort oder OTK-Code ist ungültig.'; return 'E-Mail, Passwort oder OTK-Code ist ungültig.';
} }
@@ -84,9 +84,7 @@
mat-raised-button mat-raised-button
class="button" class="button"
(click)="submit()" (click)="submit()"
[disabled]=" [disabled]="!registerForm.valid || credentialService.isValidating()">
!registerForm.valid || (credentialService.validating | async)
">
Registrieren Registrieren
</button> </button>
@@ -4,7 +4,7 @@ import {
OnDestroy, OnDestroy,
signal, signal,
DestroyRef, DestroyRef,
OnInit, effect,
} from '@angular/core'; } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@@ -54,7 +54,7 @@ import { InstitutionsService } from '../../api';
templateUrl: './app-register.component.html', templateUrl: './app-register.component.html',
styleUrl: './app-register.component.scss', styleUrl: './app-register.component.scss',
}) })
export class AppRegisterComponent implements OnDestroy, OnInit { export class AppRegisterComponent implements OnDestroy {
private readonly fb = inject(FormBuilder); private readonly fb = inject(FormBuilder);
protected readonly credentialService = inject(CredentialService); protected readonly credentialService = inject(CredentialService);
private readonly router = inject(Router); private readonly router = inject(Router);
@@ -73,42 +73,37 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
showPassword = false; showPassword = false;
constructor() { constructor() {
effect(() => {
if (this.credentialService.isValidating()) {
this.registerForm.disable();
} else {
this.registerForm.enable();
this.checkEnter();
}
});
this.setupInstitutionAutocomplete(); this.setupInstitutionAutocomplete();
} }
ngOnInit(): void {
this.subscription = this.credentialService.validating.subscribe(
(validating) => {
if (validating) {
this.registerForm.disable();
} else {
this.registerForm.enable();
this.checkEnter();
}
},
);
if (!this.credentialService.validating) {
this.checkEnter();
}
}
ngOnDestroy(): void { ngOnDestroy(): void {
this.subscription?.unsubscribe(); this.subscription?.unsubscribe();
} }
checkEnter(): void { checkEnter(): void {
if (this.credentialService.isAuthenticated.value) { if (this.credentialService.isAuthenticated()) {
this.router.navigate(['/dashboard']); this.router.navigate(['/dashboard']);
} }
} }
submit() { submit() {
if (this.registerForm.valid) { if (this.registerForm.valid) {
this.credentialService.validating.next(true); this.credentialService.isValidating.set(true);
this.registerForm.disable(); this.registerForm.disable();
this.subscription = this.credentialService this.subscription = this.credentialService
.registerAccount(this.registerForm.value) .registerAccount(this.registerForm.value)
.subscribe({ .subscribe({
next: () => { next: () => {
this.credentialService.validating.next(false); this.credentialService.isValidating.set(false);
this.snackBar.open( this.snackBar.open(
'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.', 'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.',
'OK', 'OK',
@@ -117,7 +112,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
this.router.navigate(['/login']); this.router.navigate(['/login']);
}, },
error: (err) => { error: (err) => {
this.credentialService.validating.next(false); this.credentialService.isValidating.set(false);
this.registerForm.enable(); this.registerForm.enable();
const message = const message =
err.error?.message || err.error?.message ||
@@ -16,15 +16,22 @@ import {
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import type { import { InseOrganizationManagementModelOrganizationProfile } from '../../../api';
CreateOrganizationPayload,
OrganizationProfile, export interface CreateOrganizationPayload {
UpdateOrganizationPayload, name: string;
} from '../../../shared/services/organization-management.service'; other_inst_id?: string | null;
}
export interface UpdateOrganizationPayload {
name?: string;
other_inst_id?: string | null;
deleted?: boolean;
}
export interface OrganizationDialogData { export interface OrganizationDialogData {
mode: 'create' | 'edit'; mode: 'create' | 'edit';
organization?: OrganizationProfile; organization?: InseOrganizationManagementModelOrganizationProfile;
} }
export type OrganizationDialogResult = export type OrganizationDialogResult =
@@ -66,10 +73,9 @@ export class OrganizationDialogComponent {
nonNullable: true, nonNullable: true,
validators: [Validators.required], validators: [Validators.required],
}), }),
otherInstId: new FormControl( otherInstId: new FormControl(this.data.organization?.other_inst_id ?? '', {
this.data.organization?.other_inst_id ?? '', nonNullable: true,
{ nonNullable: true }, }),
),
deleted: new FormControl(this.data.organization?.deleted ?? false, { deleted: new FormControl(this.data.organization?.deleted ?? false, {
nonNullable: true, nonNullable: true,
}), }),
@@ -100,6 +106,6 @@ export class OrganizationDialogComponent {
} }
protected close(): void { protected close(): void {
this.dialogRef.close(undefined); this.dialogRef.close();
} }
} }
@@ -3,6 +3,7 @@
<div> <div>
<h1>Organisationen</h1> <h1>Organisationen</h1>
<p>Mandanten, externe Institutions-IDs und Status verwalten.</p> <p>Mandanten, externe Institutions-IDs und Status verwalten.</p>
<!-- Was meinte die KI mit Mandanten? -->
</div> </div>
<button <button
mat-flat-button mat-flat-button
@@ -14,92 +15,38 @@
</button> </button>
</header> </header>
<section class="table-panel"> <mat-card appearance="outlined">
<div class="table-header"> <mat-card-content>
<strong>{{ total }} Organisationen</strong> <app-data-table
@if (isLoading) { [columns]="organizationColumns"
<span>Wird geladen...</span> [data]="organizationPage().items" />
} </mat-card-content>
</div> </mat-card>
<app-query-param-paginator [total]="organizationPage().total" />
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Name</th>
<th>Externe Institutions-ID</th>
<th>Mitglieder</th>
<th>Status</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
@for (organization of organizations; track organization.id) {
<tr [class.deleted]="organization.deleted">
<td>
<button
class="link-button"
type="button"
(click)="startEdit(organization)">
{{ organization.name }}
</button>
</td>
<td>{{ organization.other_inst_id || '–' }}</td>
<td>{{ organization.member_count }}</td>
<td>
<span
class="status"
[class.status--deleted]="organization.deleted">
{{ organization.deleted ? 'deleted' : 'active' }}
</span>
</td>
<td>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Bearbeiten"
(click)="startEdit(organization)">
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Deaktivieren"
[disabled]="organization.deleted"
(click)="deleteOrganization(organization)">
<mat-icon>delete</mat-icon>
</button>
</div>
</td>
</tr>
} @empty {
<tr>
<td colspan="6" class="empty">Keine Organisationen gefunden.</td>
</tr>
}
</tbody>
</table>
</div>
<div class="pagination">
<button
mat-button
type="button"
[disabled]="!canPageBack"
(click)="loadOrganizations(page - 1)">
<mat-icon>chevron_left</mat-icon>
Zurück
</button>
<span>Seite {{ page + 1 }}</span>
<button
mat-button
type="button"
[disabled]="!canPageForward"
(click)="loadOrganizations(page + 1)">
Weiter
<mat-icon>chevron_right</mat-icon>
</button>
</div>
</section>
</section> </section>
<ng-template #organizationStatusTmp let-row>
<span class="status" [class.status--deleted]="row.deleted">
{{ (row.deleted ? 'inactive' : 'active') | status }}
</span>
</ng-template>
<ng-template #organizationActionsTmp let-row>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Bearbeiten"
(click)="startEdit(row)">
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Deaktivieren"
[disabled]="row.deleted"
(click)="deleteOrganization(row)">
<mat-icon>delete</mat-icon>
</button>
</div>
</ng-template>
@@ -5,15 +5,9 @@
padding: 24px; padding: 24px;
} }
.page-header, .page-header {
.table-header,
.pagination,
.row-actions {
display: flex; display: flex;
align-items: center; align-items: center;
}
.page-header {
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 16px;
} }
@@ -32,60 +26,6 @@ p {
margin-top: 6px; margin-top: 6px;
} }
.table-panel {
overflow: hidden;
border: 1px solid #d7dde6;
border-radius: 8px;
background: #fff;
}
.table-header {
justify-content: space-between;
padding: 16px;
border-bottom: 1px solid #e5e7eb;
}
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid #edf1f7;
white-space: nowrap;
}
th {
color: #475569;
font-weight: 700;
background: #f8fafc;
}
tr.deleted {
color: #94a3b8;
}
.identifier {
font-family: monospace;
font-size: 12px;
}
.link-button {
border: 0;
background: transparent;
color: #1d4ed8;
padding: 0;
font: inherit;
cursor: pointer;
}
.status { .status {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -103,21 +43,6 @@ tr.deleted {
color: #991b1b; color: #991b1b;
} }
.row-actions {
gap: 4px;
}
.empty {
color: #64748b;
text-align: center;
}
.pagination {
justify-content: flex-end;
gap: 8px;
padding: 12px 16px;
}
@media (max-width: 640px) { @media (max-width: 640px) {
.organizations-page { .organizations-page {
padding: 16px; padding: 16px;
@@ -128,3 +53,8 @@ tr.deleted {
flex-direction: column; flex-direction: column;
} }
} }
mat-card,
mat-paginator {
background-color: var(--sg-background);
}
@@ -1,19 +1,34 @@
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core'; import {
Component,
inject,
input,
OnInit,
TemplateRef,
viewChild,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { finalize } from 'rxjs';
import {
OrganizationManagementService,
OrganizationProfile,
} from '../../shared/services/organization-management.service';
import type { import type {
OrganizationDialogComponent, OrganizationDialogComponent,
OrganizationDialogData, OrganizationDialogData,
OrganizationDialogResult, OrganizationDialogResult,
} from './organization-dialog/organization-dialog.component'; } from './organization-dialog/organization-dialog.component';
import {
InseOrganizationManagementModelOrganizationProfile,
OrganizationPage,
OrganizationService,
} from '../../api';
import {
GenericColumn,
DataTableComponent,
} from '../../shared/ui/data-table/data-table.component';
import { MatCardModule } from '@angular/material/card';
import { StatusPipe } from '../../shared/pipes/status.pipe';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { Router } from '@angular/router';
@Component({ @Component({
selector: 'app-organizations', selector: 'app-organizations',
@@ -23,50 +38,81 @@ import type {
MatDialogModule, MatDialogModule,
MatIconModule, MatIconModule,
MatSnackBarModule, MatSnackBarModule,
DataTableComponent,
MatCardModule,
StatusPipe,
QueryParamPaginatorComponent,
], ],
templateUrl: './organizations.component.html', templateUrl: './organizations.component.html',
styleUrl: './organizations.component.scss', styleUrl: './organizations.component.scss',
standalone: true, standalone: true,
}) })
export class OrganizationsComponent implements OnInit { export class OrganizationsComponent implements OnInit {
private readonly organizationService = inject(OrganizationManagementService); private readonly router = inject(Router);
private readonly dialog = inject(MatDialog); private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar); private readonly snackBar = inject(MatSnackBar);
private readonly organizationService = inject(OrganizationService);
protected organizations: OrganizationProfile[] = []; organizationPage = input.required<OrganizationPage>();
protected total = 0; organizationColumns: GenericColumn<InseOrganizationManagementModelOrganizationProfile>[] =
protected page = 0; [];
protected readonly pageSize = 10;
protected isLoading = false; organizationStatusTmp = viewChild.required<TemplateRef<any>>(
'organizationStatusTmp',
);
organizationActionsTmp = viewChild.required<TemplateRef<any>>(
'organizationActionsTmp',
);
ngOnInit(): void { ngOnInit(): void {
this.loadOrganizations(); this.organizationColumns = [
} {
id: 'name',
protected loadOrganizations(page = this.page): void { header: 'Name',
this.page = page; type: 'accessor',
this.isLoading = true; accessorKey: 'name',
this.organizationService },
.getOrganizations(page, this.pageSize) {
.pipe(finalize(() => (this.isLoading = false))) id: 'other_inst_id',
.subscribe({ header: 'Externe ID',
next: (result) => { type: 'accessor',
this.organizations = result.items; accessorKey: 'other_inst_id',
this.total = result.total; },
}, {
error: () => this.showError('Organisationen konnten nicht geladen werden.'), id: 'member_count',
}); header: 'Mitglieder',
type: 'accessor',
accessorKey: 'member_count',
},
{
id: 'deleted',
header: 'Status',
type: 'accessor',
accessorKey: 'deleted',
cellTemplate: this.organizationStatusTmp(),
},
{
id: 'actions',
header: 'Aktionen',
type: 'display',
cellTemplate: this.organizationActionsTmp(),
},
];
} }
protected startCreate(): void { protected startCreate(): void {
this.openDialog({ mode: 'create' }); this.openDialog({ mode: 'create' });
} }
protected startEdit(organization: OrganizationProfile): void { protected startEdit(
organization: InseOrganizationManagementModelOrganizationProfile,
): void {
this.openDialog({ mode: 'edit', organization }); this.openDialog({ mode: 'edit', organization });
} }
protected deleteOrganization(organization: OrganizationProfile): void { protected deleteOrganization(
organization: InseOrganizationManagementModelOrganizationProfile,
): void {
if (organization.deleted) return; if (organization.deleted) return;
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
@@ -87,26 +133,24 @@ export class OrganizationsComponent implements OnInit {
); );
} }
private softDeleteOrganization(organization: OrganizationProfile): void { private softDeleteOrganization(
this.organizationService.deleteOrganization(organization.id).subscribe({ organization: InseOrganizationManagementModelOrganizationProfile,
): void {
this.organizationService.deleteOrganisation(organization.id).subscribe({
next: () => { next: () => {
this.snackBar.open('Organisation wurde deaktiviert.', 'OK', { this.snackBar.open('Organisation wurde deaktiviert.', 'OK', {
duration: 3000, duration: 3000,
}); });
this.loadOrganizations(); this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
}, },
error: () => this.showError('Organisation konnte nicht deaktiviert werden.'), error: () =>
this.showError('Organisation konnte nicht deaktiviert werden.'),
}); });
} }
protected get canPageBack(): boolean {
return this.page > 0;
}
protected get canPageForward(): boolean {
return (this.page + 1) * this.pageSize < this.total;
}
private openDialog(data: OrganizationDialogData): void { private openDialog(data: OrganizationDialogData): void {
import('./organization-dialog/organization-dialog.component').then( import('./organization-dialog/organization-dialog.component').then(
({ OrganizationDialogComponent }) => { ({ OrganizationDialogComponent }) => {
@@ -130,8 +174,8 @@ export class OrganizationsComponent implements OnInit {
private save(result: OrganizationDialogResult): void { private save(result: OrganizationDialogResult): void {
const request = const request =
result.mode === 'create' result.mode === 'create'
? this.organizationService.createOrganization(result.payload) ? this.organizationService.createOrganisation(result.payload)
: this.organizationService.updateOrganization( : this.organizationService.updateOrganisation(
result.organizationId, result.organizationId,
result.payload, result.payload,
); );
@@ -141,7 +185,10 @@ export class OrganizationsComponent implements OnInit {
this.snackBar.open('Organisation wurde gespeichert.', 'OK', { this.snackBar.open('Organisation wurde gespeichert.', 'OK', {
duration: 3000, duration: 3000,
}); });
this.loadOrganizations(0); this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
}, },
error: (error) => error: (error) =>
this.showError( this.showError(
+2 -3
View File
@@ -1,8 +1,7 @@
import { ResolveFn } from '@angular/router'; import { ResolveFn } from '@angular/router';
import { AccountProfile } from '../api'; import { AccountProfile, AuthService } from '../api';
import { inject } from '@angular/core'; import { inject } from '@angular/core';
import { AccountManagementService } from '../shared/services/account-management.service';
export const accountResolver: ResolveFn<AccountProfile> = (route, state) => { export const accountResolver: ResolveFn<AccountProfile> = (route, state) => {
return inject(AccountManagementService).getCurrentAccount(); return inject(AuthService).getCurrentAccount();
}; };
@@ -0,0 +1,12 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import {
AuthService,
InseAccountManagementModelOrganizationProfile,
} from '../api';
export const accountsOrganizationResolver: ResolveFn<
InseAccountManagementModelOrganizationProfile[]
> = (route, state) => {
return inject(AuthService).listAccountOrganizations();
};
@@ -0,0 +1,19 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import { AccountPage, AuthService } from '../api';
export const accountsPageResolver: ResolveFn<AccountPage> = (route, state) => {
const page = Number(route.queryParamMap.get('page') ?? '0');
const size = Number(route.queryParamMap.get('size') ?? '10');
const search = route.queryParamMap.get('search') || undefined;
const organizationId =
route.queryParamMap.get('organization_id') || undefined;
return inject(AuthService).listAccounts(
page,
size,
undefined,
search,
organizationId,
);
};
@@ -0,0 +1,12 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { OrganizationPage, OrganizationService } from '../api';
export const organizationsOrganizationsResolver: ResolveFn<
OrganizationPage
> = (route, state) => {
const page = Number(route.queryParamMap.get('page') ?? '0');
const size = Number(route.queryParamMap.get('size') ?? '10');
return inject(OrganizationService).getOrganisations(page, size);
};
@@ -1,36 +1,41 @@
import { inject } from '@angular/core'; import { effect, inject, Injector } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router'; import { CanActivateFn, Router } from '@angular/router';
import { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service'; import { CredentialService } from '../services/credential.service';
export const accountViewerGuard: CanActivateFn = () => { export const accountViewerGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService); const credentialService = inject(CredentialService);
const router = inject(Router); const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe( return new Promise<boolean>((resolve) => {
filter((validating) => !validating), const ref = effect(
take(1), () => {
switchMap(() => { if (credentialService.isValidating()) {
if (!credentialService.isAuthenticated.value) { return;
void router.navigate(['/login']); }
return of(false);
}
return credentialService.validateCurrentSession().pipe( ref.destroy();
switchMap(() => {
const mayViewAccounts =
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin() ||
credentialService.isEffectiveManager();
if (!mayViewAccounts) { if (!credentialService.isAuthenticated()) {
void router.navigate(['/dashboard']); void router.navigate(['/login']);
} resolve(false);
return;
}
return of(mayViewAccounts); const mayViewAccounts =
}), credentialService.isEffectiveSuperAdmin() ||
catchError(() => of(false)), credentialService.isEffectiveAdmin() ||
); credentialService.isEffectiveManager();
}),
); if (!mayViewAccounts) {
void router.navigate(['/dashboard']);
resolve(false);
return;
}
resolve(true);
},
{ injector },
);
});
}; };
+26 -25
View File
@@ -1,35 +1,36 @@
import { inject } from '@angular/core'; import { effect, inject, Injector } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router'; import { CanActivateFn, Router } from '@angular/router';
import { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service'; import { CredentialService } from '../services/credential.service';
export const adminGuard: CanActivateFn = () => { export const adminGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService); const credentialService = inject(CredentialService);
const router = inject(Router); const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe( return new Promise<boolean>((resolve) => {
filter((validating) => !validating), const ref = effect(
take(1), () => {
switchMap(() => { if (credentialService.isValidating()) {
if (!credentialService.isAuthenticated.value) { return;
void router.navigate(['/login']); }
return of(false);
}
return credentialService.validateCurrentSession().pipe( ref.destroy();
switchMap(() => {
if (
!credentialService.isEffectiveSuperAdmin() &&
!credentialService.isEffectiveAdmin()
) {
void router.navigate(['/dashboard']);
return of(false);
}
return of(true); if (!credentialService.isAuthenticated()) {
}), void router.navigate(['/login']);
catchError(() => of(false)), resolve(false);
); return;
}), }
);
if (!credentialService.isEffectiveAdmin()) {
void router.navigate(['/dashboard']);
resolve(false);
return;
}
resolve(true);
},
{ injector },
);
});
}; };
@@ -1,31 +1,36 @@
import { inject } from '@angular/core'; import { effect, inject, Injector } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router'; import { CanActivateFn, Router } from '@angular/router';
import { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service'; import { CredentialService } from '../services/credential.service';
export const superAdminGuard: CanActivateFn = () => { export const superAdminGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService); const credentialService = inject(CredentialService);
const router = inject(Router); const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe( return new Promise<boolean>((resolve) => {
filter((validating) => !validating), const ref = effect(
take(1), () => {
switchMap(() => { if (credentialService.isValidating()) {
if (!credentialService.isAuthenticated.value) { return;
void router.navigate(['/login']); }
return of(false);
}
return credentialService.validateCurrentSession().pipe( ref.destroy();
switchMap(() => {
if (!credentialService.isEffectiveSuperAdmin()) { if (!credentialService.isAuthenticated()) {
void router.navigate(['/dashboard']); void router.navigate(['/login']);
return of(false); resolve(false);
} return;
return of(true); }
}),
catchError(() => of(false)), if (!credentialService.isEffectiveSuperAdmin()) {
); void router.navigate(['/dashboard']);
}), resolve(false);
); return;
}
resolve(true);
},
{ injector },
);
});
}; };
+21 -16
View File
@@ -1,25 +1,30 @@
import { inject } from '@angular/core'; import { effect, inject, Injector } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router'; import { CanActivateFn, Router } from '@angular/router';
import { catchError, filter, map, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service'; import { CredentialService } from '../services/credential.service';
export const userGuard: CanActivateFn = () => { export const userGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService); const credentialService = inject(CredentialService);
const router = inject(Router); const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe( return new Promise<boolean>((resolve) => {
filter((validating) => !validating), const ref = effect(
take(1), () => {
switchMap(() => { if (credentialService.isValidating()) {
if (!credentialService.isAuthenticated.value) { return;
void router.navigate(['/login']); }
return of(false);
}
return credentialService.validateCurrentSession().pipe( ref.destroy();
map(() => true),
catchError(() => of(false)), if (!credentialService.isAuthenticated()) {
); void router.navigate(['/login']);
}), resolve(false);
); return;
}
resolve(true);
},
{ injector },
);
});
}; };
@@ -1,86 +1,104 @@
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; import {
HttpErrorResponse,
HttpInterceptorFn,
HttpRequest,
} from '@angular/common/http';
import { inject } from '@angular/core'; import { inject } from '@angular/core';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar'; import { catchError, switchMap, throwError } from 'rxjs';
import { catchError, switchMap, tap, throwError } from 'rxjs'; import {
import { CredentialService } from '../services/credential.service'; CredentialService,
import { UiFocusService } from '../services/ui-focus.service'; clearStoredAuthState,
REQUIRED_TOKEN_TYPE,
TOKEN_TYPE,
} from '../services/credential.service';
export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { const attachBearer = <T>(
const url = req.url.split('?')[0]; req: HttpRequest<T>,
const uiFocusService = inject(UiFocusService); token: string,
): HttpRequest<T> => {
if (!token) {
return req;
}
return req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token),
});
};
const isPublicAuthRequest = const handleAccessTokenError = (
req.method === 'POST' && error: unknown,
(url.endsWith('/api/auth/v2/request-otk') || req: HttpRequest<unknown>,
url.endsWith('/api/auth/v2/login') || next: Parameters<HttpInterceptorFn>[1],
url.endsWith('/api/auth/v2/access') || credentialService: CredentialService,
url.endsWith('/api/auth/v2/refresh')); router: Router,
) => {
if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) { if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
return next(req); return throwError(() => error);
} }
const credentialService = inject(CredentialService); if (!credentialService.getRawAccessToken()) {
const router = inject(Router); credentialService.logout();
const snackBar = inject(MatSnackBar); router.navigate(['/login'], { replaceUrl: true });
const tokenProvider = credentialService.getBearerToken(); return throwError(() => error);
const isLogoutRequest = url.endsWith('/api/auth/v2/logout'); }
return tokenProvider.pipe( return credentialService.refreshAccessToken().pipe(
switchMap((response) => { switchMap((accessToken) => next(attachBearer(req, accessToken.raw_token))),
if (response == undefined) { catchError((refreshError) => {
credentialService.clearLocalAuthState(); credentialService.logout();
router.navigate(['/login'], { replaceUrl: true });
snackBar.open( return throwError(() => refreshError);
'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.',
'OK',
{ duration: 7000 },
);
void router.navigate(['/login']);
return throwError(
() => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }),
);
}
const authorizedRequest = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + response),
});
return next(authorizedRequest).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401 && !isLogoutRequest) {
return credentialService.handleUnauthorized().pipe(
tap((result) => {
uiFocusService.blurActiveElement();
if (result === 'stopped-impersonating') {
snackBar.open(
'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.',
'OK',
{ duration: 7000 },
);
void router.navigate(['/accounts']);
} else if (result === 'logged-out') {
snackBar.open(
'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.',
'OK',
{ duration: 7000 },
);
void router.navigate(['/login']);
}
}),
switchMap(() => throwError(() => error)),
);
}
return throwError(() => error);
}),
);
}), }),
); );
}; };
export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
const requiredType = req.context.get(REQUIRED_TOKEN_TYPE);
if (requiredType === TOKEN_TYPE.NONE) {
return next(req);
}
if (requiredType === TOKEN_TYPE.ID_TOKEN_COOKIE) {
return next(req.clone({ withCredentials: true })).pipe(
catchError((err) => {
if (err instanceof HttpErrorResponse && err.status === 401) {
clearStoredAuthState();
router.navigate(['/login'], { replaceUrl: true });
}
return throwError(() => err);
}),
);
}
if (requiredType === TOKEN_TYPE.REFRESH_TOKEN_COOKIE) {
return next(req.clone({ withCredentials: true }));
}
const credentialService = inject(CredentialService);
const rawAccessToken = credentialService.getRawAccessToken();
if (rawAccessToken && credentialService.accessTokenIsExpired()) {
return credentialService.refreshAccessToken().pipe(
switchMap((accessToken) =>
next(attachBearer(req, accessToken.raw_token)),
),
catchError(() => {
credentialService.logout();
router.navigate(['/login'], { replaceUrl: true });
return throwError(
() => new Error('Sitzung abgelaufen. Bitte erneut anmelden.'),
);
}),
);
}
return next(rawAccessToken ? attachBearer(req, rawAccessToken) : req).pipe(
catchError((err) =>
handleAccessTokenError(err, req, next, credentialService, router),
),
);
};
@@ -0,0 +1,18 @@
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'status',
})
export class StatusPipe implements PipeTransform {
transform(value: string, ...args: unknown[]): string {
value = value?.toUpperCase() ?? '';
switch (value) {
case 'ACTIVE':
return 'Aktiv';
case 'INACTIVE':
return 'Inaktiv';
default:
return value;
}
}
}
@@ -1,124 +0,0 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Configuration } from '../../api';
export type AccountRole = 'SUPER_ADMIN' | 'ADMIN' | 'MANAGER' | 'USER';
export interface AccountProfile {
id: string;
email: string;
name: string;
role: AccountRole;
organization_id: string;
organization_name: string;
deleted: boolean;
activated: boolean;
is_current: boolean;
is_real_account: boolean;
is_impersonating: boolean;
}
export interface AccountPage {
items: AccountProfile[];
total: number;
page: number;
page_size: number;
}
export interface OrganizationProfile {
id: string;
name: string;
openalex_institution_id?: string | null;
}
export interface AccountPayload {
email?: string;
name?: string;
role?: AccountRole;
organization_id?: string;
password?: string;
deleted?: boolean;
activated?: boolean;
}
export interface CreateAccountPayload {
email: string;
name: string;
role: AccountRole;
organization_id: string;
password: string;
}
@Injectable({
providedIn: 'root',
})
export class AccountManagementService {
private readonly httpClient = inject(HttpClient);
private readonly apiConfiguration = inject(Configuration, { optional: true });
getCurrentAccount(): Observable<AccountProfile> {
return this.httpClient.get<AccountProfile>(
`${this.apiBasePath}/api/accounts/me`,
);
}
listAccounts(options: {
page: number;
pageSize: number;
search?: string;
organizationId?: string;
}): Observable<AccountPage> {
let params = new HttpParams()
.set('page', options.page)
.set('page_size', options.pageSize);
if (options.search) {
params = params.set('search', options.search);
}
if (options.organizationId) {
params = params.set('organization_id', options.organizationId);
}
return this.httpClient.get<AccountPage>(
`${this.apiBasePath}/api/accounts`,
{
params,
},
);
}
createAccount(payload: CreateAccountPayload): Observable<AccountProfile> {
return this.httpClient.post<AccountProfile>(
`${this.apiBasePath}/api/accounts`,
payload,
);
}
updateAccount(
accountId: string,
payload: AccountPayload,
): Observable<AccountProfile> {
return this.httpClient.put<AccountProfile>(
`${this.apiBasePath}/api/accounts/${accountId}`,
payload,
);
}
deleteAccount(accountId: string): Observable<void> {
return this.httpClient.delete<void>(
`${this.apiBasePath}/api/accounts/${accountId}`,
);
}
listOrganizations(): Observable<OrganizationProfile[]> {
return this.httpClient.get<OrganizationProfile[]>(
`${this.apiBasePath}/api/accounts/organizations`,
);
}
private get apiBasePath(): string {
return this.apiConfiguration?.basePath ?? '';
}
}
@@ -1,49 +1,73 @@
import { Injectable, computed, inject, signal } from '@angular/core'; import { Injectable, computed, effect, inject, signal } from '@angular/core';
import { filter, take, map, catchError, finalize } from 'rxjs/operators'; import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { import {
BehaviorSubject, catchError,
finalize,
firstValueFrom,
map,
Observable, Observable,
of, of,
shareReplay,
switchMap, switchMap,
tap, tap,
throwError, throwError,
} from 'rxjs'; } from 'rxjs';
import { import {
AccessResponse, AccessResponse,
AccessToken,
AuthService, AuthService,
Configuration,
IdToken,
LoginResponse,
AccountProfile, AccountProfile,
OtkResponse,
IdTokenMetadata,
AccessToken,
LoginResponse,
} from '../../api'; } from '../../api';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
type LogoutResult = 'logged-out' | 'stopped-impersonating'; import { Router } from '@angular/router';
type UnauthorizedRecoveryResult = import { HttpContext, HttpContextToken } from '@angular/common/http';
| 'logged-out'
| 'stopped-impersonating' export const TOKEN_TYPE = {
| 'already-handling'; ACCESS_TOKEN: 'ACCESS_TOKEN',
ID_TOKEN_COOKIE: 'ID_TOKEN_COOKIE',
REFRESH_TOKEN_COOKIE: 'REFRESH_TOKEN_COOKIE',
NONE: 'NONE',
} as const;
export type TokenContextType = (typeof TOKEN_TYPE)[keyof typeof TOKEN_TYPE];
export const REQUIRED_TOKEN_TYPE = new HttpContextToken<TokenContextType>(
() => TOKEN_TYPE.ACCESS_TOKEN,
);
const STORAGE_KEY = 'auth_state';
export const clearStoredAuthState = (): void => {
localStorage.removeItem(STORAGE_KEY);
};
export interface StoredAuthState {
idTokenMetadata: IdTokenMetadata | null;
accessToken: AccessToken | null;
}
const EXPIRY_SKEW_MS = 10 * 1000; // 10 seconds
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class CredentialService { export class CredentialService {
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly httpClient = inject(HttpClient);
private readonly apiConfiguration = inject(Configuration, { optional: true });
private handlingUnauthorized = false;
private static readonly KEY_GRANT = 'grant'; public readonly isValidating = signal<boolean>(false);
public readonly isAuthenticated = computed(
public readonly validating = new BehaviorSubject<boolean>(false); () => this.accessToken() !== undefined,
public readonly isAuthenticated = new BehaviorSubject<boolean>(false); );
public readonly isEffectiveSuperAdmin = computed( public readonly isEffectiveSuperAdmin = computed(
() => this.accessToken()?.effective_role === 'SUPER_ADMIN', () => this.accessToken()?.effective_role === 'SUPER_ADMIN',
); );
public readonly isEffectiveAdmin = computed( public readonly isEffectiveAdmin = computed(
() => this.accessToken()?.effective_role === 'ADMIN', () =>
this.accessToken()?.effective_role === 'ADMIN' ||
this.isEffectiveSuperAdmin(),
); );
public readonly isEffectiveManager = computed( public readonly isEffectiveManager = computed(
() => this.accessToken()?.effective_role === 'MANAGER', () => this.accessToken()?.effective_role === 'MANAGER',
@@ -51,9 +75,13 @@ export class CredentialService {
public readonly effectiveOrganizationId = computed( public readonly effectiveOrganizationId = computed(
() => this.accessToken()?.effective_organization_id, () => this.accessToken()?.effective_organization_id,
); );
public readonly login = new BehaviorSubject<string>(''); public readonly login = computed(
public readonly email = new BehaviorSubject<string>(''); () => this.accountProfile()?.name ?? this.accountProfile()?.email ?? '',
public readonly organizationName = new BehaviorSubject<string>(''); );
public readonly email = computed(() => this.accountProfile()?.email ?? '');
public readonly organizationName = computed(
() => this.accountProfile()?.organization_name ?? '',
);
public readonly realAccountId = computed( public readonly realAccountId = computed(
() => this.accessToken()?.real_account_id ?? '', () => this.accessToken()?.real_account_id ?? '',
@@ -65,298 +93,283 @@ export class CredentialService {
() => this.realAccountId() !== this.effectiveAccountId(), () => this.realAccountId() !== this.effectiveAccountId(),
); );
private readonly identityToken = signal<IdToken | undefined>(undefined); public readonly accessToken = signal<AccessToken | undefined>(undefined);
private readonly accessToken = signal<AccessToken | undefined>(undefined);
public readonly isActiveAccessToken = computed(() => {
const accessToken = this.accessToken();
return (
accessToken !== undefined &&
new Date(accessToken.expires_at).getTime() >= Date.now()
);
});
public readonly accountProfile = toSignal<AccountProfile | undefined>(
toObservable(this.accessToken).pipe(
switchMap((accessToken) =>
accessToken
? this.authService.getCurrentAccount()
: of<AccountProfile | undefined>(undefined),
),
),
{ initialValue: undefined },
);
private refreshInFlight$: Observable<AccessToken> | null = null;
private request = 0; private request = 0;
constructor(private readonly router: Router) { constructor(private readonly router: Router) {
const data = localStorage.getItem(CredentialService.KEY_GRANT); this.restoreAuthState();
const id = data ? (JSON.parse(data) as AccessToken) : undefined;
if (id && new Date(id.expires_at).getTime() >= Date.now()) { effect(() => {
this.identityToken.set(id); console.log('Access token changed:', this.accessToken());
this.validating.next(true); });
setTimeout(() => this.refreshAccessToken(id), 0);
const storedAccessToken = this.getStoredAccessToken();
if (storedAccessToken && this.isExpired(storedAccessToken)) {
this.refreshAccessToken().subscribe({
error: (err) => {
console.error('Error refreshing access token on init:', err);
this.logout();
this.router.navigate(['/login'], { replaceUrl: true });
},
});
} }
} }
public validateCurrentSession(): Observable<void> { private restoreAuthState(): void {
return this.loadCurrentProfile(); this.accessToken.set(this.getStoredAccessToken() ?? undefined);
} }
public requestOtk(email: string, password: string): Observable<string> { private readAuthState(): StoredAuthState {
const request = ++this.request; const raw = localStorage.getItem(STORAGE_KEY);
this.validating.next(true); if (!raw) {
this.isAuthenticated.next(false); return { idTokenMetadata: null, accessToken: null };
this.identityToken.set(undefined); }
try {
return JSON.parse(raw) as StoredAuthState;
} catch {
return { idTokenMetadata: null, accessToken: null };
}
}
private writeAuthState(patch: Partial<StoredAuthState>): void {
const next: StoredAuthState = {
...this.readAuthState(),
...patch,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
}
private persistAccessToken(accessToken: AccessToken | null): void {
this.writeAuthState({ accessToken });
this.accessToken.set(accessToken ?? undefined);
}
private getStoredIdTokenMetadata(): IdTokenMetadata | null {
return this.readAuthState().idTokenMetadata;
}
private getStoredAccessToken(): AccessToken | null {
return this.readAuthState().accessToken;
}
private isExpired(token: { expires_at: string }): boolean {
return new Date(token.expires_at).getTime() < Date.now() + EXPIRY_SKEW_MS;
}
public accessTokenIsExpired(): boolean {
const accessToken = this.getStoredAccessToken();
return !accessToken || this.isExpired(accessToken);
}
public logout() {
clearStoredAuthState();
this.accessToken.set(undefined); this.accessToken.set(undefined);
this.refreshInFlight$ = null;
}
return this.authService public requestOtk(email: string, password: string): Observable<OtkResponse> {
.requestOtk({ email: email.trim().toLowerCase(), password }) return this.authService.requestOtk(
.pipe( {
map((response: { account_id?: string }) => { email: email.trim(),
if (this.request !== request) { password: password.trim(),
return ''; },
} undefined,
undefined,
return response.account_id ?? ''; { context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
}), );
finalize(() => {
if (this.request === request) {
this.validating.next(false);
}
}),
);
} }
public loginWithOtk( public loginWithOtk(
accountId: string, accountId: string,
email: string,
emailCode: string, emailCode: string,
): Observable<void> { ): Observable<LoginResponse> {
const request = ++this.request;
this.validating.next(true);
this.isAuthenticated.next(false);
return this.authService return this.authService
.login({ account_id: accountId, email_code: emailCode.trim() }) .login(
{
account_id: accountId,
email_code: emailCode.trim(),
},
undefined,
undefined,
{
context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE),
},
)
.pipe( .pipe(
switchMap((response: LoginResponse) => { tap(({ id_token }) =>
if (this.request != request) return of(undefined); this.writeAuthState({ idTokenMetadata: id_token }),
),
const idToken = response.id_token;
this.identityToken.set(idToken);
localStorage.setItem(
CredentialService.KEY_GRANT,
JSON.stringify(idToken),
);
return this.getAccessGrantForIdentity(idToken, request);
}),
); );
} }
public refreshAccessToken(identityToken: IdToken) { public requestAccess(
const request = ++this.request; realAccountId: string,
this.validating.next(true); effectiveAccountId?: string,
this.accessToken.set(undefined); ): Observable<AccessResponse> {
this.getAccessGrantForIdentity(identityToken, request).subscribe({
error: () => {
if (this.request != request) return;
this.clearLocalAuthState();
},
});
}
public impersonateAccount(accountId: string): Observable<void> {
const idToken = this.identityToken();
if (!idToken) {
return throwError(() => new Error('No identity token available.'));
}
const request = ++this.request;
this.validating.next(true);
this.accessToken.set(undefined);
return this.getAccessGrantForIdentity(idToken, request, accountId).pipe(
tap({ error: () => this.validating.next(false) }),
);
}
public stopImpersonating(): Observable<void> {
const idToken = this.identityToken();
if (!idToken) {
return throwError(() => new Error('No identity token available.'));
}
const request = ++this.request;
this.validating.next(true);
this.accessToken.set(undefined);
return this.getAccessGrantForIdentity(idToken, request).pipe(
tap({ error: () => this.validating.next(false) }),
);
}
public logoutAccount(): Observable<LogoutResult> {
const wasImpersonating = this.isImpersonating();
return this.authService return this.authService
.logout('body', false, { transferCache: false }) .getAccessToken(
{
real_account_id: realAccountId,
effective_account_id: effectiveAccountId ?? realAccountId,
},
undefined,
'body',
undefined,
{
context: new HttpContext().set(
REQUIRED_TOKEN_TYPE,
TOKEN_TYPE.ID_TOKEN_COOKIE,
),
},
)
.pipe( .pipe(
catchError((error) => { tap(({ access_token }) => {
console.error('Backend logout failed', error); this.persistAccessToken(access_token);
return of(null);
}),
switchMap(() => {
if (!wasImpersonating) {
this.clearLocalAuthState();
return of('logged-out' as const);
}
return this.stopImpersonating().pipe(
map(() => 'stopped-impersonating' as const),
catchError((error) => {
console.error('Stop impersonating after logout failed', error);
this.clearLocalAuthState();
return of('logged-out' as const);
}),
);
}), }),
); );
} }
public clearLocalAuthState(): void {
this.request += 1;
localStorage.removeItem(CredentialService.KEY_GRANT);
this.identityToken.set(undefined);
this.accessToken.set(undefined);
this.isAuthenticated.next(false);
this.validating.next(false);
this.login.next('');
this.email.next('');
this.organizationName.next('');
this.router.navigate(['/login'], { replaceUrl: true });
}
public handleUnauthorized(): Observable<UnauthorizedRecoveryResult> {
if (this.handlingUnauthorized) {
return of('already-handling' as const);
}
this.handlingUnauthorized = true;
const isImpersonating = this.isImpersonating();
const identityToken = this.identityToken();
const recovery$ =
isImpersonating && identityToken
? this.stopImpersonating().pipe(
map(() => 'stopped-impersonating' as const),
catchError((error) => {
console.error('Failed to stop impersonation after 401', error);
this.clearLocalAuthState();
return of('logged-out' as const);
}),
)
: of(null).pipe(
tap(() => this.clearLocalAuthState()),
map(() => 'logged-out' as const),
);
return recovery$.pipe(
finalize(() => {
this.handlingUnauthorized = false;
}),
);
}
public changePassword( public changePassword(
currentPassword: string, currentPassword: string,
newPassword: string, newPassword: string,
): Observable<void> { ): Observable<void> {
return this.httpClient this.isValidating.set(true);
.post( return this.authService
`${this.apiBasePath}/api/auth/v2/change-password`, .changePassword({
{ current_password: currentPassword,
current_password: currentPassword, new_password: newPassword,
new_password: newPassword, })
},
{ withCredentials: true },
)
.pipe( .pipe(
tap(() => { tap(() => this.isValidating.set(false)),
this.clearLocalAuthState();
}),
map(() => undefined),
catchError((err) => { catchError((err) => {
throw err; this.isValidating.set(false);
return throwError(() => err);
}), }),
); );
} }
public refreshAccessToken(): Observable<AccessToken> {
if (this.refreshInFlight$) {
return this.refreshInFlight$;
}
this.refreshInFlight$ = this.authService
.refreshAccessToken(undefined, 'body', undefined, {
context: new HttpContext().set(
REQUIRED_TOKEN_TYPE,
TOKEN_TYPE.REFRESH_TOKEN_COOKIE, // 'REFRESH_TOKEN_COOKIE' and NOT 'REFRESH_COOKIE', + 30 Minutes debugging this shit, changed to types
),
})
.pipe(
tap((accessToken) => {
this.persistAccessToken(accessToken);
}),
catchError(() => this.reauthenticateViaIdToken()),
finalize(() => {
this.refreshInFlight$ = null;
}),
shareReplay(1),
);
return this.refreshInFlight$;
}
reauthenticateViaIdToken(): Observable<AccessToken> {
const idTokenMetadata = this.getStoredIdTokenMetadata();
if (!idTokenMetadata || this.isExpired(idTokenMetadata)) {
this.logout();
return throwError(
() => new Error('No valid ID token metadata available.'),
);
}
return this.requestAccess(
idTokenMetadata.real_account_id,
idTokenMetadata.real_account_id,
).pipe(
map(({ access_token }) => access_token),
catchError((err) => {
console.error('Error reauthenticating via ID token:', err);
this.logout();
return throwError(() => err);
}),
);
}
public getRawAccessToken(): string | undefined {
return this.getStoredAccessToken()?.raw_token;
}
public async impersonateAccount(effectiveAccountId: string): Promise<void> {
const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id;
if (!realAccountId) {
throw new Error('No real account ID available.');
}
const request = ++this.request;
this.isValidating.set(true);
try {
await firstValueFrom(
this.requestAccess(realAccountId, effectiveAccountId),
);
} finally {
if (request === this.request) {
this.isValidating.set(false);
}
}
}
public async stopImpersonating(): Promise<void> {
this.isValidating.set(true);
const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id;
if (!realAccountId) {
throw new Error('No real account ID available.');
}
try {
await firstValueFrom(this.requestAccess(realAccountId, realAccountId));
} finally {
this.isValidating.set(false);
}
}
public async logoutAccount(): Promise<void> {
try {
await firstValueFrom(this.authService.logout());
} catch (err) {
console.error('Error logging out on the server:', err);
} finally {
this.logout();
await this.router.navigate(['/login'], { replaceUrl: true });
}
}
public registerAccount(_data: unknown): Observable<never> { public registerAccount(_data: unknown): Observable<never> {
return throwError(() => new Error('Registration is temporarily disabled.')); return throwError(() => new Error('Registration is temporarily disabled.'));
} }
//review: arman (generated fix)
public getBearerToken(): Observable<string | undefined> {
const accessToken = this.accessToken();
const identityToken = this.identityToken();
// 1. If we have a valid access token, return it immediately and complete.
if (
accessToken &&
Date.now() < new Date(accessToken.expires_at).getTime()
) {
return of(accessToken.raw_token);
}
// 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh.
if (!this.validating.value) {
if (!identityToken) {
return of(undefined); // No identity token to refresh with.
}
this.refreshAccessToken(identityToken);
}
// 3. Wait for the validation to finish, then return the resulting token.
return this.validating.pipe(
filter((isValidating) => !isValidating), // Wait until validating becomes false
take(1), // Take exactly 1 emission and then automatically complete()
map(() => this.accessToken()?.raw_token),
);
}
private getAccessGrantForIdentity(
idToken: IdToken,
request: number,
effectiveAccountId?: string,
): Observable<void> {
const realAccountId = idToken.real_account_id;
const headers = new HttpHeaders({
Authorization: `Bearer ${idToken.raw_token}`,
});
const payload = {
real_account_id: realAccountId,
effective_account_id: effectiveAccountId ?? realAccountId,
};
return this.httpClient
.post<AccessResponse>(`${this.apiBasePath}/api/auth/v2/access`, payload, {
headers,
withCredentials: true,
})
.pipe(
tap((result: AccessResponse) => {
if (this.request != request) return;
const accessToken = result.access_token;
this.accessToken.set(accessToken);
this.isAuthenticated.next(true);
this.validating.next(false);
}),
map(() => undefined),
);
}
private get apiBasePath(): string {
return this.apiConfiguration?.basePath ?? '';
}
private loadCurrentProfile(): Observable<void> {
return this.httpClient
.get<AccountProfile>(`${this.apiBasePath}/api/accounts/me`, {
withCredentials: true,
})
.pipe(
tap((profile) => {
this.login.next(profile.name ?? profile.email ?? '');
this.email.next(profile.email ?? '');
this.organizationName.next(profile.organization_name ?? '');
}),
map(() => undefined),
);
}
} }
@@ -1,75 +0,0 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Configuration } from '../../api';
export interface OrganizationProfile {
id: string;
name: string;
other_inst_id?: string | null;
deleted: boolean;
member_count: number;
}
export interface OrganizationPage {
items: OrganizationProfile[];
total: number;
page: number;
page_size: number;
}
export interface CreateOrganizationPayload {
name: string;
other_inst_id?: string | null;
}
export interface UpdateOrganizationPayload {
name?: string;
other_inst_id?: string | null;
deleted?: boolean;
}
@Injectable({ providedIn: 'root' })
export class OrganizationManagementService {
private readonly httpClient = inject(HttpClient);
private readonly apiConfiguration = inject(Configuration, { optional: true });
getOrganizations(page: number, pageSize: number): Observable<OrganizationPage> {
const params = new HttpParams()
.set('page', page)
.set('page_size', pageSize);
return this.httpClient.get<OrganizationPage>(
`${this.apiBasePath}/api/organizations`,
{ params },
);
}
createOrganization(
payload: CreateOrganizationPayload,
): Observable<OrganizationProfile> {
return this.httpClient.post<OrganizationProfile>(
`${this.apiBasePath}/api/organizations`,
payload,
);
}
updateOrganization(
organizationId: string,
payload: UpdateOrganizationPayload,
): Observable<OrganizationProfile> {
return this.httpClient.put<OrganizationProfile>(
`${this.apiBasePath}/api/organizations/${organizationId}`,
payload,
);
}
deleteOrganization(organizationId: string): Observable<void> {
return this.httpClient.delete<void>(
`${this.apiBasePath}/api/organizations/${organizationId}`,
);
}
private get apiBasePath(): string {
return this.apiConfiguration?.basePath ?? '';
}
}
@@ -3,7 +3,7 @@
<mat-drawer-container <mat-drawer-container
class="drawer-container" class="drawer-container"
[autosize]="!mediaQuery.matches"> [autosize]="!mediaQuery.matches">
@if (credentialService.isAuthenticated | async) { @if (credentialService.isAuthenticated()) {
<mat-drawer <mat-drawer
class="drawer" class="drawer"
[class.drawer--collapsed]="isSidebarCollapsed()" [class.drawer--collapsed]="isSidebarCollapsed()"
@@ -18,7 +18,7 @@
</mat-drawer> </mat-drawer>
} }
<mat-drawer-content class="content-shell"> <mat-drawer-content class="content-shell">
@if (credentialService.isAuthenticated | async) { @if (credentialService.isAuthenticated()) {
@if (credentialService.isImpersonating()) { @if (credentialService.isImpersonating()) {
<div class="impersonation-banner"> <div class="impersonation-banner">
<mat-icon>switch_account</mat-icon> <mat-icon>switch_account</mat-icon>
@@ -102,22 +102,20 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.mediaQuery.removeEventListener('change', this.mediaQueryListener); this.mediaQuery.removeEventListener('change', this.mediaQueryListener);
} }
logout() { async logout() {
this.credentialService.logoutAccount().subscribe({ const isImpersonating = this.credentialService.isImpersonating();
next: (result) => {
if (result === 'stopped-impersonating') { if (isImpersonating) {
this.router.navigate(['/accounts']); await this.credentialService.stopImpersonating();
} else { this.router.navigate(['/accounts']);
this.router.navigate(['/login']); } else {
} await this.credentialService.logoutAccount();
}, }
});
} }
stopImpersonating(): void { async stopImpersonating(): Promise<void> {
this.credentialService.stopImpersonating().subscribe({ await this.credentialService.stopImpersonating();
next: () => this.router.navigate(['/accounts']), this.router.navigate(['/accounts']);
});
} }
navigateBack() { navigateBack() {
@@ -105,13 +105,13 @@
<div <div
class="account-icon" class="account-icon"
[matTooltip]=" [matTooltip]="
((credentialService.login | async) || 'user') + (credentialService.login() || 'user') +
' · ' + ' · ' +
((credentialService.organizationName | async) || '') (credentialService.organizationName() || '')
" "
matTooltipPosition="right"> matTooltipPosition="right">
<div class="avatar"> <div class="avatar">
{{ (credentialService.login | async)?.charAt(0) }} {{ (credentialService.login() || 'user').charAt(0) }}
</div> </div>
</div> </div>
} @else { } @else {
@@ -119,13 +119,11 @@
<mat-card appearance="outlined" class="account-card-content"> <mat-card appearance="outlined" class="account-card-content">
<mat-card-content class="account-card"> <mat-card-content class="account-card">
<div class="avatar"> <div class="avatar">
{{ (credentialService.login | async)?.charAt(0) }} {{ (credentialService.login() || 'user').charAt(0) }}
</div> </div>
<div> <div>
<strong>{{ <strong>{{ credentialService.login() || 'Max Mustermann' }}</strong>
(credentialService.login | async) || 'Max Mustermann' <strong>{{ credentialService.organizationName() }}</strong>
}}</strong>
<strong>{{ credentialService.organizationName | async }}</strong>
</div> </div>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
@@ -70,7 +70,7 @@ export class AppMenuComponent {
icon: 'groups', icon: 'groups',
route: '/persons', route: '/persons',
queryParams: { queryParams: {
institutionName: this.credentialService.organizationName.value, institutionName: this.credentialService.organizationName(),
}, },
disabled: false, disabled: false,
}, },
@@ -142,9 +142,7 @@ export class AppMenuComponent {
label: 'Navigation', label: 'Navigation',
items: this.navItems.filter( items: this.navItems.filter(
(item) => (item) =>
!item.adminOnly && !item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly,
!item.superAdminOnly &&
!item.managerOrAdminOnly,
), ),
}, },
{ {
@@ -181,15 +179,7 @@ export class AppMenuComponent {
}); });
dialogRef.componentInstance.confirmDelete.subscribe(() => { dialogRef.componentInstance.confirmDelete.subscribe(() => {
this.credentialService.logoutAccount().subscribe({ void this.credentialService.logoutAccount();
next: (result) => {
if (result === 'stopped-impersonating') {
this.router.navigate(['/accounts']);
} else {
this.router.navigate(['/login']);
}
},
});
}); });
} }
} }
@@ -1,5 +1,12 @@
<select (change)="_handleSelectionChange($event)" [ngModel]="_urlValue()"> <mat-form-field style="width: 100%">
@for (option of options(); track $index) { @if (label()) {
<option [value]="option.value">{{ option.display_name }}</option> <mat-label>{{ label() }}</mat-label>
} }
</select> <mat-select
(selectionChange)="_handleSelectionChange($event)"
[value]="_urlValue()">
@for (option of _options(); track $index) {
<mat-option [value]="option.value">{{ option.display_name }}</mat-option>
}
</mat-select>
</mat-form-field>
@@ -1,6 +1,7 @@
import { Component, computed, inject, input, output } from '@angular/core'; import { Component, computed, inject, input, output } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatSelectChange, MatSelectModule } from '@angular/material/select';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
export type SelectorOption = { export type SelectorOption = {
@@ -10,14 +11,30 @@ export type SelectorOption = {
@Component({ @Component({
selector: 'app-query-param-selector', selector: 'app-query-param-selector',
imports: [FormsModule], imports: [FormsModule, MatSelectModule],
templateUrl: './query-param-selector.component.html', templateUrl: './query-param-selector.component.html',
styleUrl: './query-param-selector.component.scss', styleUrl: './query-param-selector.component.scss',
}) })
export class QueryParamSelectorComponent { export class QueryParamSelectorComponent {
options = input.required<SelectorOption[]>(); options = input.required<SelectorOption[]>();
queryParamKey = input.required<string>(); queryParamKey = input.required<string>();
handleSelectionChange = output<Event>(); handleSelectionChange = output<MatSelectChange>();
allowEmptyValue = input<boolean>(false);
label = input<string>('');
_options = computed<SelectorOption[]>(() => {
const options = this.options();
if (!options) {
return [];
}
if (this.allowEmptyValue()) {
return [{ value: '', display_name: '' }, ...options];
}
return options;
});
private readonly activatedRoute = inject(ActivatedRoute); private readonly activatedRoute = inject(ActivatedRoute);
private readonly router = inject(Router); private readonly router = inject(Router);
@@ -33,8 +50,8 @@ export class QueryParamSelectorComponent {
return params && key ? params[key] || '' : ''; return params && key ? params[key] || '' : '';
}); });
_handleSelectionChange(event: Event): void { _handleSelectionChange(event: MatSelectChange): void {
const newValue = (event.target as HTMLSelectElement).value; const newValue = event.value;
this.router.navigate([], { this.router.navigate([], {
queryParams: { [this.queryParamKey()]: newValue }, queryParams: { [this.queryParamKey()]: newValue },