diff --git a/service/src/main/inse/account_management/router.py b/service/src/main/inse/account_management/router.py index 82781fb0..81b22593 100644 --- a/service/src/main/inse/account_management/router.py +++ b/service/src/main/inse/account_management/router.py @@ -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, diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py index 9e0362ad..b9d9dfda 100644 --- a/service/src/main/inse/account_management/service.py +++ b/service/src/main/inse/account_management/service.py @@ -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) diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index bd519058..fdd687a2 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -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." ) diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 2ce4f52a..9c15079f 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -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, ], ): diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 61626236..604085ab 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -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]: diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 0e61130c..728a61ee 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -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, ) diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py index 0a8b82ca..5a2db2bd 100644 --- a/service/src/main/inse/organization_management/router.py +++ b/service/src/main/inse/organization_management/router.py @@ -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) diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 80dd88c9..528bcf35 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -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) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 99b72add..f9ac2e32 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -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 diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 8ea55e0b..817a3a65 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -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]; diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 6beb60cc..086a0e47 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -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; - public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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>; - public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - 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>; - 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>; - 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 { + 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; + 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>; + 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>; + 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 { 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; - public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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('post', `${basePath}${localVarPath}`, + return this.httpClient.request('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; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (accountId === null || accountId === undefined) { throw new Error('Required parameter accountId was null or undefined when calling updateAccount.'); } diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts index 2af0ed8b..14fb942d 100644 --- a/webapp/src/app/api/api/organization.service.ts +++ b/webapp/src/app/api/api/organization.service.ts @@ -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; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + 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 { 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; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (organizationId === null || organizationId === undefined) { throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); } diff --git a/webapp/src/app/api/model/accessResponse.ts b/webapp/src/app/api/model/accessResponse.ts index f1610895..6a36e872 100644 --- a/webapp/src/app/api/model/accessResponse.ts +++ b/webapp/src/app/api/model/accessResponse.ts @@ -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; } diff --git a/webapp/src/app/api/model/accessToken.ts b/webapp/src/app/api/model/accessToken.ts index ce3ea930..2c470009 100644 --- a/webapp/src/app/api/model/accessToken.ts +++ b/webapp/src/app/api/model/accessToken.ts @@ -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 { } diff --git a/webapp/src/app/api/model/accountProfile.ts b/webapp/src/app/api/model/accountProfile.ts index 52a9f7e6..58adefb8 100644 --- a/webapp/src/app/api/model/accountProfile.ts +++ b/webapp/src/app/api/model/accountProfile.ts @@ -26,3 +26,4 @@ export interface AccountProfile { export namespace AccountProfile { } + diff --git a/webapp/src/app/api/model/bodyRequestOtk.ts b/webapp/src/app/api/model/bodyRequestOtk.ts index 1600a002..ba1a396d 100644 --- a/webapp/src/app/api/model/bodyRequestOtk.ts +++ b/webapp/src/app/api/model/bodyRequestOtk.ts @@ -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; } + diff --git a/webapp/src/app/api/model/createOrganizationRequest.ts b/webapp/src/app/api/model/createOrganizationRequest.ts index 94aacb80..fffb5457 100644 --- a/webapp/src/app/api/model/createOrganizationRequest.ts +++ b/webapp/src/app/api/model/createOrganizationRequest.ts @@ -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; } + diff --git a/webapp/src/app/api/model/extractedKeywordsResponse.ts b/webapp/src/app/api/model/extractedKeywordsResponse.ts index 8fe10a5f..43731b7c 100644 --- a/webapp/src/app/api/model/extractedKeywordsResponse.ts +++ b/webapp/src/app/api/model/extractedKeywordsResponse.ts @@ -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; } + diff --git a/webapp/src/app/api/model/idToken.ts b/webapp/src/app/api/model/idTokenMetadata.ts similarity index 72% rename from webapp/src/app/api/model/idToken.ts rename to webapp/src/app/api/model/idTokenMetadata.ts index e6a88cd3..5398083d 100644 --- a/webapp/src/app/api/model/idToken.ts +++ b/webapp/src/app/api/model/idTokenMetadata.ts @@ -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 { } diff --git a/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts index 47235351..c67acc71 100644 --- a/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts @@ -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; } + diff --git a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts index 8f9f0e6b..404df0f9 100644 --- a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts @@ -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; } + diff --git a/webapp/src/app/api/model/keywordTopicMatch.ts b/webapp/src/app/api/model/keywordTopicMatch.ts index ee4c8326..f9c2ab49 100644 --- a/webapp/src/app/api/model/keywordTopicMatch.ts +++ b/webapp/src/app/api/model/keywordTopicMatch.ts @@ -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; } + diff --git a/webapp/src/app/api/model/keywordsTopicsRequest.ts b/webapp/src/app/api/model/keywordsTopicsRequest.ts index 883ed079..8810bf5f 100644 --- a/webapp/src/app/api/model/keywordsTopicsRequest.ts +++ b/webapp/src/app/api/model/keywordsTopicsRequest.ts @@ -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; + +export interface KeywordsTopicsRequest { + /** + * List of keywords/sentences to query by similarity. + */ + keywords: Array; } + diff --git a/webapp/src/app/api/model/keywordsTopicsResponse.ts b/webapp/src/app/api/model/keywordsTopicsResponse.ts index 78a2f9d2..4aee622f 100644 --- a/webapp/src/app/api/model/keywordsTopicsResponse.ts +++ b/webapp/src/app/api/model/keywordsTopicsResponse.ts @@ -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; + +export interface KeywordsTopicsResponse { + /** + * Top matching topics for each keyword in the requested list. + */ + results: Array; } + diff --git a/webapp/src/app/api/model/loginResponse.ts b/webapp/src/app/api/model/loginResponse.ts index 216d0fb0..c91eb493 100644 --- a/webapp/src/app/api/model/loginResponse.ts +++ b/webapp/src/app/api/model/loginResponse.ts @@ -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; } + diff --git a/webapp/src/app/api/model/matchedAuthor.ts b/webapp/src/app/api/model/matchedAuthor.ts index 311e2184..6194df94 100644 --- a/webapp/src/app/api/model/matchedAuthor.ts +++ b/webapp/src/app/api/model/matchedAuthor.ts @@ -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; } + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 8e381ef2..3bf537d5 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -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'; diff --git a/webapp/src/app/api/model/otkResponse.ts b/webapp/src/app/api/model/otkResponse.ts new file mode 100644 index 00000000..7d956289 --- /dev/null +++ b/webapp/src/app/api/model/otkResponse.ts @@ -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; +} + diff --git a/webapp/src/app/api/model/refreshToken.ts b/webapp/src/app/api/model/refreshToken.ts deleted file mode 100644 index 89506b70..00000000 --- a/webapp/src/app/api/model/refreshToken.ts +++ /dev/null @@ -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 { -} - - diff --git a/webapp/src/app/api/model/tokenType.ts b/webapp/src/app/api/model/tokenType.ts index 06231c11..a0efdc46 100644 --- a/webapp/src/app/api/model/tokenType.ts +++ b/webapp/src/app/api/model/tokenType.ts @@ -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]; diff --git a/webapp/src/app/api/model/updateAccountRequest.ts b/webapp/src/app/api/model/updateAccountRequest.ts index 1d4389f7..efc4cea6 100644 --- a/webapp/src/app/api/model/updateAccountRequest.ts +++ b/webapp/src/app/api/model/updateAccountRequest.ts @@ -23,3 +23,4 @@ export interface UpdateAccountRequest { export namespace UpdateAccountRequest { } + diff --git a/webapp/src/app/api/model/updateOrganizationRequest.ts b/webapp/src/app/api/model/updateOrganizationRequest.ts index a56b51e7..e12063b6 100644 --- a/webapp/src/app/api/model/updateOrganizationRequest.ts +++ b/webapp/src/app/api/model/updateOrganizationRequest.ts @@ -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; } + diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 3b700752..0d7f746c 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -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); diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 4f8758d7..ac603aae 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -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], diff --git a/webapp/src/app/modules/account/account.component.ts b/webapp/src/app/modules/account/account.component.ts index 8b3eec70..647e5a99 100644 --- a/webapp/src/app/modules/account/account.component.ts +++ b/webapp/src/app/modules/account/account.component.ts @@ -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 }, + ); + } }, }, }, diff --git a/webapp/src/app/modules/accounts/account-dialog.component.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts index a10cff43..87fb87f2 100644 --- a/webapp/src/app/modules/accounts/account-dialog.component.ts +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -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(this.data.account?.name ?? '', [ Validators.required, ]), - role: new FormControl(this.data.account?.role ?? 'USER', [ + role: new FormControl(this.data.account?.role ?? 'USER', [ Validators.required, ]), organizationId: new FormControl( @@ -148,6 +164,6 @@ export class AccountDialogComponent { } protected close(): void { - this.dialogRef.close(undefined); + this.dialogRef.close(); } } diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 5f2ac458..7e1f45e0 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -23,189 +23,73 @@ } -
- - Name oder E-Mail - - - - @if (credentialService.isEffectiveSuperAdmin()) { - - Organisation - - Alle Organisationen - @for (organization of organizations; track organization.id) { - - {{ organization.name }} - - } - - - } - -
- - -
-
- -
-
- {{ total }} Accounts - @if (isLoading) { - Wird geladen... - } -
- -
- - - - - - - - - @if (!isReadOnly) { - - } - - - - @for (account of accounts; track account.id) { - - - - - - - @if (!isReadOnly) { - - } - - } @empty { - - - - } - -
NameE-MailOrganisationRolleStatusAktionen
- @if (isReadOnly) { - {{ account.name }} - } @else { - - } - {{ account.email }}{{ account.organization_name }} - {{ account.role | role }} - - - {{ - account.deleted - ? 'deleted' - : account.activated - ? 'active' - : 'inactive' - }} - - -
- - - @if (credentialService.isEffectiveSuperAdmin()) { - - } - -
-
- Keine Accounts gefunden. -
-
- - +
+ +
+ + + + + +
+ + + {{ row.role | role }} + + + + + {{ + (row.deleted ? 'deleted' : row.activated ? 'active' : 'inactive') | status + }} + + + + +
+ + + + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component.scss b/webapp/src/app/modules/accounts/accounts.component.scss index 58c2be4a..dc24d512 100644 --- a/webapp/src/app/modules/accounts/accounts.component.scss +++ b/webapp/src/app/modules/accounts/accounts.component.scss @@ -155,3 +155,8 @@ tr.deactivated:not(.deleted) { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index da287d1c..b66f5e5e 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -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[] = []; + accountRoleTmp = viewChild.required>('accountRoleTmp'); + accountStatusTmp = viewChild.required>('accountStatusTmp'); + accountActionsTmp = viewChild.required>('accountActionsTmp'); + + availableRoles = computed(() => { 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(''), - organizationId: new FormControl(''), }); + selectorOptions = computed(() => { + return this.organizations().map((org) => ({ + value: org.id, + display_name: org.name, + })); + }); + + accountPage = input.required(); + organizations = + input.required(); + 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 { 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 { diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index b7bca239..a8bd7fea 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -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('', [Validators.required, Validators.email]), password: new FormControl('', [ @@ -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.'; } diff --git a/webapp/src/app/modules/app-register/app-register.component.html b/webapp/src/app/modules/app-register/app-register.component.html index e6349bc5..a9e758c6 100644 --- a/webapp/src/app/modules/app-register/app-register.component.html +++ b/webapp/src/app/modules/app-register/app-register.component.html @@ -84,9 +84,7 @@ mat-raised-button class="button" (click)="submit()" - [disabled]=" - !registerForm.valid || (credentialService.validating | async) - "> + [disabled]="!registerForm.valid || credentialService.isValidating()"> Registrieren diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts index d4169732..a2341a1a 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -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 || diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index 0ec24397..5edb4c3c 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -12,11 +12,13 @@
+ [queryParamKey]="'sort_by'" + label="Sortieren nach" /> + [queryParamKey]="'sorting_order'" + label="Sortierreihenfolge" />
diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 7303fdd7..8edbecef 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -25,7 +25,7 @@ .cards { display: grid; gap: 1.5rem; - grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(550px, 1fr)); padding: 0 1rem; } diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts index 6348c11f..a192c306 100644 --- a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts @@ -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(); } } diff --git a/webapp/src/app/modules/organizations/organizations.component.html b/webapp/src/app/modules/organizations/organizations.component.html index a6486b74..14853ec0 100644 --- a/webapp/src/app/modules/organizations/organizations.component.html +++ b/webapp/src/app/modules/organizations/organizations.component.html @@ -3,6 +3,7 @@

Organisationen

Mandanten, externe Institutions-IDs und Status verwalten.

+
- Seite {{ page + 1 }} - - - + + + + + + + + + + {{ (row.deleted ? 'inactive' : 'active') | status }} + + + + +
+ + +
+
diff --git a/webapp/src/app/modules/organizations/organizations.component.scss b/webapp/src/app/modules/organizations/organizations.component.scss index b558f858..e455d7e3 100644 --- a/webapp/src/app/modules/organizations/organizations.component.scss +++ b/webapp/src/app/modules/organizations/organizations.component.scss @@ -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); +} diff --git a/webapp/src/app/modules/organizations/organizations.component.ts b/webapp/src/app/modules/organizations/organizations.component.ts index 0d061c50..6cbaecb4 100644 --- a/webapp/src/app/modules/organizations/organizations.component.ts +++ b/webapp/src/app/modules/organizations/organizations.component.ts @@ -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(); + organizationColumns: GenericColumn[] = + []; + + organizationStatusTmp = viewChild.required>( + 'organizationStatusTmp', + ); + organizationActionsTmp = viewChild.required>( + '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( diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 14a37666..60086f40 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -26,14 +26,11 @@ USPTO -
- -
+ diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index adfd23e2..0eb946dc 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -15,6 +15,10 @@ import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; import { PatentsService } from '../../api/api/patents.service'; import { PatentEntry } from '../../api/model/patentEntry'; import { IpcClassification } from '../../api'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; @@ -44,6 +48,7 @@ const DESCRIPTION_PREVIEW_LENGTH = 140; MatProgressSpinnerModule, MatChipsModule, MatDividerModule, + QueryParamSelectorComponent, ], templateUrl: './patents.component.html', styleUrl: './patents.component.scss', @@ -71,6 +76,12 @@ export class PatentsComponent implements OnInit { private searchSubject = new Subject(); + sortingDirectionOptions: SelectorOption[] = [ + { value: '', display_name: '' }, + { value: 'asc', display_name: 'Aufsteigend' }, + { value: 'desc', display_name: 'Absteigend' }, + ]; + constructor() { this.searchSubject .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed()) diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 706f34fb..b2bcbddf 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -28,11 +28,13 @@
+ queryParamKey="sort_by" + label="Sortieren nach" /> + queryParamKey="sorting_order" + label="Sortierreihenfolge" />
diff --git a/webapp/src/app/resolvers/account.resolver.ts b/webapp/src/app/resolvers/account.resolver.ts index 9a2b7936..13b005b4 100644 --- a/webapp/src/app/resolvers/account.resolver.ts +++ b/webapp/src/app/resolvers/account.resolver.ts @@ -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 = (route, state) => { - return inject(AccountManagementService).getCurrentAccount(); + return inject(AuthService).getCurrentAccount(); }; diff --git a/webapp/src/app/resolvers/accounts-organizations.resolver.ts b/webapp/src/app/resolvers/accounts-organizations.resolver.ts new file mode 100644 index 00000000..8fb026c9 --- /dev/null +++ b/webapp/src/app/resolvers/accounts-organizations.resolver.ts @@ -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(); +}; diff --git a/webapp/src/app/resolvers/accounts-page.resolver.ts b/webapp/src/app/resolvers/accounts-page.resolver.ts new file mode 100644 index 00000000..1d4be85d --- /dev/null +++ b/webapp/src/app/resolvers/accounts-page.resolver.ts @@ -0,0 +1,19 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { AccountPage, AuthService } from '../api'; + +export const accountsPageResolver: ResolveFn = (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, + ); +}; diff --git a/webapp/src/app/resolvers/organizations-organizations.resolver.ts b/webapp/src/app/resolvers/organizations-organizations.resolver.ts new file mode 100644 index 00000000..70297dee --- /dev/null +++ b/webapp/src/app/resolvers/organizations-organizations.resolver.ts @@ -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); +}; diff --git a/webapp/src/app/shared/guards/account-viewer.guard.ts b/webapp/src/app/shared/guards/account-viewer.guard.ts index 1cc8e9ee..9eeac48d 100644 --- a/webapp/src/app/shared/guards/account-viewer.guard.ts +++ b/webapp/src/app/shared/guards/account-viewer.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index 55e18ca8..a8876ced 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/super-admin.guard.ts b/webapp/src/app/shared/guards/super-admin.guard.ts index b1936483..993f00a5 100644 --- a/webapp/src/app/shared/guards/super-admin.guard.ts +++ b/webapp/src/app/shared/guards/super-admin.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index 190780ae..7145e5ea 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 130e6c94..08113260 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -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 = ( + req: HttpRequest, + token: string, +): HttpRequest => { + 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, + next: Parameters[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), + ), + ); +}; diff --git a/webapp/src/app/shared/pipes/status.pipe.ts b/webapp/src/app/shared/pipes/status.pipe.ts new file mode 100644 index 00000000..5ba35960 --- /dev/null +++ b/webapp/src/app/shared/pipes/status.pipe.ts @@ -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; + } + } +} diff --git a/webapp/src/app/shared/services/account-management.service.ts b/webapp/src/app/shared/services/account-management.service.ts deleted file mode 100644 index e86179ef..00000000 --- a/webapp/src/app/shared/services/account-management.service.ts +++ /dev/null @@ -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 { - return this.httpClient.get( - `${this.apiBasePath}/api/accounts/me`, - ); - } - - listAccounts(options: { - page: number; - pageSize: number; - search?: string; - organizationId?: string; - }): Observable { - 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( - `${this.apiBasePath}/api/accounts`, - { - params, - }, - ); - } - - createAccount(payload: CreateAccountPayload): Observable { - return this.httpClient.post( - `${this.apiBasePath}/api/accounts`, - payload, - ); - } - - updateAccount( - accountId: string, - payload: AccountPayload, - ): Observable { - return this.httpClient.put( - `${this.apiBasePath}/api/accounts/${accountId}`, - payload, - ); - } - - deleteAccount(accountId: string): Observable { - return this.httpClient.delete( - `${this.apiBasePath}/api/accounts/${accountId}`, - ); - } - - listOrganizations(): Observable { - return this.httpClient.get( - `${this.apiBasePath}/api/accounts/organizations`, - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } -} diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index efc16734..e70311a2 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -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( + () => 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(false); - public readonly isAuthenticated = new BehaviorSubject(false); + public readonly isValidating = signal(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(''); - public readonly email = new BehaviorSubject(''); - public readonly organizationName = new BehaviorSubject(''); + 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(undefined); - private readonly accessToken = signal(undefined); + public readonly accessToken = signal(undefined); + + public readonly isActiveAccessToken = computed(() => { + const accessToken = this.accessToken(); + return ( + accessToken !== undefined && + new Date(accessToken.expires_at).getTime() >= Date.now() + ); + }); + + public readonly accountProfile = toSignal( + toObservable(this.accessToken).pipe( + switchMap((accessToken) => + accessToken + ? this.authService.getCurrentAccount() + : of(undefined), + ), + ), + { initialValue: undefined }, + ); + + private refreshInFlight$: Observable | 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 { - return this.loadCurrentProfile(); + private restoreAuthState(): void { + this.accessToken.set(this.getStoredAccessToken() ?? undefined); } - public requestOtk(email: string, password: string): Observable { - 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): 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 { + 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 { - const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); - + ): Observable { 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 { - 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 { - 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 { - const wasImpersonating = this.isImpersonating(); - + public requestAccess( + realAccountId: string, + effectiveAccountId?: string, + ): Observable { 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 { - 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 { - 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 { + 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 { + 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 { + 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 { + 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 { + 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 { return throwError(() => new Error('Registration is temporarily disabled.')); } - - //review: arman (generated fix) - public getBearerToken(): Observable { - 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 { - 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(`${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 { - return this.httpClient - .get(`${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), - ); - } } diff --git a/webapp/src/app/shared/services/organization-management.service.ts b/webapp/src/app/shared/services/organization-management.service.ts deleted file mode 100644 index 9597a005..00000000 --- a/webapp/src/app/shared/services/organization-management.service.ts +++ /dev/null @@ -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 { - const params = new HttpParams() - .set('page', page) - .set('page_size', pageSize); - return this.httpClient.get( - `${this.apiBasePath}/api/organizations`, - { params }, - ); - } - - createOrganization( - payload: CreateOrganizationPayload, - ): Observable { - return this.httpClient.post( - `${this.apiBasePath}/api/organizations`, - payload, - ); - } - - updateOrganization( - organizationId: string, - payload: UpdateOrganizationPayload, - ): Observable { - return this.httpClient.put( - `${this.apiBasePath}/api/organizations/${organizationId}`, - payload, - ); - } - - deleteOrganization(organizationId: string): Observable { - return this.httpClient.delete( - `${this.apiBasePath}/api/organizations/${organizationId}`, - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } -} diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index f4ae841c..7be187a0 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -3,7 +3,7 @@ - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { } - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { @if (credentialService.isImpersonating()) {
switch_account diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 127f842d..abd2f2ec 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -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 { + await this.credentialService.stopImpersonating(); + this.router.navigate(['/accounts']); } navigateBack() { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index bb0b8f36..5b913d11 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -105,13 +105,13 @@ } @else { @@ -119,13 +119,11 @@ diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 7ea9e1b8..f39ff565 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -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(); }); } } diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html index 0f6dcd9b..2ce167fe 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html @@ -1,5 +1,12 @@ - + + @for (option of _options(); track $index) { + {{ option.display_name }} + } + + diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts index caa3f7bf..2b51fdd4 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts @@ -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(); queryParamKey = input.required(); - handleSelectionChange = output(); + handleSelectionChange = output(); + allowEmptyValue = input(false); + label = input(''); + + _options = computed(() => { + 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 },