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
from typing import Optional
from typing import Annotated, Optional
from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
from fastapi import APIRouter, Query, Response, status
from inse.auth import service as auth_service
from inse.auth.model import AccessToken
from inse.database import get_session
from inse.auth.model import AccessTokenMetadata
from inse.database import SessionDep
from inse.tags import Tags
from . import service
@@ -24,11 +23,10 @@ router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
@router.get(
"/me",
operation_id="getCurrentAccount",
response_model=AccountProfile,
)
async def get_current_account(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.get_current_account(session=session, access_token=access_token)
@@ -36,16 +34,15 @@ async def get_current_account(
@router.get(
"",
operation_id="listAccounts",
response_model=AccountPage,
)
async def list_accounts(
page: int = Query(default=0, ge=0),
page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0),
search: Optional[str] = Query(default=None),
organization_id: Optional[uuid.UUID] = Query(default=None),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
session: SessionDep,
page: Annotated[int, Query(ge=0)] = 0,
page_size: Annotated[int, Query(ge=1, le=100)] = 10,
offset: Annotated[int, Query(ge=0)] = 0,
search: Annotated[Optional[str], Query()] = None,
organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage:
return service.list_accounts(
session=session,
@@ -61,13 +58,12 @@ async def list_accounts(
@router.post(
"",
operation_id="createAccount",
response_model=AccountProfile,
status_code=status.HTTP_201_CREATED,
)
async def create_account(
payload: CreateAccountRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.create_account(
session=session,
@@ -79,11 +75,10 @@ async def create_account(
@router.get(
"/organizations",
operation_id="listAccountOrganizations",
response_model=list[OrganizationProfile],
)
async def list_organizations(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[OrganizationProfile]:
return service.list_organizations(session=session, access_token=access_token)
@@ -91,13 +86,12 @@ async def list_organizations(
@router.put(
"/{account_id}",
operation_id="updateAccount",
response_model=AccountProfile,
)
async def update_account(
account_id: uuid.UUID,
payload: UpdateAccountRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.update_account(
session=session,
@@ -114,8 +108,8 @@ async def update_account(
)
async def delete_account(
account_id: uuid.UUID,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_account(
session=session,
@@ -5,7 +5,7 @@ from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
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 (
AccountPage,
@@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
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 ""
return AccountProfile(
id=account.id,
@@ -55,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> 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:
return
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)
return _account_to_profile(account, access_token)
def list_accounts(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
page: int,
page_size: int,
offset: Optional[int] = None,
@@ -157,7 +157,7 @@ def list_accounts(
def create_account(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
payload: CreateAccountRequest,
) -> AccountProfile:
if not _is_admin(access_token.effective_role):
@@ -207,7 +207,7 @@ def create_account(
def list_organizations(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
) -> list[OrganizationProfile]:
if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec(
@@ -233,7 +233,7 @@ def list_organizations(
def update_account(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
account_id: uuid.UUID,
payload: UpdateAccountRequest,
) -> AccountProfile:
@@ -307,7 +307,7 @@ def update_account(
def delete_account(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
account_id: uuid.UUID,
) -> None:
account = _get_account_or_404(session, account_id)
+41 -31
View File
@@ -15,9 +15,9 @@ class UserRole(StrEnum):
class TokenType(StrEnum):
ID_TOKEN = "ID"
REFRESH_TOKEN = "REFRESH"
ACCESS_TOKEN = "ACCESS"
ID_TOKEN = "ID_TOKEN"
REFRESH_TOKEN = "REFRESH_TOKEN"
ACCESS_TOKEN = "ACCESS_TOKEN"
class Durable(SQLModel):
@@ -129,37 +129,20 @@ class Secret(SQLModel, table=True):
)
class Token(BaseModel):
token_type: TokenType = Field(
description="The type of the token (ID, Refresh, or Access).",
)
class BaseTokenData(BaseModel):
real_account_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the real account associated with this token.",
)
expires_at: datetime = Field(
index=True,
nullable=False,
description="The timestamp indicating when the token will expire.",
)
epoch: int = Field(
default=0,
nullable=False,
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(
default=TokenType.ID_TOKEN,
const=True,
@@ -167,24 +150,23 @@ class IdToken(Token):
)
class AccessToken(Token):
class AccessTokenMetadata(BaseTokenData):
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
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(
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.",
)
effective_role: UserRole = Field(
default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
nullable=False,
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
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(
default=TokenType.REFRESH_TOKEN,
const=True,
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):
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):
access_token: AccessToken = Field(
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 (
AccessResponse,
AccessToken,
IdToken,
AccessTokenMetadata,
IdTokenMetadata,
LoginResponse,
RefreshToken,
OtkResponse,
RefreshTokenMetadata,
)
logger = logging.getLogger(__name__)
@@ -40,7 +42,7 @@ async def request_otk(
session: SessionDep,
email: Annotated[str, Body(description="User's email address")],
password: Annotated[str, Body(description="User's password")],
):
) -> OtkResponse:
return auth_service.request_otk(session=session, email=email, password=password)
@@ -80,7 +82,7 @@ async def get_action_tokens(
effective_account_id: Annotated[
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:
logger.debug(
"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(
response: Response,
refresh_token: Annotated[
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep
],
) -> 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(
@@ -125,7 +130,7 @@ async def refresh_access_token(
async def logout(
session: Annotated[Session, Depends(get_session)],
access_token: Annotated[
AccessToken,
AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
@@ -150,7 +155,7 @@ async def change_password(
Body(description="New password", min_length=8),
],
access_token: Annotated[
AccessToken,
AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
+194 -183
View File
@@ -4,21 +4,23 @@ import json
import logging
import secrets
import uuid
from typing import Annotated, Any, Dict, Literal, Optional
from typing import Annotated, Any, Dict, Optional
import jwt
from argon2 import PasswordHasher
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 inse.auth.model import (
AccessResponse,
AccessToken,
AccessTokenMetadata,
Account,
IdToken,
IdTokenMetadata,
LoginResponse,
Organization,
RefreshToken,
OtkResponse,
RefreshTokenMetadata,
Secret,
TokenType,
UserRole,
@@ -28,9 +30,9 @@ from inse.database import get_session
from sqlmodel import Session, select, func
from inse.auth.email_service import send_email
ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days
REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes
ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes
ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
@@ -41,8 +43,11 @@ EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EPOCH_KEY = "epoch"
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()
@@ -155,7 +160,7 @@ def _verify_password(password: str, password_hash: str) -> bool:
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.
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)
if (
account is None
or account.deleted
or account.id is None
):
if account is None or account.deleted or account.id is None:
logger.warning("OTK request failed for email %s: account not found", email)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -247,7 +248,7 @@ def request_otk(session: Session, email: str, password: str):
else:
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(
@@ -331,9 +332,9 @@ def login(
def _get_current_user_access_token_payload(
session: Annotated[Session, Depends(get_session)],
request: Request,
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.
Args:
@@ -344,18 +345,22 @@ def _get_current_user_access_token_payload(
Returns:
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
access_token_payload = _verify_fp_token(
request=request,
cookie_key=ACT_FP_COOKIE_KEY,
token=token,
access_token_payload = _verify_access_token_fp(
secure_fgp=secure_fgp,
raw_access_token=token,
session=session,
)
# 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]),
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
@@ -367,15 +372,13 @@ def _get_current_user_access_token_payload(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY],
raw_token=token,
)
def _get_current_user_refresh_token_payload(
session: Annotated[Session, Depends(get_session)],
request: Request,
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
) -> RefreshToken:
token: Annotated[str | None, Cookie(alias=REFRESH_TOKEN_COOKIE_KEY)] = None,
) -> RefreshTokenMetadata:
"""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:
@@ -384,18 +387,20 @@ def _get_current_user_refresh_token_payload(
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token.
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(
request=request,
cookie_key=ACT_FP_COOKIE_KEY,
token=token,
refresh_token_payload = _verify_refresh_token(
raw_refresh_token=token,
session=session,
)
# 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]),
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
@@ -406,8 +411,6 @@ def _get_current_user_refresh_token_payload(
effective_organization_id=uuid.UUID(
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)
@@ -417,9 +420,8 @@ def _get_current_user_refresh_token_payload(
def _get_current_user_id_token_payload(
session: Annotated[Session, Depends(get_session)],
request: Request,
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
) -> IdToken:
token: Annotated[str | None, Cookie(alias=ID_TOKEN_COOKIE_KEY)] = None,
) -> IdTokenMetadata:
"""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:
@@ -430,30 +432,24 @@ def _get_current_user_id_token_payload(
Returns:
IdToken: The verified ID token payload.
"""
logger.debug(
"Verifying ID token for request %s with credentials %s",
request.url,
credentials,
)
token = credentials.credentials
logger.debug("Verifying ID token for request %s with token %s", request.url, token)
if token is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="ID token cookie is missing",
)
id_token_payload = _verify_fp_token(
request=request,
cookie_key=ID_FP_COOKIE_KEY,
token=token,
id_token_payload = _verify_id_token(
raw_id_token=token,
session=session,
)
# 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]),
expires_at=datetime.datetime.fromtimestamp(
id_token_payload["exp"], tz=datetime.timezone.utc
),
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(
response: Response,
session: Session,
id_token: IdToken,
id_token: IdTokenMetadata,
real_account_id: uuid.UUID,
effective_account_id: Optional[uuid.UUID] = None,
) -> 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.
if real_account_id != id_token.real_account_id:
@@ -616,16 +596,15 @@ def get_access_token(
if effective_account_id is None:
effective_account_id = real_account_id
elif effective_account_id != real_account_id:
if not _is_valid_impersonation(
session=session,
real_account_id=real_account_id,
effective_account_id=effective_account_id,
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Impersonation not allowed",
)
elif effective_account_id != real_account_id and not _is_valid_impersonation(
session=session,
real_account_id=real_account_id,
effective_account_id=effective_account_id,
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Impersonation not allowed",
)
role = _get_account_role(session=session, account_id=effective_account_id)
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
)
user_fingerprint_hash = _set_act_fp_cookie(response=response)
user_fingerprint_hash = _set_access_fp_cookie(response=response)
access_token = _build_access_token(
real_account_id=real_account_id,
@@ -643,77 +622,96 @@ def get_access_token(
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
)
refresh_token = _build_refresh_token(
_set_refresh_token(
response=response,
real_account_id=real_account_id,
effective_account_id=effective_account_id,
effective_role=role,
effective_organization_id=organization_id,
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
)
return AccessResponse(
access_token=access_token,
refresh_token=refresh_token,
)
def _set_id_fp_cookie(response: Response) -> str:
"""Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint.
def _set_id_token_cookie(response: Response, raw_id_token: str) -> None:
"""Sets a secure cookie for the ID token.
Args:
response (Response): The FastAPI response object to which the cookie will be added.
Returns:
str: The hashed value of the fingerprint.
raw_id_token (str): The raw string representation of the ID token.
"""
return _set_fingerprint_cookie(
response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60
_set_token_cookie(
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.
Args:
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:
str: The hashed value of the fingerprint.
"""
user_fingerprint = secrets.token_hex(50)
secure = False if settings.environment == "dev" else True
response.set_cookie(
key=key,
key=ACCESS_FP_COOKIE_KEY,
value=user_fingerprint,
httponly=True,
secure=secure,
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()
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.
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.
return _refresh_access_token(
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.
user_fingerprint_hash = _set_access_fp_cookie(response=response)
return _build_access_token(
real_account_id=refresh_token.real_account_id,
@@ -752,7 +732,7 @@ def _refresh_access_token(
effective_role=refresh_token.effective_role,
effective_organization_id=refresh_token.effective_organization_id,
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,
real_account_id: uuid.UUID,
epoch: int,
) -> IdToken:
) -> IdTokenMetadata:
"""Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie.
Args:
@@ -775,34 +755,31 @@ def _build_id_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=ID_TOKEN_EXPIRATION_MINUTES
)
user_fingerprint_hash = _set_id_fp_cookie(response)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
}
raw_token = _build_token(
payload=payload,
expiration_datetime=expires_at,
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,
expires_at=expires_at,
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,
effective_account_id: uuid.UUID,
effective_role: UserRole,
effective_organization_id: uuid.UUID,
epoch: int,
user_fingerprint_hash: str,
) -> RefreshToken:
) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
Args:
@@ -815,7 +792,7 @@ def _build_refresh_token(
user_fingerprint_hash (str): The hashed value of the user's fingerprint.
Returns:
RefreshToken: The generated refresh token object.
RefreshTokenMetadata: The generated refresh token object.
"""
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
@@ -826,7 +803,6 @@ def _build_refresh_token(
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
}
raw_token = _build_token(
@@ -834,16 +810,14 @@ def _build_refresh_token(
expiration_datetime=expires_at,
token_type=TokenType.REFRESH_TOKEN,
)
return RefreshToken(
_set_refresh_token_cookie(response=response, raw_refresh_token=raw_token)
return RefreshTokenMetadata(
real_account_id=real_account_id,
effective_account_id=effective_account_id,
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
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
def _verify_fp_token(
request: Request,
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.
def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
"""Verifies the provided ID token and returns the decoded payload if valid.
Args:
request (Request): The FastAPI request object containing the cookies.
cookie_key (str): The name of the cookie that contains the fingerprint.
token (str): The JWT token to verify.
raw_id_token (str): The JWT ID 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 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:
ValueError: If the token HMAC key is not set in the configuration.
@@ -953,19 +966,29 @@ def _verify_fp_token(
Returns:
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")
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:
payload = jwt.decode(
token,
@@ -974,23 +997,12 @@ def _verify_fp_token(
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)
if not real_account_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token missing real account ID",
)
epoch_account_id = uuid.UUID(real_account_id)
effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY)
@@ -1013,7 +1025,6 @@ def _verify_fp_token(
)
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -1055,7 +1066,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> 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.
Args:
@@ -1079,7 +1090,7 @@ def logout(session: Session, access_token: AccessToken) -> Dict[str, str]:
def change_password(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
current_password: str,
new_password: str,
) -> Dict[str, str]:
+118 -111
View File
@@ -14,9 +14,10 @@ from inse.auth.model import (
Account,
Organization,
Secret,
IdToken,
AccessToken,
RefreshToken,
IdTokenMetadata,
AccessTokenMetadata,
RefreshTokenMetadata,
UserRole,
)
@@ -61,6 +62,19 @@ def create_org_and_account(
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():
pw = "s3cret-password"
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
resp = auth_service.request_otk(in_memory_session, email, password)
assert resp["status"] == "ok"
assert resp["account_id"] == str(acc.id)
assert resp.status == "success"
assert resp.account_id == acc.id
secret = in_memory_session.exec(
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(
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.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):
@@ -108,35 +125,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
assert isinstance(id_token, IdToken)
secure_fgp_hash = auth_service._set_access_fp_cookie(response)
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
for header, value in response.headers.items():
if header.lower() == "set-cookie":
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,
payload = auth_service._verify_access_token_fp(
secure_fgp=secure_fgp,
raw_access_token=access_token.raw_token,
session=in_memory_session,
)
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
with pytest.raises(Exception):
auth_service._verify_fp_token(
request=DummyReq({}),
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
auth_service._verify_access_token_fp(
secure_fgp="bad-fingerprint",
raw_access_token=access_token.raw_token,
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(
response, in_memory_session, id_token, acc.id
)
assert isinstance(access_response.access_token, AccessToken)
assert isinstance(access_response.refresh_token, RefreshToken)
assert isinstance(access_response.access_token, AccessTokenMetadata)
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
assert isinstance(refreshed, AccessToken)
raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
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
@@ -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.commit()
assert account.id is not None
with pytest.raises(HTTPException) as error:
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
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
cookie_header = None
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
secure_fgp_hash = 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_hash,
)
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
auth_service._verify_access_token_fp(
secure_fgp="badcookie",
raw_access_token=access_token.raw_token,
session=in_memory_session,
)
@@ -300,28 +327,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup):
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
cookie_header = None
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
secure_fgp_hash = auth_service._set_access_fp_cookie(response)
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,
)
acc.epoch += 1
in_memory_session.add(acc)
in_memory_session.commit()
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
auth_service._verify_access_token_fp(
secure_fgp=secure_fgp,
raw_access_token=access_token.raw_token,
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
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
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"
bad_token = access_token.raw_token + "x"
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=bad_token,
auth_service._verify_access_token_fp(
secure_fgp=secure_fgp,
raw_access_token=bad_token,
session=in_memory_session,
)
@@ -391,7 +411,7 @@ def test_impersonation_rules(in_memory_session, settings_backup):
real_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):
@@ -425,7 +445,7 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
login_res = auth_service.login(
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):
@@ -461,7 +481,7 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup):
assert acc.id is not None
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(
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_organization_id=acc.organization_id,
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):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
token=access_token.raw_token,
auth_service._verify_access_token_fp(
secure_fgp="wrongcookie",
raw_access_token=access_token.raw_token,
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
response = Response()
cookie_raw = auth_service._set_id_fp_cookie(response)
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
payload = {
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.USER_FINGERPRINT_HASH_KEY: cookie_raw,
auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash,
}
bad_token = auth_service._build_token(
payload=payload,
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):
auth_service._verify_fp_token(
request=DummyReq(
{
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,
auth_service._verify_access_token_fp(
secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY),
raw_access_token=bad_token,
session=in_memory_session,
)
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
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.tags import Tags
@@ -26,7 +26,7 @@ async def get_organizations(
page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationPage:
return service.get_organizations(
session=session,
@@ -46,7 +46,7 @@ async def get_organizations(
async def create_organization(
payload: CreateOrganizationRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile:
return service.create_organization(session, access_token, payload)
@@ -60,7 +60,7 @@ async def update_organization(
organization_id: uuid.UUID,
payload: UpdateOrganizationRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile:
return service.update_organization(
session, access_token, organization_id, payload
@@ -75,7 +75,7 @@ async def update_organization(
async def delete_organization(
organization_id: uuid.UUID,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_organization(session, access_token, organization_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -4,7 +4,7 @@ from typing import Optional
from fastapi import HTTPException, status
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 (
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:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
@@ -109,7 +109,7 @@ def _deactivate_organization_accounts(
def get_organizations(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
page: int,
page_size: int,
offset: Optional[int] = None,
@@ -145,7 +145,7 @@ def get_organizations(
def create_organization(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
payload: CreateOrganizationRequest,
) -> OrganizationProfile:
_require_super_admin(access_token)
@@ -164,7 +164,7 @@ def create_organization(
def update_organization(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
organization_id: uuid.UUID,
payload: UpdateOrganizationRequest,
) -> OrganizationProfile:
@@ -191,7 +191,7 @@ def update_organization(
def delete_organization(
session: Session,
access_token: AccessToken,
access_token: AccessTokenMetadata,
organization_id: uuid.UUID,
) -> None:
_require_super_admin(access_token)
+2 -2
View File
@@ -113,7 +113,7 @@ model/hEUReportSummary.ts
model/hEUTopic.ts
model/hEUWebLink.ts
model/hTTPValidationError.ts
model/idToken.ts
model/idTokenMetadata.ts
model/inseAccountManagementModelOrganizationProfile.ts
model/inseOrganizationManagementModelOrganizationProfile.ts
model/institution.ts
@@ -149,6 +149,7 @@ model/openAccess.ts
model/orgPatentEntry.ts
model/orgPatentsResponse.ts
model/organizationPage.ts
model/otkResponse.ts
model/patentEntry.ts
model/patentsByAuthorResponse.ts
model/patentsByInstitutionResponse.ts
@@ -160,7 +161,6 @@ model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts
model/publicationsByAuthorResponse.ts
model/rankingResponse.ts
model/refreshToken.ts
model/score.ts
model/sortDirection.ts
model/tokenType.ts
+1 -16
View File
@@ -26,19 +26,4 @@ export * from './topics.service';
import { TopicsService } from './topics.service';
export * from './works.service';
import { WorksService } from './works.service';
export const APIS = [
AuthService,
CompanyConnectionsService,
FundingService,
INSEServiceService,
InstitutionsService,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonNetworkService,
PersonsService,
ProjectsService,
TopicsService,
WorksService,
];
export const APIS = [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
import { LoginResponse } from '../model/loginResponse';
// @ts-ignore
import { OtkResponse } from '../model/otkResponse';
// @ts-ignore
import { UpdateAccountRequest } from '../model/updateAccountRequest';
// @ts-ignore
@@ -64,13 +66,14 @@ export class AuthService extends BaseService {
* Change the user\'s password and invalidate existing tokens.
* @endpoint post /api/auth/v2/change-password
* @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 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, 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, observe: any = 'body', reportProgress: boolean = false, 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, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<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, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyChangePassword === null || bodyChangePassword === undefined) {
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
}
@@ -132,13 +135,14 @@ export class AuthService extends BaseService {
* Create Account
* @endpoint post /api/accounts
* @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 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, 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, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
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) {
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
}
@@ -200,13 +204,14 @@ export class AuthService extends BaseService {
* Delete Account
* @endpoint delete /api/accounts/{account_id}
* @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 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, 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, observe: any = 'body', reportProgress: boolean = false, 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, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<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, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (accountId === null || accountId === undefined) {
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.
* @endpoint post /api/auth/v2/access
* @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 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, 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, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
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) {
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
@@ -326,13 +329,14 @@ export class AuthService extends BaseService {
/**
* Get Current Account
* @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 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(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(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
@@ -431,13 +435,14 @@ export class AuthService extends BaseService {
/**
* List 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 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(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(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
@@ -490,13 +495,14 @@ export class AuthService extends BaseService {
* @param offset
* @param search
* @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 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, 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, 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?: '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?: '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?: '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: 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,
@@ -624,13 +630,14 @@ export class AuthService extends BaseService {
* Logout
* Logout the authenticated user.
* @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 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(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(observe: any = 'body', reportProgress: boolean = false, 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(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<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;
@@ -679,19 +686,17 @@ export class AuthService extends BaseService {
* Refresh Access Token
* Refresh the access token using a valid refresh token.
* @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 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(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(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'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 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?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<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<OtkResponse>>;
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> {
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
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`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
return this.httpClient.request<OtkResponse>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyRequestOtk,
@@ -801,13 +806,14 @@ export class AuthService extends BaseService {
* @endpoint put /api/accounts/{account_id}
* @param accountId
* @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 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, 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, 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?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
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) {
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
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,355 +9,205 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
providedIn: 'root'
})
export class INSEServiceService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* 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> {
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,
);
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
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';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarHeaders = this.defaultHeaders;
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,
},
);
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
/**
* 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 localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (topic) {
topic.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'topic',
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/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 =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (topic) {
topic.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic');
})
}
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';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
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
}
);
}
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
* @endpoint post /api/organizations
* @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 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, 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, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
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) {
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
}
@@ -115,13 +116,14 @@ export class OrganizationService extends BaseService {
* Delete Organization
* @endpoint delete /api/organizations/{organization_id}
* @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 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, 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, observe: any = 'body', reportProgress: boolean = false, 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, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<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, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (organizationId === null || organizationId === undefined) {
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 pageSize
* @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 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, 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, 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?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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, 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, 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});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -240,13 +243,14 @@ export class OrganizationService extends BaseService {
* @endpoint put /api/organizations/{organization_id}
* @param organizationId
* @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 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, 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, 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?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
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) {
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
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,18 +9,12 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AllPatentsResponse } from '../model/allPatentsResponse';
@@ -36,657 +30,338 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
providedIn: 'root'
})
export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* 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> {
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,
);
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
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';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
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`;
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;
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,
},
);
}
/**
* Get pre-indexed org patents for an institution.
* @endpoint get /api/inse-service/institutions/{id}/org-patents
* @param id
* @param matchType Filter patents by match type.
* @param page
* @param size
* @param source
* @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 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>;
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>>;
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> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getOrgPatentsByInstitution.');
}
/**
* Get pre-indexed org patents for an institution.
* @endpoint get /api/inse-service/institutions/{id}/org-patents
* @param id
* @param matchType Filter patents by match type.
* @param page
* @param size
* @param source
* @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 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>;
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>>;
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> {
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(localVarQueryParameters,
<any>matchType, 'match_type');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>source, 'source');
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})}/org-patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<OrgPatentsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>matchType,
'match_type',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>size,
'size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>source,
'source',
);
/**
* Returns one publication by OpenAlex ID or DOI.
* @endpoint get /api/inse-service/patents/{identifier}
* @param identifier
* @param prefix Application Prefix (EP or US)
* @param title Do we want to fallback to title search if ID and DOI dont work?
* @param fillingDate Filling date in YYYY-MM-DD format
* @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 getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
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>>;
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 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 =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'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/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';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
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
}
);
}
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;
return this.httpClient.request<OrgPatentsResponse>(
'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 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.');
}
/**
* Returns one publication by OpenAlex ID or DOI.
* @endpoint get /api/inse-service/patents/{identifier}
* @param identifier
* @param prefix Application Prefix (EP or US)
* @param title Do we want to fallback to title search if ID and DOI dont work?
* @param fillingDate Filling date in YYYY-MM-DD format
* @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 getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
fillingDate?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentEntry>;
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>>;
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 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
}
);
}
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 {
HttpHeaders,
HttpParams,
HttpParameterCodec,
} from '@angular/common/http';
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';
export interface ConfigurationParameters {
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: { [key: string]: string };
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* 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>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials?: { [key: string]: string | (() => string | undefined) };
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* 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>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials?: {[ key: string ]: string | (() => string | undefined)};
}
export class Configuration {
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: { [key: string]: string };
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials: { [key: string]: string | (() => string | undefined) };
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials: {[ key: string ]: string | (() => string | undefined)};
constructor({
accessToken,
apiKeys,
basePath,
credentials,
encodeParam,
encoder,
password,
username,
withCredentials,
}: ConfigurationParameters = {}) {
if (apiKeys) {
this.apiKeys = apiKeys;
}
if (username !== undefined) {
this.username = username;
}
if (password !== undefined) {
this.password = password;
}
if (accessToken !== undefined) {
this.accessToken = accessToken;
}
if (basePath !== undefined) {
this.basePath = basePath;
}
if (withCredentials !== undefined) {
this.withCredentials = withCredentials;
}
if (encoder) {
this.encoder = encoder;
}
this.encodeParam =
encodeParam ?? ((param) => this.defaultEncodeParam(param));
this.credentials = credentials ?? {};
constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) {
if (apiKeys) {
this.apiKeys = apiKeys;
}
if (username !== undefined) {
this.username = username;
}
if (password !== undefined) {
this.password = password;
}
if (accessToken !== undefined) {
this.accessToken = accessToken;
}
if (basePath !== undefined) {
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
if (!this.credentials['HTTPBearer']) {
this.credentials['HTTPBearer'] = () => {
return typeof this.accessToken === 'function'
? 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;
// init default HTTPBearer credential
if (!this.credentials['HTTPBearer']) {
this.credentials['HTTPBearer'] = () => {
return typeof this.accessToken === 'function'
? this.accessToken()
: this.accessToken;
};
}
}
const type = contentTypes.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
/**
* 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;
}
/**
* Select the correct accept content-type to use for a request.
* 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 = contentTypes.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
/**
* Select the correct accept content-type to use for a request.
* 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.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp(
'^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$',
'i',
);
return (
mime !== null &&
(jsonMime.test(mime) ||
mime.toLowerCase() === 'application/json-patch+json')
);
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
public lookupCredential(key: string): string | undefined {
const value = this.credentials[key];
return typeof value === 'function' ? value() : value;
}
public lookupCredential(key: string): string | undefined {
const value = this.credentials[key];
return typeof value === 'function'
? value()
: value;
}
public addCredentialToHeaders(
credentialKey: string,
headerName: string,
headers: HttpHeaders,
prefix?: string,
): HttpHeaders {
const value = this.lookupCredential(credentialKey);
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
}
public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders {
const value = this.lookupCredential(credentialKey);
return value
? headers.set(headerName, (prefix ?? '') + value)
: headers;
}
public addCredentialToQuery(
credentialKey: string,
paramName: string,
query: HttpParams,
): HttpParams {
const value = this.lookupCredential(credentialKey);
return value ? query.set(paramName, value) : query;
}
public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
const value = this.lookupCredential(credentialKey);
return value
? query.set(paramName, value)
: query;
}
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// 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!
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// 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!
const value =
param.dataFormat === 'date-time' && param.value instanceof Date
? (param.value as Date).toISOString()
: param.value;
const value = param.dataFormat === 'date-time' && param.value instanceof Date
? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value));
}
return encodeURIComponent(String(value));
}
}
@@ -7,7 +7,6 @@
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { RefreshToken } from './refreshToken';
import { AccessToken } from './accessToken';
@@ -16,9 +15,5 @@ export interface AccessResponse {
* The access token issued upon successful authentication.
*/
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 {
/**
* 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.
*/
@@ -29,13 +25,13 @@ export interface AccessToken {
*/
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;
/**
* 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.
*/
@@ -48,6 +44,10 @@ export interface AccessToken {
* The unique identifier of the organization associated with this access token.
*/
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 {
}
@@ -26,3 +26,4 @@ export interface AccountProfile {
export namespace AccountProfile {
}
+12 -10
View File
@@ -1,20 +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 BodyRequestOtk {
/**
* User\'s email address
*/
email: string;
/**
* User\'s password
*/
password: string;
export interface BodyRequestOtk {
/**
* User\'s email address
*/
email: string;
/**
* User\'s password
*/
password: string;
}
@@ -1,14 +1,16 @@
/**
* 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 CreateOrganizationRequest {
name: string;
other_inst_id?: string | null;
export interface CreateOrganizationRequest {
name: string;
other_inst_id?: string | null;
}
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -10,17 +10,19 @@
import { ExtractedKeywordsLLM } from './extractedKeywordsLLM';
import { ExtractedKeywords } from './extractedKeywords';
export interface ExtractedKeywordsResponse {
results_llm?: ExtractedKeywordsLLM | null;
results?: ExtractedKeywords | null;
/**
* The source of the input text, e.g., \'url\', \'text\', or \'keywords\'.
*/
source: string;
source_url?: string | null;
/**
* The actual content from which keywords were extracted.
*/
source_content: string;
duration?: number | null;
export interface ExtractedKeywordsResponse {
results_llm?: ExtractedKeywordsLLM | null;
results?: ExtractedKeywords | null;
/**
* The source of the input text, e.g., \'url\', \'text\', or \'keywords\'.
*/
source: string;
source_url?: string | null;
/**
* The actual content from which keywords were extracted.
*/
source_content: string;
duration?: number | null;
}
@@ -10,11 +10,7 @@
import { TokenType } from './tokenType';
export interface IdToken {
/**
* The type of the token, which is always ID_TOKEN for this class.
*/
token_type?: TokenType;
export interface IdTokenMetadata {
/**
* The unique identifier of the real account associated with this token.
*/
@@ -28,15 +24,11 @@ export interface IdToken {
*/
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;
/**
* The raw token string.
*/
raw_token: string;
token_type?: TokenType;
}
export namespace IdToken {
export namespace IdTokenMetadata {
}
@@ -1,15 +1,17 @@
/**
* 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 InseAccountManagementModelOrganizationProfile {
id: string;
name: string;
openalex_institution_id?: string | null;
export interface InseAccountManagementModelOrganizationProfile {
id: string;
name: string;
openalex_institution_id?: string | null;
}
@@ -1,17 +1,19 @@
/**
* 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 InseOrganizationManagementModelOrganizationProfile {
id: string;
name: string;
other_inst_id?: string | null;
deleted: boolean;
member_count: number;
export interface InseOrganizationManagementModelOrganizationProfile {
id: string;
name: string;
other_inst_id?: string | null;
deleted: boolean;
member_count: number;
}
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,7 +9,9 @@
*/
import { Topic } from './topic';
export interface KeywordTopicMatch {
keyword: string;
topic?: Topic | null;
export interface KeywordTopicMatch {
keyword: string;
topic?: Topic | null;
}
@@ -1,16 +1,18 @@
/**
* 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 KeywordsTopicsRequest {
/**
* List of keywords/sentences to query by similarity.
*/
keywords: Array<string>;
export interface KeywordsTopicsRequest {
/**
* List of keywords/sentences to query by similarity.
*/
keywords: Array<string>;
}
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,9 +9,11 @@
*/
import { KeywordTopicMatch } from './keywordTopicMatch';
export interface KeywordsTopicsResponse {
/**
* Top matching topics for each keyword in the requested list.
*/
results: Array<KeywordTopicMatch>;
export interface KeywordsTopicsResponse {
/**
* Top matching topics for each keyword in the requested list.
*/
results: Array<KeywordTopicMatch>;
}
+9 -7
View File
@@ -1,17 +1,19 @@
/**
* 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 { IdToken } from './idToken';
import { IdTokenMetadata } from './idTokenMetadata';
export interface LoginResponse {
/**
* The ID token issued upon successful login.
*/
id_token: IdToken;
export interface LoginResponse {
/**
* The ID token issued upon successful login.
*/
id_token: IdTokenMetadata;
}
+6 -4
View File
@@ -1,14 +1,16 @@
/**
* 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 MatchedAuthor {
openalex_author_id: string;
author_name: string;
export interface MatchedAuthor {
openalex_author_id: string;
author_name: string;
}
+2 -2
View File
@@ -89,7 +89,7 @@ export * from './hEUReportSummary';
export * from './hEUTopic';
export * from './hEUWebLink';
export * from './hTTPValidationError';
export * from './idToken';
export * from './idTokenMetadata';
export * from './inseAccountManagementModelOrganizationProfile';
export * from './inseOrganizationManagementModelOrganizationProfile';
export * from './institution';
@@ -124,6 +124,7 @@ export * from './openAccess';
export * from './orgPatentEntry';
export * from './orgPatentsResponse';
export * from './organizationPage';
export * from './otkResponse';
export * from './patentEntry';
export * from './patentsByAuthorResponse';
export * from './patentsByInstitutionResponse';
@@ -135,7 +136,6 @@ export * from './publicationDetailByFunder';
export * from './publicationIdsByAuthorPosition';
export * from './publicationsByAuthorResponse';
export * from './rankingResponse';
export * from './refreshToken';
export * from './score';
export * from './sortDirection';
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 = {
Id: 'ID',
Refresh: 'REFRESH',
Access: 'ACCESS'
IdToken: 'ID_TOKEN',
RefreshToken: 'REFRESH_TOKEN',
AccessToken: 'ACCESS_TOKEN'
} as const;
export type TokenType = typeof TokenType[keyof typeof TokenType];
@@ -23,3 +23,4 @@ export interface UpdateAccountRequest {
export namespace UpdateAccountRequest {
}
@@ -1,15 +1,17 @@
/**
* 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 UpdateOrganizationRequest {
name?: string | null;
other_inst_id?: string | null;
deleted?: boolean | null;
export interface UpdateOrganizationRequest {
name?: string | null;
other_inst_id?: string | null;
deleted?: boolean | null;
}
+2
View File
@@ -5,6 +5,7 @@ import {
Router,
withComponentInputBinding,
withNavigationErrorHandler,
withRouterConfig,
} from '@angular/router';
import { routes } from './app.routes';
@@ -37,6 +38,7 @@ export const appConfig: ApplicationConfig = {
provideRouter(
routes,
withComponentInputBinding(),
withRouterConfig({ onSameUrlNavigation: 'reload' }),
withNavigationErrorHandler((navigationError: NavigationError) => {
const router = inject(Router);
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 { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
import { personNewsResolver } from './resolvers/person-news.resolver';
import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.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 { accountResolver } from './resolvers/account.resolver';
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 = [
{
@@ -114,6 +116,11 @@ export const routes: Routes = [
import('./modules/accounts/accounts.component').then(
(mod) => mod.AccountsComponent,
),
resolve: {
accountPage: accountsPageResolver,
organizations: accountsOrganizationResolver,
},
runGuardsAndResolvers: 'always',
},
{
path: 'organizations',
@@ -122,7 +129,12 @@ export const routes: Routes = [
import('./modules/organizations/organizations.component').then(
(mod) => mod.OrganizationsComponent,
),
resolve: {
organizationPage: organizationsOrganizationsResolver,
},
runGuardsAndResolvers: 'always',
},
{
path: 'news/:id',
canActivate: [userGuard],
@@ -145,18 +145,19 @@ export class AccountComponent {
if (!oldPassword || !newPassword) {
return;
}
this._credentialService
.changePassword(oldPassword, newPassword)
.subscribe({
error: (error) => {
console.error('Error changing password:', error);
this._snackBar.open(
'Das alte Passwort ist nicht korrekt. Bitte versuchen Sie es erneut.',
'OK',
{ duration: 7000 },
);
},
});
try {
await this._credentialService.changePassword(
oldPassword,
newPassword,
);
} catch (error) {
console.error('Error changing password:', error);
this._snackBar.open(
'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 { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import type {
AccountPayload,
import {
AccountProfile,
AccountRole,
CreateAccountPayload,
OrganizationProfile,
} from '../../shared/services/account-management.service';
InseAccountManagementModelOrganizationProfile,
UserRole,
} from '../../api';
export type AccountDialogMode = 'create' | 'edit';
export interface AccountDialogData {
mode: AccountDialogMode;
account?: AccountProfile;
organizations: OrganizationProfile[];
organizations: InseAccountManagementModelOrganizationProfile[];
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 =
@@ -69,7 +85,7 @@ export class AccountDialogComponent {
name: new FormControl<string>(this.data.account?.name ?? '', [
Validators.required,
]),
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [
role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
Validators.required,
]),
organizationId: new FormControl<string>(
@@ -148,6 +164,6 @@ export class AccountDialogComponent {
}
protected close(): void {
this.dialogRef.close(undefined);
this.dialogRef.close();
}
}
@@ -23,189 +23,73 @@
}
</header>
<form class="filters" [formGroup]="filterForm" (ngSubmit)="applyFilters()">
<mat-form-field appearance="outline">
<mat-label>Name oder E-Mail</mat-label>
<input matInput formControlName="search" />
</mat-form-field>
@if (credentialService.isEffectiveSuperAdmin()) {
<mat-form-field appearance="outline">
<mat-label>Organisation</mat-label>
<mat-select formControlName="organizationId">
<mat-option value="">Alle Organisationen</mat-option>
@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 style="display: flex; gap: 1rem; align-items: center">
<app-query-param-input
queryParamKey="search"
label="Nach Name oder E-Mail suchen"
style="width: 35%" />
<app-query-param-selector
queryParamKey="organization_id"
[options]="selectorOptions()"
label="Organisation"
[allowEmptyValue]="true"
style="width: 25%" />
</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>
<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;
}
}
mat-card,
mat-paginator {
background-color: var(--sg-background);
}
@@ -1,6 +1,14 @@
import { CommonModule } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import {
Component,
OnInit,
TemplateRef,
computed,
inject,
input,
viewChild,
} from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
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 { MatDialog, MatDialogModule } from '@angular/material/dialog';
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 type {
AccountDialogComponent,
AccountDialogResult,
} from './account-dialog.component';
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({
selector: 'app-accounts',
@@ -38,95 +59,92 @@ import { RolePipe } from '../../shared/pipes/role.pipe';
MatTooltipModule,
MatDialogModule,
RolePipe,
DataTableComponent,
QueryParamPaginatorComponent,
QueryParamInputComponent,
QueryParamSelectorComponent,
MatCardModule,
StatusPipe
],
templateUrl: './accounts.component.html',
styleUrl: './accounts.component.scss',
standalone: true,
})
export class AccountsComponent implements OnInit {
private readonly accountService = inject(AccountManagementService);
protected readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar);
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
private readonly authService = inject(AuthService);
protected get isReadOnly(): boolean {
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()) {
return ['SUPER_ADMIN', 'ADMIN', '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 {
if (!this.isReadOnly) {
this.loadOrganizations();
}
this.loadAccounts();
}
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;
this.accountColumns = [
{
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'name',
},
error: () => {
this.snackBar.open(
'Organisationen konnten nicht geladen werden.',
'OK',
{ duration: 5000 },
);
{
id: 'email',
header: 'E-Mail',
type: 'accessor',
accessorKey: 'email',
},
});
}
protected applyFilters(): void {
this.loadAccounts(0);
}
protected resetFilters(): void {
this.filterForm.reset({ search: '', organizationId: '' });
this.loadAccounts(0);
{
id: 'organization_name',
header: 'Organisation',
type: 'accessor',
accessorKey: 'organization_name',
},
{
id: 'role',
header: 'Rolle',
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 {
@@ -140,15 +158,18 @@ export class AccountsComponent implements OnInit {
private saveDialogResult(result: AccountDialogResult): void {
const request =
result.mode === 'create'
? this.accountService.createAccount(result.payload)
: this.accountService.updateAccount(result.accountId, result.payload);
? this.authService.createAccount(result.payload)
: this.authService.updateAccount(result.accountId, result.payload);
request.subscribe({
next: () => {
this.snackBar.open('Account wurde gespeichert.', 'OK', {
duration: 3000,
});
this.loadAccounts(0);
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: (error) => {
const message =
@@ -170,9 +191,9 @@ export class AccountsComponent implements OnInit {
{
mode: 'create' | 'edit';
account?: AccountProfile;
organizations: OrganizationProfile[];
organizations: InseAccountManagementModelOrganizationProfile[];
canSelectOrganization: boolean;
roles: AccountRole[];
roles: UserRole[];
},
AccountDialogResult | undefined
>(AccountDialogComponent, {
@@ -180,9 +201,9 @@ export class AccountsComponent implements OnInit {
maxWidth: 'calc(100vw - 32px)',
data: {
...data,
organizations: this.organizations,
organizations: this.organizations(),
canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(),
roles: this.availableRoles,
roles: this.availableRoles(),
},
});
@@ -199,12 +220,15 @@ export class AccountsComponent implements OnInit {
return;
}
this.accountService.deleteAccount(account.id).subscribe({
this.authService.deleteAccount(account.id).subscribe({
next: () => {
this.snackBar.open('Account wurde deaktiviert.', 'OK', {
duration: 3000,
});
this.loadAccounts();
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: () => {
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
@@ -248,14 +272,17 @@ export class AccountsComponent implements OnInit {
account: AccountProfile,
activated: boolean,
): void {
this.accountService.updateAccount(account.id, { activated }).subscribe({
this.authService.updateAccount(account.id, { activated }).subscribe({
next: () => {
this.snackBar.open(
activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.',
'OK',
{ duration: 3000 },
);
this.loadAccounts();
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: () => {
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)) {
return;
}
this.credentialService.impersonateAccount(account.id).subscribe({
next: () => {
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
duration: 4000,
});
this.router.navigate(['/dashboard']);
},
error: () => {
this.snackBar.open(
'Impersonation konnte nicht gestartet werden.',
'OK',
{
duration: 5000,
},
);
},
});
}
protected get canPageBack(): boolean {
return this.page > 0;
}
protected get canPageForward(): boolean {
return (this.page + 1) * this.pageSize < this.total;
try {
await this.credentialService.impersonateAccount(account.id);
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
duration: 4000,
});
this.router.navigate(['/dashboard']);
} catch (error) {
console.error('Impersonation failed:', error);
this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', {
duration: 5000,
});
return;
}
}
protected canImpersonate(account: AccountProfile): boolean {
@@ -1,4 +1,4 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Component, effect, OnDestroy } from '@angular/core';
import {
FormControl,
FormGroup,
@@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input';
import { CredentialService } from '../../shared/services/credential.service';
import { MatIconModule } from '@angular/material/icon';
import { CommonModule } from '@angular/common';
import { finalize, Subscription } from 'rxjs';
import { Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
@@ -34,7 +34,7 @@ type LoginStep = 'credentials' | 'otk';
styleUrl: './app-login.component.scss',
standalone: true,
})
export class AppLoginComponent implements OnInit, OnDestroy {
export class AppLoginComponent implements OnDestroy {
credentialsForm = new FormGroup({
email: new FormControl<string>('', [Validators.required, Validators.email]),
password: new FormControl<string>('', [
@@ -64,28 +64,21 @@ export class AppLoginComponent implements OnInit, OnDestroy {
protected credentialService: CredentialService,
protected router: Router,
protected snackBar: MatSnackBar,
) {}
ngOnInit(): void {
this.subscription = this.credentialService.validating.subscribe(
(validating) => {
if (validating) {
this.credentialsForm.disable();
this.otkForm.disable();
} else {
this.credentialsForm.enable();
this.otkForm.enable();
this.checkEnter();
}
},
);
if (!this.credentialService.validating.value) {
this.checkEnter();
}
) {
effect(() => {
if (this.credentialService.isValidating()) {
this.credentialsForm.disable();
this.otkForm.disable();
} else {
this.credentialsForm.enable();
this.otkForm.enable();
this.checkEnter();
}
});
}
checkEnter(): void {
if (this.credentialService.isAuthenticated.value) {
if (this.credentialService.isAuthenticated()) {
this.router.navigate(['/dashboard']);
}
}
@@ -110,39 +103,35 @@ export class AppLoginComponent implements OnInit, OnDestroy {
const email = this.credentialsForm.controls.email.value ?? '';
const password = this.credentialsForm.controls.password.value ?? '';
this.credentialService
.requestOtk(email, password)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.credentialsForm.enable();
}),
)
.subscribe({
next: (accountId) => {
if (!accountId) {
return;
}
this.accountId = accountId;
this.currentStep = 'otk';
this.otkForm.reset();
this.startCountdown();
this.snackBar.open(
'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', {
this.credentialService.requestOtk(email, password).subscribe({
next: (otkResponse) => {
const accountId = otkResponse.account_id;
this.accountId = accountId;
this.currentStep = 'otk';
this.otkForm.reset();
this.startCountdown();
this.snackBar.open(
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
'OK',
{
duration: 4000,
},
);
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
});
},
});
},
);
},
complete: () => {
this.isSubmitting = false;
this.credentialsForm.enable();
},
});
}
resendCode() {
@@ -178,29 +167,32 @@ export class AppLoginComponent implements OnInit, OnDestroy {
this.isSubmitting = true;
this.otkForm.disable();
const email = this.credentialsForm.controls.email.value ?? '';
const code = this.otkForm.controls.code.value ?? '';
this.credentialService
.loginWithOtk(this.accountId, email, code)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.otkForm.enable();
}),
)
.subscribe({
next: () => {
this.stopCountdown();
this.router.navigate(['/dashboard']);
},
error: (error: HttpErrorResponse) => {
this.credentialService.clearLocalAuthState();
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
this.credentialService.loginWithOtk(this.accountId, code).subscribe({
next: () => {
this.credentialService.reauthenticateViaIdToken().subscribe({
next: () => {
this.checkEnter();
this.stopCountdown();
this.router.navigate(['/dashboard']);
},
});
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
});
},
});
},
);
},
complete: () => {
this.isSubmitting = false;
this.otkForm.enable();
},
});
}
editCredentials() {
@@ -240,6 +232,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
}
private getLoginErrorMessage(error: HttpErrorResponse): string {
console.error('Login error:', error);
if (error.status === 401) {
return 'E-Mail, Passwort oder OTK-Code ist ungültig.';
}
@@ -84,9 +84,7 @@
mat-raised-button
class="button"
(click)="submit()"
[disabled]="
!registerForm.valid || (credentialService.validating | async)
">
[disabled]="!registerForm.valid || credentialService.isValidating()">
Registrieren
</button>
@@ -4,7 +4,7 @@ import {
OnDestroy,
signal,
DestroyRef,
OnInit,
effect,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@@ -54,7 +54,7 @@ import { InstitutionsService } from '../../api';
templateUrl: './app-register.component.html',
styleUrl: './app-register.component.scss',
})
export class AppRegisterComponent implements OnDestroy, OnInit {
export class AppRegisterComponent implements OnDestroy {
private readonly fb = inject(FormBuilder);
protected readonly credentialService = inject(CredentialService);
private readonly router = inject(Router);
@@ -73,42 +73,37 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
showPassword = false;
constructor() {
effect(() => {
if (this.credentialService.isValidating()) {
this.registerForm.disable();
} else {
this.registerForm.enable();
this.checkEnter();
}
});
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 {
this.subscription?.unsubscribe();
}
checkEnter(): void {
if (this.credentialService.isAuthenticated.value) {
if (this.credentialService.isAuthenticated()) {
this.router.navigate(['/dashboard']);
}
}
submit() {
if (this.registerForm.valid) {
this.credentialService.validating.next(true);
this.credentialService.isValidating.set(true);
this.registerForm.disable();
this.subscription = this.credentialService
.registerAccount(this.registerForm.value)
.subscribe({
next: () => {
this.credentialService.validating.next(false);
this.credentialService.isValidating.set(false);
this.snackBar.open(
'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.',
'OK',
@@ -117,7 +112,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
this.router.navigate(['/login']);
},
error: (err) => {
this.credentialService.validating.next(false);
this.credentialService.isValidating.set(false);
this.registerForm.enable();
const message =
err.error?.message ||
@@ -16,15 +16,22 @@ import {
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import type {
CreateOrganizationPayload,
OrganizationProfile,
UpdateOrganizationPayload,
} from '../../../shared/services/organization-management.service';
import { InseOrganizationManagementModelOrganizationProfile } from '../../../api';
export interface CreateOrganizationPayload {
name: string;
other_inst_id?: string | null;
}
export interface UpdateOrganizationPayload {
name?: string;
other_inst_id?: string | null;
deleted?: boolean;
}
export interface OrganizationDialogData {
mode: 'create' | 'edit';
organization?: OrganizationProfile;
organization?: InseOrganizationManagementModelOrganizationProfile;
}
export type OrganizationDialogResult =
@@ -66,10 +73,9 @@ export class OrganizationDialogComponent {
nonNullable: true,
validators: [Validators.required],
}),
otherInstId: new FormControl(
this.data.organization?.other_inst_id ?? '',
{ nonNullable: true },
),
otherInstId: new FormControl(this.data.organization?.other_inst_id ?? '', {
nonNullable: true,
}),
deleted: new FormControl(this.data.organization?.deleted ?? false, {
nonNullable: true,
}),
@@ -100,6 +106,6 @@ export class OrganizationDialogComponent {
}
protected close(): void {
this.dialogRef.close(undefined);
this.dialogRef.close();
}
}
@@ -3,6 +3,7 @@
<div>
<h1>Organisationen</h1>
<p>Mandanten, externe Institutions-IDs und Status verwalten.</p>
<!-- Was meinte die KI mit Mandanten? -->
</div>
<button
mat-flat-button
@@ -14,92 +15,38 @@
</button>
</header>
<section class="table-panel">
<div class="table-header">
<strong>{{ total }} Organisationen</strong>
@if (isLoading) {
<span>Wird geladen...</span>
}
</div>
<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>
<mat-card appearance="outlined">
<mat-card-content>
<app-data-table
[columns]="organizationColumns"
[data]="organizationPage().items" />
</mat-card-content>
</mat-card>
<app-query-param-paginator [total]="organizationPage().total" />
</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;
}
.page-header,
.table-header,
.pagination,
.row-actions {
.page-header {
display: flex;
align-items: center;
}
.page-header {
justify-content: space-between;
gap: 16px;
}
@@ -32,60 +26,6 @@ p {
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 {
display: inline-flex;
align-items: center;
@@ -103,21 +43,6 @@ tr.deleted {
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) {
.organizations-page {
padding: 16px;
@@ -128,3 +53,8 @@ tr.deleted {
flex-direction: column;
}
}
mat-card,
mat-paginator {
background-color: var(--sg-background);
}
@@ -1,19 +1,34 @@
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 { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { finalize } from 'rxjs';
import {
OrganizationManagementService,
OrganizationProfile,
} from '../../shared/services/organization-management.service';
import type {
OrganizationDialogComponent,
OrganizationDialogData,
OrganizationDialogResult,
} 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({
selector: 'app-organizations',
@@ -23,50 +38,81 @@ import type {
MatDialogModule,
MatIconModule,
MatSnackBarModule,
DataTableComponent,
MatCardModule,
StatusPipe,
QueryParamPaginatorComponent,
],
templateUrl: './organizations.component.html',
styleUrl: './organizations.component.scss',
standalone: true,
})
export class OrganizationsComponent implements OnInit {
private readonly organizationService = inject(OrganizationManagementService);
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly organizationService = inject(OrganizationService);
protected organizations: OrganizationProfile[] = [];
protected total = 0;
protected page = 0;
protected readonly pageSize = 10;
protected isLoading = false;
organizationPage = input.required<OrganizationPage>();
organizationColumns: GenericColumn<InseOrganizationManagementModelOrganizationProfile>[] =
[];
organizationStatusTmp = viewChild.required<TemplateRef<any>>(
'organizationStatusTmp',
);
organizationActionsTmp = viewChild.required<TemplateRef<any>>(
'organizationActionsTmp',
);
ngOnInit(): void {
this.loadOrganizations();
}
protected loadOrganizations(page = this.page): void {
this.page = page;
this.isLoading = true;
this.organizationService
.getOrganizations(page, this.pageSize)
.pipe(finalize(() => (this.isLoading = false)))
.subscribe({
next: (result) => {
this.organizations = result.items;
this.total = result.total;
},
error: () => this.showError('Organisationen konnten nicht geladen werden.'),
});
this.organizationColumns = [
{
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'name',
},
{
id: 'other_inst_id',
header: 'Externe ID',
type: 'accessor',
accessorKey: 'other_inst_id',
},
{
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 {
this.openDialog({ mode: 'create' });
}
protected startEdit(organization: OrganizationProfile): void {
protected startEdit(
organization: InseOrganizationManagementModelOrganizationProfile,
): void {
this.openDialog({ mode: 'edit', organization });
}
protected deleteOrganization(organization: OrganizationProfile): void {
protected deleteOrganization(
organization: InseOrganizationManagementModelOrganizationProfile,
): void {
if (organization.deleted) return;
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
@@ -87,26 +133,24 @@ export class OrganizationsComponent implements OnInit {
);
}
private softDeleteOrganization(organization: OrganizationProfile): void {
this.organizationService.deleteOrganization(organization.id).subscribe({
private softDeleteOrganization(
organization: InseOrganizationManagementModelOrganizationProfile,
): void {
this.organizationService.deleteOrganisation(organization.id).subscribe({
next: () => {
this.snackBar.open('Organisation wurde deaktiviert.', 'OK', {
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 {
import('./organization-dialog/organization-dialog.component').then(
({ OrganizationDialogComponent }) => {
@@ -130,8 +174,8 @@ export class OrganizationsComponent implements OnInit {
private save(result: OrganizationDialogResult): void {
const request =
result.mode === 'create'
? this.organizationService.createOrganization(result.payload)
: this.organizationService.updateOrganization(
? this.organizationService.createOrganisation(result.payload)
: this.organizationService.updateOrganisation(
result.organizationId,
result.payload,
);
@@ -141,7 +185,10 @@ export class OrganizationsComponent implements OnInit {
this.snackBar.open('Organisation wurde gespeichert.', 'OK', {
duration: 3000,
});
this.loadOrganizations(0);
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: (error) =>
this.showError(
+2 -3
View File
@@ -1,8 +1,7 @@
import { ResolveFn } from '@angular/router';
import { AccountProfile } from '../api';
import { AccountProfile, AuthService } from '../api';
import { inject } from '@angular/core';
import { AccountManagementService } from '../shared/services/account-management.service';
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 { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service';
export const accountViewerGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe(
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
return new Promise<boolean>((resolve) => {
const ref = effect(
() => {
if (credentialService.isValidating()) {
return;
}
return credentialService.validateCurrentSession().pipe(
switchMap(() => {
const mayViewAccounts =
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin() ||
credentialService.isEffectiveManager();
ref.destroy();
if (!mayViewAccounts) {
void router.navigate(['/dashboard']);
}
if (!credentialService.isAuthenticated()) {
void router.navigate(['/login']);
resolve(false);
return;
}
return of(mayViewAccounts);
}),
catchError(() => of(false)),
);
}),
);
const mayViewAccounts =
credentialService.isEffectiveSuperAdmin() ||
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 { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service';
export const adminGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe(
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
return new Promise<boolean>((resolve) => {
const ref = effect(
() => {
if (credentialService.isValidating()) {
return;
}
return credentialService.validateCurrentSession().pipe(
switchMap(() => {
if (
!credentialService.isEffectiveSuperAdmin() &&
!credentialService.isEffectiveAdmin()
) {
void router.navigate(['/dashboard']);
return of(false);
}
ref.destroy();
return of(true);
}),
catchError(() => of(false)),
);
}),
);
if (!credentialService.isAuthenticated()) {
void router.navigate(['/login']);
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 { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service';
export const superAdminGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe(
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
return new Promise<boolean>((resolve) => {
const ref = effect(
() => {
if (credentialService.isValidating()) {
return;
}
return credentialService.validateCurrentSession().pipe(
switchMap(() => {
if (!credentialService.isEffectiveSuperAdmin()) {
void router.navigate(['/dashboard']);
return of(false);
}
return of(true);
}),
catchError(() => of(false)),
);
}),
);
ref.destroy();
if (!credentialService.isAuthenticated()) {
void router.navigate(['/login']);
resolve(false);
return;
}
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 { catchError, filter, map, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service';
export const userGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
const injector = inject(Injector);
return credentialService.validating.pipe(
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
return new Promise<boolean>((resolve) => {
const ref = effect(
() => {
if (credentialService.isValidating()) {
return;
}
return credentialService.validateCurrentSession().pipe(
map(() => true),
catchError(() => of(false)),
);
}),
);
ref.destroy();
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 { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
import { catchError, switchMap, tap, throwError } from 'rxjs';
import { CredentialService } from '../services/credential.service';
import { UiFocusService } from '../services/ui-focus.service';
import { catchError, switchMap, throwError } from 'rxjs';
import {
CredentialService,
clearStoredAuthState,
REQUIRED_TOKEN_TYPE,
TOKEN_TYPE,
} from '../services/credential.service';
export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
const url = req.url.split('?')[0];
const uiFocusService = inject(UiFocusService);
const attachBearer = <T>(
req: HttpRequest<T>,
token: string,
): HttpRequest<T> => {
if (!token) {
return req;
}
return req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token),
});
};
const isPublicAuthRequest =
req.method === 'POST' &&
(url.endsWith('/api/auth/v2/request-otk') ||
url.endsWith('/api/auth/v2/login') ||
url.endsWith('/api/auth/v2/access') ||
url.endsWith('/api/auth/v2/refresh'));
if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) {
return next(req);
const handleAccessTokenError = (
error: unknown,
req: HttpRequest<unknown>,
next: Parameters<HttpInterceptorFn>[1],
credentialService: CredentialService,
router: Router,
) => {
if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
return throwError(() => error);
}
const credentialService = inject(CredentialService);
const router = inject(Router);
const snackBar = inject(MatSnackBar);
const tokenProvider = credentialService.getBearerToken();
const isLogoutRequest = url.endsWith('/api/auth/v2/logout');
if (!credentialService.getRawAccessToken()) {
credentialService.logout();
router.navigate(['/login'], { replaceUrl: true });
return throwError(() => error);
}
return tokenProvider.pipe(
switchMap((response) => {
if (response == undefined) {
credentialService.clearLocalAuthState();
snackBar.open(
'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);
}),
);
return credentialService.refreshAccessToken().pipe(
switchMap((accessToken) => next(attachBearer(req, accessToken.raw_token))),
catchError((refreshError) => {
credentialService.logout();
router.navigate(['/login'], { replaceUrl: true });
return throwError(() => refreshError);
}),
);
};
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 { filter, take, map, catchError, finalize } from 'rxjs/operators';
import { Injectable, computed, effect, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import {
BehaviorSubject,
catchError,
finalize,
firstValueFrom,
map,
Observable,
of,
shareReplay,
switchMap,
tap,
throwError,
} from 'rxjs';
import {
AccessResponse,
AccessToken,
AuthService,
Configuration,
IdToken,
LoginResponse,
AccountProfile,
OtkResponse,
IdTokenMetadata,
AccessToken,
LoginResponse,
} from '../../api';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
type LogoutResult = 'logged-out' | 'stopped-impersonating';
type UnauthorizedRecoveryResult =
| 'logged-out'
| 'stopped-impersonating'
| 'already-handling';
import { Router } from '@angular/router';
import { HttpContext, HttpContextToken } from '@angular/common/http';
export const TOKEN_TYPE = {
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({
providedIn: 'root',
})
export class CredentialService {
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 validating = new BehaviorSubject<boolean>(false);
public readonly isAuthenticated = new BehaviorSubject<boolean>(false);
public readonly isValidating = signal<boolean>(false);
public readonly isAuthenticated = computed(
() => this.accessToken() !== undefined,
);
public readonly isEffectiveSuperAdmin = computed(
() => this.accessToken()?.effective_role === 'SUPER_ADMIN',
);
public readonly isEffectiveAdmin = computed(
() => this.accessToken()?.effective_role === 'ADMIN',
() =>
this.accessToken()?.effective_role === 'ADMIN' ||
this.isEffectiveSuperAdmin(),
);
public readonly isEffectiveManager = computed(
() => this.accessToken()?.effective_role === 'MANAGER',
@@ -51,9 +75,13 @@ export class CredentialService {
public readonly effectiveOrganizationId = computed(
() => this.accessToken()?.effective_organization_id,
);
public readonly login = new BehaviorSubject<string>('');
public readonly email = new BehaviorSubject<string>('');
public readonly organizationName = new BehaviorSubject<string>('');
public readonly login = computed(
() => this.accountProfile()?.name ?? this.accountProfile()?.email ?? '',
);
public readonly email = computed(() => this.accountProfile()?.email ?? '');
public readonly organizationName = computed(
() => this.accountProfile()?.organization_name ?? '',
);
public readonly realAccountId = computed(
() => this.accessToken()?.real_account_id ?? '',
@@ -65,298 +93,283 @@ export class CredentialService {
() => this.realAccountId() !== this.effectiveAccountId(),
);
private readonly identityToken = signal<IdToken | undefined>(undefined);
private readonly accessToken = signal<AccessToken | undefined>(undefined);
public 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;
constructor(private readonly router: Router) {
const data = localStorage.getItem(CredentialService.KEY_GRANT);
const id = data ? (JSON.parse(data) as AccessToken) : undefined;
if (id && new Date(id.expires_at).getTime() >= Date.now()) {
this.identityToken.set(id);
this.validating.next(true);
setTimeout(() => this.refreshAccessToken(id), 0);
this.restoreAuthState();
effect(() => {
console.log('Access token changed:', this.accessToken());
});
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> {
return this.loadCurrentProfile();
private restoreAuthState(): void {
this.accessToken.set(this.getStoredAccessToken() ?? undefined);
}
public requestOtk(email: string, password: string): Observable<string> {
const request = ++this.request;
this.validating.next(true);
this.isAuthenticated.next(false);
this.identityToken.set(undefined);
private readAuthState(): StoredAuthState {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) {
return { idTokenMetadata: null, accessToken: null };
}
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.refreshInFlight$ = null;
}
return this.authService
.requestOtk({ email: email.trim().toLowerCase(), password })
.pipe(
map((response: { account_id?: string }) => {
if (this.request !== request) {
return '';
}
return response.account_id ?? '';
}),
finalize(() => {
if (this.request === request) {
this.validating.next(false);
}
}),
);
public requestOtk(email: string, password: string): Observable<OtkResponse> {
return this.authService.requestOtk(
{
email: email.trim(),
password: password.trim(),
},
undefined,
undefined,
{ context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
);
}
public loginWithOtk(
accountId: string,
email: string,
emailCode: string,
): Observable<void> {
const request = ++this.request;
this.validating.next(true);
this.isAuthenticated.next(false);
): Observable<LoginResponse> {
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(
switchMap((response: LoginResponse) => {
if (this.request != request) return of(undefined);
const idToken = response.id_token;
this.identityToken.set(idToken);
localStorage.setItem(
CredentialService.KEY_GRANT,
JSON.stringify(idToken),
);
return this.getAccessGrantForIdentity(idToken, request);
}),
tap(({ id_token }) =>
this.writeAuthState({ idTokenMetadata: id_token }),
),
);
}
public refreshAccessToken(identityToken: IdToken) {
const request = ++this.request;
this.validating.next(true);
this.accessToken.set(undefined);
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();
public requestAccess(
realAccountId: string,
effectiveAccountId?: string,
): Observable<AccessResponse> {
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(
catchError((error) => {
console.error('Backend logout failed', error);
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);
}),
);
tap(({ access_token }) => {
this.persistAccessToken(access_token);
}),
);
}
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(
currentPassword: string,
newPassword: string,
): Observable<void> {
return this.httpClient
.post(
`${this.apiBasePath}/api/auth/v2/change-password`,
{
current_password: currentPassword,
new_password: newPassword,
},
{ withCredentials: true },
)
this.isValidating.set(true);
return this.authService
.changePassword({
current_password: currentPassword,
new_password: newPassword,
})
.pipe(
tap(() => {
this.clearLocalAuthState();
}),
map(() => undefined),
tap(() => this.isValidating.set(false)),
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> {
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
class="drawer-container"
[autosize]="!mediaQuery.matches">
@if (credentialService.isAuthenticated | async) {
@if (credentialService.isAuthenticated()) {
<mat-drawer
class="drawer"
[class.drawer--collapsed]="isSidebarCollapsed()"
@@ -18,7 +18,7 @@
</mat-drawer>
}
<mat-drawer-content class="content-shell">
@if (credentialService.isAuthenticated | async) {
@if (credentialService.isAuthenticated()) {
@if (credentialService.isImpersonating()) {
<div class="impersonation-banner">
<mat-icon>switch_account</mat-icon>
@@ -102,22 +102,20 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.mediaQuery.removeEventListener('change', this.mediaQueryListener);
}
logout() {
this.credentialService.logoutAccount().subscribe({
next: (result) => {
if (result === 'stopped-impersonating') {
this.router.navigate(['/accounts']);
} else {
this.router.navigate(['/login']);
}
},
});
async logout() {
const isImpersonating = this.credentialService.isImpersonating();
if (isImpersonating) {
await this.credentialService.stopImpersonating();
this.router.navigate(['/accounts']);
} else {
await this.credentialService.logoutAccount();
}
}
stopImpersonating(): void {
this.credentialService.stopImpersonating().subscribe({
next: () => this.router.navigate(['/accounts']),
});
async stopImpersonating(): Promise<void> {
await this.credentialService.stopImpersonating();
this.router.navigate(['/accounts']);
}
navigateBack() {
@@ -105,13 +105,13 @@
<div
class="account-icon"
[matTooltip]="
((credentialService.login | async) || 'user') +
(credentialService.login() || 'user') +
' · ' +
((credentialService.organizationName | async) || '')
(credentialService.organizationName() || '')
"
matTooltipPosition="right">
<div class="avatar">
{{ (credentialService.login | async)?.charAt(0) }}
{{ (credentialService.login() || 'user').charAt(0) }}
</div>
</div>
} @else {
@@ -119,13 +119,11 @@
<mat-card appearance="outlined" class="account-card-content">
<mat-card-content class="account-card">
<div class="avatar">
{{ (credentialService.login | async)?.charAt(0) }}
{{ (credentialService.login() || 'user').charAt(0) }}
</div>
<div>
<strong>{{
(credentialService.login | async) || 'Max Mustermann'
}}</strong>
<strong>{{ credentialService.organizationName | async }}</strong>
<strong>{{ credentialService.login() || 'Max Mustermann' }}</strong>
<strong>{{ credentialService.organizationName() }}</strong>
</div>
</mat-card-content>
</mat-card>
@@ -70,7 +70,7 @@ export class AppMenuComponent {
icon: 'groups',
route: '/persons',
queryParams: {
institutionName: this.credentialService.organizationName.value,
institutionName: this.credentialService.organizationName(),
},
disabled: false,
},
@@ -142,9 +142,7 @@ export class AppMenuComponent {
label: 'Navigation',
items: this.navItems.filter(
(item) =>
!item.adminOnly &&
!item.superAdminOnly &&
!item.managerOrAdminOnly,
!item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly,
),
},
{
@@ -181,15 +179,7 @@ export class AppMenuComponent {
});
dialogRef.componentInstance.confirmDelete.subscribe(() => {
this.credentialService.logoutAccount().subscribe({
next: (result) => {
if (result === 'stopped-impersonating') {
this.router.navigate(['/accounts']);
} else {
this.router.navigate(['/login']);
}
},
});
void this.credentialService.logoutAccount();
});
}
}
@@ -1,5 +1,12 @@
<select (change)="_handleSelectionChange($event)" [ngModel]="_urlValue()">
@for (option of options(); track $index) {
<option [value]="option.value">{{ option.display_name }}</option>
<mat-form-field style="width: 100%">
@if (label()) {
<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 { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatSelectChange, MatSelectModule } from '@angular/material/select';
import { ActivatedRoute, Router } from '@angular/router';
export type SelectorOption = {
@@ -10,14 +11,30 @@ export type SelectorOption = {
@Component({
selector: 'app-query-param-selector',
imports: [FormsModule],
imports: [FormsModule, MatSelectModule],
templateUrl: './query-param-selector.component.html',
styleUrl: './query-param-selector.component.scss',
})
export class QueryParamSelectorComponent {
options = input.required<SelectorOption[]>();
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 router = inject(Router);
@@ -33,8 +50,8 @@ export class QueryParamSelectorComponent {
return params && key ? params[key] || '' : '';
});
_handleSelectionChange(event: Event): void {
const newValue = (event.target as HTMLSelectElement).value;
_handleSelectionChange(event: MatSelectChange): void {
const newValue = event.value;
this.router.navigate([], {
queryParams: { [this.queryParamKey()]: newValue },