From 11ea77135ec825f13ff384cd43c4f820787c1559 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 30 Jun 2026 20:58:41 +0200 Subject: [PATCH] Replace OpenAlex HTTP clients with Elasticsearch --- service/src/data/predefined_accounts 2.json | 29 + .../inse/account_management/__init__ 2.py | 1 + .../main/inse/account_management/model 2.py | 51 + .../main/inse/account_management/router 2.py | 125 ++ .../main/inse/account_management/service 2.py | 311 +++++ service/src/main/inse/auth/__init__ 2.py | 0 service/src/main/inse/auth/email_service 2.py | 29 + service/src/main/inse/auth/model 2.py | 212 ++++ service/src/main/inse/auth/router 2.py | 162 +++ service/src/main/inse/auth/service 2.py | 1076 +++++++++++++++++ .../src/main/inse/auth/test_auth_service 2.py | 517 ++++++++ service/src/main/inse/config.py | 1 - service/src/main/inse/institutions/logic.py | 40 +- .../main/inse/institutions/search_client.py | 224 ++-- .../src/main/inse/institutions/test_logic.py | 194 +-- .../inse/institutions/test_search_client.py | 86 +- .../organization_management/__init__ 2.py | 1 + .../inse/organization_management/model 2.py | 30 + .../inse/organization_management/router 2.py | 81 ++ .../inse/organization_management/service 2.py | 183 +++ .../organization_management/test_service 2.py | 181 +++ service/src/main/inse/topics/logic.py | 40 +- service/src/main/inse/topics/search_client.py | 197 +-- service/src/main/inse/topics/test_logic.py | 216 +--- .../main/inse/topics/test_search_client.py | 78 +- .../main/inse/works/test_openalex_logic.py | 234 ++-- webapp/src/app/api/api/auth.service 2.ts | 871 +++++++++++++ webapp/src/app/api/model/accessResponse 2.ts | 24 + webapp/src/app/api/model/accessToken 2.ts | 55 + webapp/src/app/api/model/accountPage 2.ts | 19 + webapp/src/app/api/model/accountProfile 2.ts | 28 + .../src/app/api/model/bodyChangePassword 2.ts | 22 + .../src/app/api/model/bodyGetAccessToken 2.ts | 22 + webapp/src/app/api/model/bodyLogin 2.ts | 22 + webapp/src/app/api/model/bodyRequestOtk 2.ts | 22 + .../app/api/model/createAccountRequest 2.ts | 24 + webapp/src/app/api/model/idToken 2.ts | 42 + webapp/src/app/api/model/loginResponse 2.ts | 19 + webapp/src/app/api/model/refreshToken 2.ts | 55 + webapp/src/app/api/model/tokenType 2.ts | 18 + .../app/api/model/updateAccountRequest 2.ts | 25 + webapp/src/app/api/model/userRole 2.ts | 19 + .../accounts/account-dialog.component 2.html | 71 ++ .../accounts/account-dialog.component 2.scss | 22 + .../accounts/account-dialog.component 2.ts | 153 +++ .../accounts/accounts.component 2.html | 146 +++ .../accounts/accounts.component 2.scss | 147 +++ .../modules/accounts/accounts.component 2.ts | 247 ++++ .../organizations.component 2.html | 105 ++ .../organizations.component 2.scss | 130 ++ .../organizations.component 2.ts | 158 +++ .../person-publications.component.ts | 40 +- .../app/shared/guards/super-admin.guard 2.ts | 31 + .../services/account-management.service 2.ts | 117 ++ .../organization-management.service 2.ts | 75 ++ .../app/shared/services/ui-focus.service 2.ts | 14 + 56 files changed, 6226 insertions(+), 816 deletions(-) create mode 100644 service/src/data/predefined_accounts 2.json create mode 100644 service/src/main/inse/account_management/__init__ 2.py create mode 100644 service/src/main/inse/account_management/model 2.py create mode 100644 service/src/main/inse/account_management/router 2.py create mode 100644 service/src/main/inse/account_management/service 2.py create mode 100644 service/src/main/inse/auth/__init__ 2.py create mode 100644 service/src/main/inse/auth/email_service 2.py create mode 100644 service/src/main/inse/auth/model 2.py create mode 100644 service/src/main/inse/auth/router 2.py create mode 100644 service/src/main/inse/auth/service 2.py create mode 100644 service/src/main/inse/auth/test_auth_service 2.py create mode 100644 service/src/main/inse/organization_management/__init__ 2.py create mode 100644 service/src/main/inse/organization_management/model 2.py create mode 100644 service/src/main/inse/organization_management/router 2.py create mode 100644 service/src/main/inse/organization_management/service 2.py create mode 100644 service/src/main/inse/organization_management/test_service 2.py create mode 100644 webapp/src/app/api/api/auth.service 2.ts create mode 100644 webapp/src/app/api/model/accessResponse 2.ts create mode 100644 webapp/src/app/api/model/accessToken 2.ts create mode 100644 webapp/src/app/api/model/accountPage 2.ts create mode 100644 webapp/src/app/api/model/accountProfile 2.ts create mode 100644 webapp/src/app/api/model/bodyChangePassword 2.ts create mode 100644 webapp/src/app/api/model/bodyGetAccessToken 2.ts create mode 100644 webapp/src/app/api/model/bodyLogin 2.ts create mode 100644 webapp/src/app/api/model/bodyRequestOtk 2.ts create mode 100644 webapp/src/app/api/model/createAccountRequest 2.ts create mode 100644 webapp/src/app/api/model/idToken 2.ts create mode 100644 webapp/src/app/api/model/loginResponse 2.ts create mode 100644 webapp/src/app/api/model/refreshToken 2.ts create mode 100644 webapp/src/app/api/model/tokenType 2.ts create mode 100644 webapp/src/app/api/model/updateAccountRequest 2.ts create mode 100644 webapp/src/app/api/model/userRole 2.ts create mode 100644 webapp/src/app/modules/accounts/account-dialog.component 2.html create mode 100644 webapp/src/app/modules/accounts/account-dialog.component 2.scss create mode 100644 webapp/src/app/modules/accounts/account-dialog.component 2.ts create mode 100644 webapp/src/app/modules/accounts/accounts.component 2.html create mode 100644 webapp/src/app/modules/accounts/accounts.component 2.scss create mode 100644 webapp/src/app/modules/accounts/accounts.component 2.ts create mode 100644 webapp/src/app/modules/organizations/organizations.component 2.html create mode 100644 webapp/src/app/modules/organizations/organizations.component 2.scss create mode 100644 webapp/src/app/modules/organizations/organizations.component 2.ts create mode 100644 webapp/src/app/shared/guards/super-admin.guard 2.ts create mode 100644 webapp/src/app/shared/services/account-management.service 2.ts create mode 100644 webapp/src/app/shared/services/organization-management.service 2.ts create mode 100644 webapp/src/app/shared/services/ui-focus.service 2.ts diff --git a/service/src/data/predefined_accounts 2.json b/service/src/data/predefined_accounts 2.json new file mode 100644 index 00000000..b6bf36da --- /dev/null +++ b/service/src/data/predefined_accounts 2.json @@ -0,0 +1,29 @@ +{ + "organizations": [ + { + "id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c", + "name": "The Super Admin Organization" + }, + { + "name": "Universität Duisburg-Essen", + "openalex_instution_id": "https://openalex.org/I62318514" + }, + { + "name": "Ruhr-Universität Bochum", + "openalex_instution_id": "https://openalex.org/I904495901" + }, + { + "name": "TU Dortmund", + "openalex_instution_id": "https://openalex.org/I200332995" + } + ], + "accounts": [ + { + "email": "super@admin.com", + "password": "superadmin", + "name": "Super Admin", + "organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c", + "role": "SUPER_ADMIN" + } + ] +} diff --git a/service/src/main/inse/account_management/__init__ 2.py b/service/src/main/inse/account_management/__init__ 2.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/service/src/main/inse/account_management/__init__ 2.py @@ -0,0 +1 @@ + diff --git a/service/src/main/inse/account_management/model 2.py b/service/src/main/inse/account_management/model 2.py new file mode 100644 index 00000000..2bb7613d --- /dev/null +++ b/service/src/main/inse/account_management/model 2.py @@ -0,0 +1,51 @@ +import uuid +from typing import List, Optional + +from pydantic import BaseModel, Field + +from inse.auth.model import UserRole + + +class OrganizationProfile(BaseModel): + id: uuid.UUID + name: str + openalex_institution_id: Optional[str] = None + + +class AccountProfile(BaseModel): + id: uuid.UUID + email: str + name: str + role: UserRole + organization_id: uuid.UUID + organization_name: str + deleted: bool + is_current: bool = False + is_real_account: bool = False + is_impersonating: bool = False + + +class AccountPage(BaseModel): + items: List[AccountProfile] + total: int + page: int + page_size: int + + +class CreateAccountRequest(BaseModel): + email: str = Field(min_length=3) + name: str = Field(min_length=1) + role: UserRole = UserRole.USER + organization_id: uuid.UUID + password: str = Field(min_length=8) + openalex_person_id: Optional[str] = None + + +class UpdateAccountRequest(BaseModel): + email: Optional[str] = Field(default=None, min_length=3) + name: Optional[str] = Field(default=None, min_length=1) + role: Optional[UserRole] = None + organization_id: Optional[uuid.UUID] = None + password: Optional[str] = Field(default=None, min_length=8) + openalex_person_id: Optional[str] = None + deleted: Optional[bool] = None diff --git a/service/src/main/inse/account_management/router 2.py b/service/src/main/inse/account_management/router 2.py new file mode 100644 index 00000000..82781fb0 --- /dev/null +++ b/service/src/main/inse/account_management/router 2.py @@ -0,0 +1,125 @@ +import uuid +from typing import Optional + +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.database import get_session +from inse.tags import Tags + +from . import service +from .model import ( + AccountPage, + AccountProfile, + CreateAccountRequest, + OrganizationProfile, + UpdateAccountRequest, +) + +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, +) -> AccountProfile: + return service.get_current_account(session=session, access_token=access_token) + + +@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, +) -> AccountPage: + return service.list_accounts( + session=session, + access_token=access_token, + page=page, + page_size=page_size, + offset=offset, + search=search, + organization_id=organization_id, + ) + + +@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, +) -> AccountProfile: + return service.create_account( + session=session, + access_token=access_token, + payload=payload, + ) + + +@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, +) -> list[OrganizationProfile]: + return service.list_organizations(session=session, access_token=access_token) + + +@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, +) -> AccountProfile: + return service.update_account( + session=session, + access_token=access_token, + account_id=account_id, + payload=payload, + ) + + +@router.delete( + "/{account_id}", + operation_id="deleteAccount", + status_code=status.HTTP_204_NO_CONTENT, +) +async def delete_account( + account_id: uuid.UUID, + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> Response: + service.delete_account( + session=session, + access_token=access_token, + account_id=account_id, + ) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/service/src/main/inse/account_management/service 2.py b/service/src/main/inse/account_management/service 2.py new file mode 100644 index 00000000..5ef45372 --- /dev/null +++ b/service/src/main/inse/account_management/service 2.py @@ -0,0 +1,311 @@ +import uuid +from typing import Optional + +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 .model import ( + AccountPage, + AccountProfile, + CreateAccountRequest, + OrganizationProfile, + UpdateAccountRequest, +) + + +def _is_admin(role: UserRole) -> bool: + return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN} + + +def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool: + if editor_role == UserRole.SUPER_ADMIN: + return True + if editor_role == UserRole.ADMIN: + return role in {UserRole.MANAGER, UserRole.USER} + return False + + +def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: + organization_name = account.organization.name if account.organization else "" + return AccountProfile( + id=account.id, + email=account.email, + name=account.name, + role=account.role, + organization_id=account.organization_id, + organization_name=organization_name, + deleted=account.deleted, + is_current=account.id == token.effective_account_id, + is_real_account=account.id == token.real_account_id, + is_impersonating=token.is_impersonating(), + ) + + +def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account: + account = session.get(Account, account_id) + if account is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Account not found.", + ) + return account + + +def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None: + if token.effective_role == UserRole.SUPER_ADMIN: + return + if ( + token.effective_role == UserRole.ADMIN + and account.organization_id == token.effective_organization_id + ): + return + if account.id == token.effective_account_id: + return + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is outside your scope.", + ) + + +def _ensure_email_available( + session: Session, + email: str, + excluded_account_id: Optional[uuid.UUID] = None, +) -> None: + normalized_email = email.lower().strip() + if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Invalid email address.", + ) + + statement = select(Account).where(Account.email == normalized_email) + if excluded_account_id is not None: + statement = statement.where(Account.id != excluded_account_id) + + existing = session.exec(statement).first() + if existing is not None: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Email address is already used by another account.", + ) + + +def get_current_account(session: Session, access_token: AccessToken) -> 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, + page: int, + page_size: int, + offset: Optional[int] = None, + search: Optional[str] = None, + organization_id: Optional[uuid.UUID] = None, +) -> AccountPage: + if not _is_admin(access_token.effective_role): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only admins can list accounts.", + ) + + statement = select(Account) + count_statement = select(func.count()).select_from(Account) + + filters = [] + if access_token.effective_role == UserRole.ADMIN: + filters.append(Account.organization_id == access_token.effective_organization_id) + elif organization_id is not None: + filters.append(Account.organization_id == organization_id) + + if search: + pattern = f"%{search.lower().strip()}%" + filters.append( + or_( + func.lower(Account.name).like(pattern), + func.lower(Account.email).like(pattern), + ) + ) + + for filter_expression in filters: + statement = statement.where(filter_expression) + count_statement = count_statement.where(filter_expression) + + total = session.exec(count_statement).one() + effective_offset = offset if offset is not None else page * page_size + accounts = session.exec( + statement.order_by(Account.name).offset(effective_offset).limit(page_size) + ).all() + + return AccountPage( + items=[_account_to_profile(account, access_token) for account in accounts], + total=total, + page=page, + page_size=page_size, + ) + + +def create_account( + session: Session, + access_token: AccessToken, + payload: CreateAccountRequest, +) -> AccountProfile: + if not _is_admin(access_token.effective_role): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only admins can create accounts.", + ) + + if ( + access_token.effective_role == UserRole.ADMIN + and payload.organization_id != access_token.effective_organization_id + ): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Admins can only create accounts in their own organization.", + ) + + if not _role_allowed_for_editor(access_token.effective_role, payload.role): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="You cannot assign this role.", + ) + + organization = session.get(Organization, payload.organization_id) + if organization is None or organization.deleted: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Organization not found.", + ) + + email = payload.email.lower().strip() + _ensure_email_available(session, email) + + account = Account( + email=email, + name=payload.name.strip(), + role=payload.role, + organization_id=payload.organization_id, + password_hash=auth_service._hash_password(payload.password), + openalex_person_id=payload.openalex_person_id, + ) + session.add(account) + session.commit() + session.refresh(account) + return _account_to_profile(account, access_token) + + +def list_organizations( + session: Session, + access_token: AccessToken, +) -> list[OrganizationProfile]: + if access_token.effective_role == UserRole.SUPER_ADMIN: + organizations = session.exec( + select(Organization) + .where(Organization.deleted == False) # noqa: E712 + .order_by(Organization.name) + ).all() + elif access_token.effective_role == UserRole.ADMIN: + organization = session.get(Organization, access_token.effective_organization_id) + organizations = [organization] if organization and not organization.deleted else [] + else: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + + return [ + OrganizationProfile( + id=organization.id, + name=organization.name, + openalex_institution_id=organization.openalex_institution_id, + ) + for organization in organizations + ] + + +def update_account( + session: Session, + access_token: AccessToken, + account_id: uuid.UUID, + payload: UpdateAccountRequest, +) -> AccountProfile: + account = _get_account_or_404(session, account_id) + _ensure_account_in_editor_scope(account, access_token) + + is_self_update = account.id == access_token.effective_account_id + can_admin_update = _is_admin(access_token.effective_role) + + if not can_admin_update and not is_self_update: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + + if payload.email is not None: + email = payload.email.lower().strip() + _ensure_email_available(session, email, excluded_account_id=account.id) + account.email = email + + if payload.name is not None: + account.name = payload.name.strip() + + if payload.password is not None: + account.password_hash = auth_service._hash_password(payload.password) + account.epoch += 1 + + if payload.openalex_person_id is not None: + account.openalex_person_id = payload.openalex_person_id + + if payload.role is not None: + if not can_admin_update: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + if not _role_allowed_for_editor(access_token.effective_role, payload.role): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="You cannot assign this role.", + ) + account.role = payload.role + account.epoch += 1 + + if payload.organization_id is not None: + if access_token.effective_role != UserRole.SUPER_ADMIN: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + organization = session.get(Organization, payload.organization_id) + if organization is None or organization.deleted: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Organization not found.", + ) + account.organization_id = payload.organization_id + account.epoch += 1 + + if payload.deleted is not None: + if not can_admin_update or is_self_update: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + account.deleted = payload.deleted + account.epoch += 1 + + session.add(account) + session.commit() + session.refresh(account) + return _account_to_profile(account, access_token) + + +def delete_account( + session: Session, + access_token: AccessToken, + account_id: uuid.UUID, +) -> None: + account = _get_account_or_404(session, account_id) + _ensure_account_in_editor_scope(account, access_token) + + if ( + not _is_admin(access_token.effective_role) + or account.id == access_token.effective_account_id + ): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + + account.deleted = True + account.epoch += 1 + session.add(account) + session.commit() diff --git a/service/src/main/inse/auth/__init__ 2.py b/service/src/main/inse/auth/__init__ 2.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/auth/email_service 2.py b/service/src/main/inse/auth/email_service 2.py new file mode 100644 index 00000000..85ef913c --- /dev/null +++ b/service/src/main/inse/auth/email_service 2.py @@ -0,0 +1,29 @@ +import smtplib +from email.message import EmailMessage + + +def send_email( + recipient: str, + subject: str, + body: str, + smtp_server: str = "localhost", + smtp_port: int = 25, + sender: str = "no-reply@smartguide.local", + username: str | None = None, + password: str | None = None, + use_tls: bool = False, +): + msg = EmailMessage() + msg["From"] = sender + msg["To"] = recipient + msg["Subject"] = subject + msg.set_content(body) + + with smtplib.SMTP(smtp_server, smtp_port) as server: + if use_tls: + server.starttls() + + if username and password: + server.login(username, password) + + server.send_message(msg) diff --git a/service/src/main/inse/auth/model 2.py b/service/src/main/inse/auth/model 2.py new file mode 100644 index 00000000..a79aa113 --- /dev/null +++ b/service/src/main/inse/auth/model 2.py @@ -0,0 +1,212 @@ +import uuid +from datetime import datetime +from enum import StrEnum +from typing import List + +from pydantic import BaseModel +from sqlmodel import Field, Relationship, SQLModel + + +class UserRole(StrEnum): + SUPER_ADMIN = "SUPER_ADMIN" + ADMIN = "ADMIN" + MANAGER = "MANAGER" + USER = "USER" + + +class TokenType(StrEnum): + ID_TOKEN = "ID" + REFRESH_TOKEN = "REFRESH" + ACCESS_TOKEN = "ACCESS" + + +class Durable(SQLModel): + deleted: bool = Field( + default=False, + nullable=False, + index=True, + description="Indicates whether the record is marked as deleted.", + ) + + +class Organization(Durable, table=True): + id: uuid.UUID | None = Field( + default_factory=uuid.uuid4, + primary_key=True, + description="Unique identifier for the organization. Generated automatically if not provided.", + ) + name: str = Field( + index=True, + unique=True, + nullable=False, + description="The unique name of the organization.", + ) + openalex_institution_id: str | None = Field( + default=None, + index=True, + description="The OpenAlex ID of the institution associated with the organization.", + ) + + accounts: List["Account"] = Relationship(back_populates="organization") + + +class Account(Durable, table=True): + id: uuid.UUID | None = Field( + default_factory=uuid.uuid4, + primary_key=True, + description="Unique identifier for the account. Generated automatically if not provided.", + ) + email: str = Field( + index=True, + unique=True, + nullable=False, + description="The email address associated with the account.", + ) + name: str = Field( + index=True, + nullable=False, + description="The name of the account holder.", + ) + openalex_person_id: str | None = Field( + default=None, + index=True, + description="The OpenAlex ID of the person associated with the account.", + ) + epoch: int = Field( + default=0, + nullable=False, + description="The epoch value for the account. Used for versioning of tokens.", + ) + password_hash: str = Field( + index=False, + nullable=False, + description="The hashed password for the account using Argon2id algorithm.", + # https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + ) + + organization_id: uuid.UUID = Field( + foreign_key="organization.id", + nullable=False, + description="The unique identifier of the organization strictly associated with this account.", + ) + role: UserRole = Field( + default=UserRole.USER, + index=True, + nullable=False, + description="The specific role this account holds within its organization.", + ) + + organization: Organization = Relationship(back_populates="accounts") + + +class Secret(SQLModel, table=True): + id: uuid.UUID | None = Field( + default_factory=uuid.uuid4, + primary_key=True, + description="Unique identifier for the secret. Generated automatically if not provided.", + ) + account_id: uuid.UUID = Field( + foreign_key="account.id", + unique=True, # Ensure that each account can have only one associated secret + nullable=False, + description="The unique identifier of the account associated with this secret.", + ) + secret_value: str = Field( + index=False, + nullable=False, + description="The actual secret value. This should be stored securely and encrypted.", + ) + expires_at: datetime = Field( + index=True, + nullable=False, + description="The timestamp indicating when the secret will expire.", + ) + + +class Token(BaseModel): + token_type: TokenType = Field( + description="The type of the token (ID, Refresh, or Access).", + ) + 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): + token_type: TokenType = Field( + default=TokenType.ID_TOKEN, + const=True, + description="The type of the token, which is always ID_TOKEN for this class.", + ) + + +class AccessToken(Token): + token_type: TokenType = Field( + default=TokenType.ACCESS_TOKEN, + const=True, + description="The type of the token, which is always ACCESS_TOKEN for this class.", + ) + 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.", + ) + + def is_impersonating(self) -> bool: + """Determine if the access token is being used for impersonation. + + Returns: + bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise. + """ + return self.effective_account_id != self.real_account_id + + +class RefreshToken(AccessToken): + token_type: TokenType = Field( + default=TokenType.REFRESH_TOKEN, + const=True, + description="The type of the token, which is always REFRESH_TOKEN for this class.", + ) + + +class LoginResponse(BaseModel): + id_token: IdToken = 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." + ) diff --git a/service/src/main/inse/auth/router 2.py b/service/src/main/inse/auth/router 2.py new file mode 100644 index 00000000..2ce4f52a --- /dev/null +++ b/service/src/main/inse/auth/router 2.py @@ -0,0 +1,162 @@ +import logging +from typing import Annotated +import uuid + +from fastapi import APIRouter, Body, Depends, Response, status +from sqlmodel import Session + +from inse.tags import Tags + +import inse.auth.service as auth_service +from inse.database import SessionDep, get_session +from inse.auth.model import ( + AccessResponse, + AccessToken, + IdToken, + LoginResponse, + RefreshToken, +) + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH]) + + +@router.get("/health") +async def health_check(): + return {"status": "ok"} + + +@router.post( + "/request-otk", + summary="Request One-Time Key", + description="Request a one-time key (OTK) for authentication using email and password.", + operation_id="requestOtk", + responses={ + status.HTTP_200_OK: {"description": "One-time key requested successfully."} + }, +) +async def request_otk( + session: SessionDep, + email: Annotated[str, Body(description="User's email address")], + password: Annotated[str, Body(description="User's password")], +): + return auth_service.request_otk(session=session, email=email, password=password) + + +@router.post( + "/login", + summary="Login with One-Time Key", + description="Login using a one-time key (OTK) sent to the user's email.", + operation_id="login", + responses={status.HTTP_200_OK: {"description": "Login successful."}}, +) +async def login( + session: SessionDep, + response: Response, + account_id: Annotated[uuid.UUID, Body(description="User's account ID")], + email_code: Annotated[ + str, Body(embed=True, description="One-time code sent to user's email") + ], +) -> LoginResponse: + return auth_service.login( + session=session, response=response, account_id=account_id, email_code=email_code + ) + + +@router.post( + "/access", + summary="Get Access Token", + description="Retrieve an access token for the authenticated user.", + operation_id="getAccessToken", + responses={ + status.HTTP_200_OK: {"description": "Access token retrieved successfully."} + }, +) +async def get_action_tokens( + response: Response, + session: SessionDep, + real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")], + effective_account_id: Annotated[ + uuid.UUID, Body(description="Effective account ID for the access token") + ], + id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], +) -> AccessResponse: + logger.debug( + "Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s", + real_account_id, + effective_account_id, + id_token, + ) + + return auth_service.get_access_token( + response=response, + session=session, + real_account_id=real_account_id, + effective_account_id=effective_account_id, + id_token=id_token, + ) + + +@router.post( + "/refresh", + summary="Refresh Access Token", + description="Refresh the access token using a valid refresh token.", + operation_id="refreshAccessToken", + responses={ + status.HTTP_200_OK: {"description": "Access token refreshed successfully."} + }, +) +async def refresh_access_token( + refresh_token: Annotated[ + RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep + ], +) -> AccessToken: + return auth_service.refresh_access_token(refresh_token=refresh_token) + + +@router.post( + "/logout", + summary="Logout", + description="Logout the authenticated user.", + operation_id="logout", + responses={status.HTTP_200_OK: {"description": "Logout successful."}}, +) +async def logout( + session: Annotated[Session, Depends(get_session)], + access_token: Annotated[ + AccessToken, + auth_service.CurrentUserAccessTokenPayloadDep, + ], +): + return auth_service.logout(session=session, access_token=access_token) + + +@router.post( + "/change-password", + summary="Change Password", + description="Change the user's password and invalidate existing tokens.", + operation_id="changePassword", + responses={status.HTTP_200_OK: {"description": "Password changed successfully."}}, +) +async def change_password( + session: Annotated[Session, Depends(get_session)], + current_password: Annotated[ + str, + Body(description="Current password"), + ], + new_password: Annotated[ + str, + Body(description="New password", min_length=8), + ], + access_token: Annotated[ + AccessToken, + auth_service.CurrentUserAccessTokenPayloadDep, + ], +): + return auth_service.change_password( + session=session, + access_token=access_token, + current_password=current_password, + new_password=new_password, + ) diff --git a/service/src/main/inse/auth/service 2.py b/service/src/main/inse/auth/service 2.py new file mode 100644 index 00000000..ff9e518f --- /dev/null +++ b/service/src/main/inse/auth/service 2.py @@ -0,0 +1,1076 @@ +import datetime +import hashlib +import json +import logging +import secrets +import uuid +from typing import Annotated, Any, Dict, Literal, Optional + +import jwt +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError +from fastapi import Depends, HTTPException, Request, Response, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from inse.auth.model import ( + AccessResponse, + AccessToken, + Account, + IdToken, + LoginResponse, + Organization, + RefreshToken, + Secret, + TokenType, + UserRole, +) +from inse.config import get_settings +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 + +OTK_EXPIRATION_MINUTES = 15 # 15 minutes + +REAL_ACCOUNT_ID_KEY = "real_account_id" +EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id" +EFFECTIVE_ROLE_KEY = "effective_role" +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" + +settings = get_settings() + +logger = logging.getLogger(__name__) + +security_scheme = HTTPBearer() + +_password_hasher = PasswordHasher() + +AccountNotFoundException = HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Account not found.", +) + + +def create_predefined_accounts(session: Session, file_path: str): + """Creates predefined accounts and organizations in the database from a JSON file. This function is intended to be used for development and testing purposes, and it will not run in a production environment. + + Args: + session (Session): The database session used to add the predefined accounts and organizations. + file_path (str): The path to the JSON file containing the predefined accounts and organizations. + """ + + if settings.environment == "prod": + logger.info( + "Skipping predefined accounts population in production environment." + ) + return + + account_count = session.exec(select(func.count()).select_from(Account)).one() + if account_count > 0: + logger.info( + "Skipping predefined accounts population as accounts already exist in the database." + ) + return + + try: + with open(file_path, "r") as file: + data: Dict[str, Any] = json.loads(file.read()) + for organization_data in data.get("organizations", []): + organization_id = organization_data.get("id") + if organization_id is not None: + organization_id = uuid.UUID(organization_id) + organization_name = organization_data["name"] + organization = Organization(id=organization_id, name=organization_name) + session.add(organization) + for account_data in data.get("accounts", []): + organization_id = uuid.UUID(account_data["organization_id"]) + role = UserRole(account_data["role"]) + email = account_data["email"] + password_hash = _hash_password(account_data["password"]) + account = Account( + email=email, + name=account_data["name"], + organization_id=organization_id, + role=role, + password_hash=password_hash, + epoch=0, + ) + session.add(account) + + session.commit() + logger.info("Predefined accounts and organizations populated successfully.") + except FileNotFoundError: + logger.error( + "Predefined accounts file not found at %s. Skipping population.", + file_path, + ) + except Exception as e: + logger.exception( + "Error occurred while populating predefined accounts: %s. Skipping population.", + str(e), + ) + + +def _hash_password(password: str) -> str: + """Hashes the provided password using Argon2 and returns the hashed value. + + Args: + password (str): The password to hash. + + Returns: + str: The hashed password. + """ + return _password_hasher.hash(password) + + +def _verify_password(password: str, password_hash: str) -> bool: + """Verifies the provided password against the stored password hash using Argon2. + + Args: + password (str): The password to verify. + password_hash (str): The stored password hash to verify against. + + Returns: + bool: True if the password is correct, False otherwise. + """ + try: + return _password_hasher.verify(password_hash, password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + return False + + +def request_otk(session: Session, email: str, password: str): + """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: + session (Session): The database session used to query the account and secret. + email (str): The user's email address. + password (str): The user's password. + + + Raises: + HTTPException: If the email or password is invalid. + HTTPException: If the account is not found. + """ + email = email.lower().strip() + + logger.debug("OTK request for email %s: starting validation", email) + account = session.exec( + select(Account).where( + Account.email == email, + Account.deleted == False, # noqa: E712 + ) + ).first() + + logger.debug("OTK request for email %s: account found: %s", email, account) + + 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, + detail="Invalid email or password", + ) + + if not _verify_password(password, account.password_hash): + logger.warning( + "OTK request failed for email %s: password verification failed", email + ) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid email or password", + ) + + otk_code = f"{secrets.randbelow(1_000_000):06d}" + print(otk_code) + + secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first() + + expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( + minutes=OTK_EXPIRATION_MINUTES + ) + + if secret is None: + secret = Secret( + account_id=account.id, + secret_value=otk_code, + expires_at=expires_at, + ) + session.add(secret) + else: + secret.secret_value = otk_code + secret.expires_at = expires_at + + session.commit() + + if settings.send_otk_email: + send_email( + recipient=account.email, + subject="Your SmartGUIDE login code", + body=f"Your login code is: {otk_code}", + smtp_server=settings.smtp_server, + smtp_port=settings.smtp_port, + sender=settings.smtp_sender, + username=settings.smtp_username, + password=settings.smtp_password, + use_tls=settings.smtp_use_tls, + ) + logger.info("Sent OTK email for account %s", account.id) + elif settings.environment == "dev": + logger.info("OTK code for account %s: %s", account.id, otk_code) + else: + logger.info("OTK generated for account %s", account.id) + + return {"status": "ok", "account_id": str(account.id)} + + +def login( + session: Session, response: Response, account_id: uuid.UUID, email_code: str +) -> LoginResponse: + """Login using a one-time key (OTK) sent to the user's email. Validates the OTK and generates an ID token for the user. + + Args: + session (Session): The database session used to query the account and secret. + response (Response): The response object to set the ID token cookie. + account_id (uuid.UUID): The unique identifier of the account associated with the one-time code. + email_code (str): The one-time code sent to the user's email. + + Raises: + HTTPException: If the code is invalid or expired. + HTTPException: If the account is not active. + + Returns: + LoginResponse: The response containing the ID token issued upon successful login. + """ + now = datetime.datetime.now(datetime.timezone.utc) + + secret = session.exec( + select(Secret).where( + Secret.account_id == account_id, + Secret.secret_value == email_code, + # Validating the code and ensuring it matches the account ID + ) + ).first() + + if not settings.skip_otk_validation: + if secret is None: + logger.warning("Login failed: invalid or expired code %s", email_code) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired code", + ) + + secret_expires = secret.expires_at + if getattr(secret_expires, "tzinfo", None) is None: + secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc) + + if secret_expires <= now: + logger.warning("Login failed: invalid or expired code %s", email_code) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired code", + ) + session.delete(secret) + + else: + if settings.environment == "prod": + logger.warning( + "Skipping OTK validation in production environment for account %s.", + account_id, + ) + else: + logger.warning( + "Skipping OTK validation for account %s due to configuration setting.", + account_id, + ) + + account = _get_active_account(session, account_id) + if not account or account.deleted or account.id is None: + logger.warning("Login failed: account is not active %s", account_id) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) + + id_token = _build_id_token( + response, + account.id, + account.epoch, + ) + + session.commit() + + return LoginResponse(id_token=id_token) + + +def _get_current_user_access_token_payload( + session: Annotated[Session, Depends(get_session)], + request: Request, + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], +) -> AccessToken: + """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: + session (Annotated[Session, Depends): The database session used to query the account and secret. + request (Request): The request object containing the access token. + credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the access token. + + Returns: + AccessToken: The verified access token payload. + """ + + token = credentials.credentials + + access_token_payload = _verify_fp_token( + request=request, + cookie_key=ACT_FP_COOKIE_KEY, + token=token, + session=session, + ) + # If reaches here, the access token is valid and the fingerprint matches + + return AccessToken( + 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( + access_token_payload["exp"], tz=datetime.timezone.utc + ), + epoch=access_token_payload[EPOCH_KEY], + effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]), + effective_organization_id=uuid.UUID( + 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: + """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: + session (Annotated[Session, Depends): The database session used to query the account and secret. + request (Request): The request object containing the refresh token. + credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token. + + Returns: + RefreshToken: The verified refresh token payload. + """ + token = credentials.credentials + + refresh_token_payload = _verify_fp_token( + request=request, + cookie_key=ACT_FP_COOKIE_KEY, + token=token, + session=session, + ) + # If reaches here, the refresh token is valid and the fingerprint matches + refresh_token = RefreshToken( + 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( + refresh_token_payload["exp"], tz=datetime.timezone.utc + ), + epoch=refresh_token_payload[EPOCH_KEY], + effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]), + 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) + + return refresh_token + + +def _get_current_user_id_token_payload( + session: Annotated[Session, Depends(get_session)], + request: Request, + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], +) -> IdToken: + """Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. + + Args: + session (Annotated[Session, Depends): The database session used to query the account and secret. + request (Request): The request object containing the ID token. + credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the ID token. + + 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) + + id_token_payload = _verify_fp_token( + request=request, + cookie_key=ID_FP_COOKIE_KEY, + token=token, + session=session, + ) + # If reaches here, the ID token is valid and the fingerprint matches + + return IdToken( + 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, + ) + + +CurrentUserAccessTokenPayloadDep = Depends(_get_current_user_access_token_payload) +CurrentUserRefreshTokenPayloadDep = Depends(_get_current_user_refresh_token_payload) +CurrentUserIdTokenPayloadDep = Depends(_get_current_user_id_token_payload) + + +def _get_account_epoch( + session: Session, + account_id: uuid.UUID, +) -> int: + """Retrieves the current epoch value for the specified account ID, ensuring that the account exists and is not deleted. + + Args: + session (Session): The database session used to query the account. + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch. + + Raises: + HTTPException: If the account does not exist, is deleted, or has no valid ID. + + Returns: + int: The current epoch value for the account. + """ + account = session.get(Account, account_id) + + if account is None or account.deleted or account.id is None: + raise AccountNotFoundException + + return account.epoch + + +def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole: + """Retrieves the role for the given account ID. + + Args: + session (Session): The database session. + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role. + + Returns: + UserRole: The role associated with the given account ID. + """ + account = session.get(Account, account_id) + + if not account or account.deleted or account.id is None: + raise AccountNotFoundException + + return account.role + + +def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID: + """Retrieves the organization ID for the given account ID. + + Args: + session (Session): The database session. + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the organization ID. + + Returns: + uuid.UUID: The organization ID associated with the given account ID. + """ + account = session.get(Account, account_id) + + if not account or account.deleted or account.id is None: + raise AccountNotFoundException + + return account.organization_id + + +def _is_valid_impersonation( + session: Session, real_account_id: uuid.UUID, effective_account_id: uuid.UUID +) -> bool: + """Checks if the real account is allowed to impersonate the effective account. + + Args: + session (Session): The database session. + real_account_id (uuid.UUID): The unique identifier of the real account. + effective_account_id (uuid.UUID): The unique identifier of the effective account. + + Returns: + bool: True if impersonation is allowed, False otherwise. + """ + real_account = session.get(Account, real_account_id) + if not real_account or real_account.deleted or real_account.id is None: + raise AccountNotFoundException + effective_account = session.get(Account, effective_account_id) + if ( + not effective_account + or effective_account.deleted + or effective_account.id is None + ): + raise AccountNotFoundException + + if real_account.role == UserRole.SUPER_ADMIN: + return True # Super admins can impersonate any account + + if real_account.organization_id != effective_account.organization_id: + return False # Cannot impersonate accounts from different organizations + + if real_account.role == UserRole.ADMIN and effective_account.role in [ + UserRole.MANAGER, + UserRole.USER, + ]: + return True # Admins can impersonate managers and users within the same organization + + # if ( + # real_account.role == UserRole.MANAGER + # and effective_account.role == UserRole.USER + # ): + # return True # Managers can impersonate users within the same organization + # # They can't tho? + + return False + + +def get_access_token( + response: Response, + session: Session, + id_token: IdToken, + 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: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Real account ID does not match ID token", + ) + + # The new frontend explicitly sends the real account as the effective account. + # That is self-access, not impersonation; otherwise normal login fails for users + # because they do not have impersonation permissions. + 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", + ) + + role = _get_account_role(session=session, account_id=effective_account_id) + epoch = _get_account_epoch(account_id=effective_account_id, session=session) + organization_id = _get_account_organization( + session=session, account_id=effective_account_id + ) + + user_fingerprint_hash = _set_act_fp_cookie(response=response) + + access_token = _build_access_token( + 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, + ) + refresh_token = _build_refresh_token( + 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. + + 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, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 + ) + + +def _set_act_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, + value=user_fingerprint, + httponly=True, + secure=secure, + samesite="strict", + max_age=max_age, + ) + return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() + + +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. + session (Session): The database session. + refresh_token (RefreshToken): The refresh token to verify. + + Returns: + AccessToken: The refreshed access token. + """ + # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. + + return _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. + + return _build_access_token( + real_account_id=refresh_token.real_account_id, + effective_account_id=refresh_token.effective_account_id, + 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, + ) + + +def _build_id_token( + response: Response, + real_account_id: uuid.UUID, + epoch: int, +) -> IdToken: + """Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + real_account_id (uuid.UUID): The UUID of the real account. + expires_at (datetime.datetime): The expiration time for the token. + epoch (int): The epoch value for the tokens. + + Returns: + IdToken: The generated ID token object. + """ + 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( + 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( + 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: + """Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + real_account_id (uuid.UUID): The UUID of the real account. + effective_account_id (uuid.UUID): The UUID of the effective account. + effective_role (UserRole): The role of the effective account. + effective_organization_id (uuid.UUID): The UUID of the organization associated with the effective account. + epoch (int): The epoch value for the tokens. + user_fingerprint_hash (str): The hashed value of the user's fingerprint. + + Returns: + RefreshToken: The generated refresh token object. + """ + expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( + minutes=REFRESH_TOKEN_EXPIRATION_MINUTES + ) + payload = { + REAL_ACCOUNT_ID_KEY: str(real_account_id), + EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id), + 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( + payload=payload, + expiration_datetime=expires_at, + token_type=TokenType.REFRESH_TOKEN, + ) + + return RefreshToken( + 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, + ) + + +def _build_access_token( + real_account_id: uuid.UUID, + effective_account_id: uuid.UUID, + effective_role: UserRole, + effective_organization_id: uuid.UUID, + epoch: int, + user_fingerprint_hash: str, +) -> AccessToken: + """Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + real_account_id (uuid.UUID): The UUID of the real account. + effective_account_id (uuid.UUID): The UUID of the effective account. + effective_role (UserRole): The role of the effective account. + effective_organization_id (uuid.UUID): The UUID of the organization associated with the effective account. + epoch (int): The epoch value for the tokens. + user_fingerprint_hash (str): The hashed value of the user's fingerprint. + + Returns: + AccessToken: The generated access token object. + """ + expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( + minutes=ACCESS_TOKEN_EXPIRATION_MINUTES + ) + payload = { + REAL_ACCOUNT_ID_KEY: str(real_account_id), + EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id), + 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( + payload=payload, + expiration_datetime=expires_at, + token_type=TokenType.ACCESS_TOKEN, + ) + + return AccessToken( + 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, + ) + + +def _build_token( + payload: Dict[str, Any], + expiration_datetime: datetime.datetime, + token_type: TokenType, +) -> str: + """Builds a JWT token with the given payload and expiration time. + + Args: + payload (Dict[str, Any]): The payload to encode in the JWT. + expiration_datetime (datetime.datetime): The expiration time for the token. + token_type (TokenType): The type of the token to build. + + Returns: + str: The encoded JWT token. + """ + now = datetime.datetime.now(datetime.timezone.utc) + payload.update( + { + "exp": expiration_datetime, + "iss": settings.token_issuer_id, + "iat": now, + "nbf": now, + "type": token_type.value, + } + ) + if not settings.token_hmac_key: + raise ValueError("Token HMAC key is not set in the configuration.") + token = jwt.encode(payload, settings.token_hmac_key, algorithm="HS256") + 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. + + 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. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the fingerprint cookie is missing or does not match the token's fingerprint. + 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 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() + + try: + payload = jwt.decode( + token, + settings.token_hmac_key, + algorithms=["HS256"], + 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) + if effective_account_id: + epoch_account_id = uuid.UUID(effective_account_id) + + current_account_epoch = _get_account_epoch( + session=session, + account_id=epoch_account_id, + ) + + token_epoch = payload.get(EPOCH_KEY) + if token_epoch is None or token_epoch != current_account_epoch: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token epoch mismatch", + ) + + return payload + + except jwt.ExpiredSignatureError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token has expired", + ) + except jwt.InvalidTokenError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid token", + ) + + +def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: + """Gets the active account for the given account ID, ensuring that the account exists and is not deleted. + + Args: + session (Session): The database session used to query the account. + account_id (uuid.UUID): The ID of the account to retrieve. + + Raises: + HTTPException: If the account does not exist or is deleted. + + Returns: + Account: The active account if it exists and is not deleted. + """ + account = session.get(Account, account_id) + + if account is None or account.deleted or account.id is None: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) + + return account + + +def logout(session: Session, access_token: AccessToken) -> 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: + request (Request): The FastAPI request object. + session (Session): The database session used to query the account. + access_token (AccessToken): The access token for the user to logout. + + Returns: + dict: A dictionary containing the status of the logout operation. + """ + + account = _get_active_account(session, access_token.effective_account_id) + + account.epoch += 1 + + session.add(account) + session.commit() + + return {"status": "ok"} + + +def change_password( + session: Session, + access_token: AccessToken, + current_password: str, + new_password: str, +) -> Dict[str, str]: + """Change the password for the user associated with the provided access token. + + Args: + request (Request): The FastAPI request object. + session (Session): The database session used to query the account. + access_token (AccessToken): The access token for the user. + current_password (str): The current password for the user. + new_password (str): The new password for the user. + + Raises: + HTTPException: If the access token is invalid or the current password is incorrect. + + Returns: + Dict[str, str]: A dictionary containing the status of the password change operation. + """ + account = _get_active_account(session, access_token.effective_account_id) + + if not _verify_password(current_password, account.password_hash): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Current password is incorrect.", + ) + + account.password_hash = _hash_password(new_password) + account.epoch += 1 + + session.add(account) + session.commit() + + return {"status": "ok"} diff --git a/service/src/main/inse/auth/test_auth_service 2.py b/service/src/main/inse/auth/test_auth_service 2.py new file mode 100644 index 00000000..7db19bb4 --- /dev/null +++ b/service/src/main/inse/auth/test_auth_service 2.py @@ -0,0 +1,517 @@ +import inse.config as config_module +import uuid + +import pytest +from sqlmodel import Session, SQLModel, create_engine, select + + +from fastapi import Response, HTTPException +import datetime as _dt +from datetime import timedelta + +from inse.auth import service as auth_service +from inse.auth.model import ( + Account, + Organization, + Secret, + IdToken, + AccessToken, + RefreshToken, + UserRole, +) + + +@pytest.fixture() +def settings_backup(): + orig = config_module.get_settings() + backup = config_module.Settings(**orig.model_dump()) + yield backup + for k, v in backup.model_dump().items(): + setattr(config_module.settings, k, v) + + +@pytest.fixture() +def in_memory_session(): + engine = create_engine( + "sqlite:///:memory:", connect_args={"check_same_thread": False} + ) + SQLModel.metadata.create_all(engine) + with Session(engine) as session: + yield session + + +def create_org_and_account( + session: Session, email: str, password: str, role=UserRole.USER +): + org = Organization(name=f"Test Org {email}") + session.add(org) + session.flush() + assert org.id is not None + pwd_hash = auth_service._hash_password(password) + acc = Account( + email=email, + name="Tester", + organization_id=org.id, + password_hash=pwd_hash, + role=role, + ) + session.add(acc) + session.commit() + session.refresh(acc) + return org, acc + + +def test_hash_and_verify_password(): + pw = "s3cret-password" + h = auth_service._hash_password(pw) + assert auth_service._verify_password(pw, h) is True + assert auth_service._verify_password("wrong", h) is False + + +def test_request_otk_and_login_flow(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "test-hmac-key" + config_module.settings.token_issuer_id = "test-issuer" + config_module.settings.skip_otk_validation = False + + email = "user@example.com" + password = "hunter2" + + org, acc = create_org_and_account(in_memory_session, email, password) + 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) + + secret = in_memory_session.exec( + select(Secret).where(Secret.account_id == acc.id) + ).first() + assert secret is not None + + response = Response() + + login_result = auth_service.login( + in_memory_session, response, acc.id, secret.secret_value + ) + assert isinstance(login_result.id_token, IdToken) + assert login_result.id_token.real_account_id == acc.id + assert login_result.id_token.user_fingerprint_hash is not None + + +def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "another-key" + config_module.settings.token_issuer_id = "issuer-2" + + email = "fp@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + 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) + + 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, + 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, + session=in_memory_session, + ) + + +def test_access_and_refresh_token_flow(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "flow-key" + config_module.settings.token_issuer_id = "flow-issuer" + + email = "flow@example.com" + password = "pwflow" + org, acc = create_org_and_account( + in_memory_session, email, password, role=UserRole.ADMIN + ) + assert acc.id is not None + + response = Response() + id_token = auth_service._build_id_token(response, acc.id, acc.epoch) + + 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) + + refreshed = auth_service.refresh_access_token(access_response.refresh_token) + assert isinstance(refreshed, AccessToken) + assert refreshed.real_account_id == access_response.access_token.real_account_id + + +def test_logout_and_change_password(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "logout-key" + config_module.settings.token_issuer_id = "logout-issuer" + + email = "logout@example.com" + password = "oldpw" + org, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + response = Response() + id_token = auth_service._build_id_token(response, acc.id, acc.epoch) + access_resp = auth_service.get_access_token( + response, in_memory_session, id_token, acc.id + ) + + before_epoch = acc.epoch + out = auth_service.logout(in_memory_session, access_resp.access_token) + assert out["status"] == "ok" + in_memory_session.refresh(acc) + assert acc.epoch == before_epoch + 1 + + new_pw = "newpw123" + acc.password_hash = auth_service._hash_password(password) + in_memory_session.add(acc) + in_memory_session.commit() + + change_out = auth_service.change_password( + in_memory_session, access_resp.access_token, password, new_pw + ) + assert change_out["status"] == "ok" + in_memory_session.refresh(acc) + assert auth_service._verify_password(new_pw, acc.password_hash) + + +def test_request_otk_invalid_credentials(in_memory_session, settings_backup): + email = "nope@example.com" + password = "rightpw" + org, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + with pytest.raises(HTTPException): + auth_service.request_otk(in_memory_session, email, "wrongpw") + + +def test_login_with_expired_secret(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "expired-key" + config_module.settings.token_issuer_id = "expired-issuer" + config_module.settings.skip_otk_validation = False + + email = "expired@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10) + secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at) + in_memory_session.add(secret) + in_memory_session.commit() + + with pytest.raises(HTTPException): + auth_service.login(in_memory_session, Response(), acc.id, "000000") + + +def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "cookie-key" + config_module.settings.token_issuer_id = "cookie-issuer" + + email = "cookie@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + 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 + + 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, + session=in_memory_session, + ) + + +def test_token_epoch_mismatch(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "epoch-key" + config_module.settings.token_issuer_id = "epoch-issuer" + + email = "epoch@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + 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 + + 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, + session=in_memory_session, + ) + + +def test_invalid_token_signature_raises(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "sig-key" + config_module.settings.token_issuer_id = "sig-issuer" + + email = "sig@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + 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 + + bad_token = id_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, + session=in_memory_session, + ) + + +def test_impersonation_rules(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "imp-key" + config_module.settings.token_issuer_id = "imp-issuer" + + org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw") + assert real_acc.id is not None + org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw") + assert eff_acc.id is not None + + response = Response() + id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch) + + with pytest.raises(HTTPException): + auth_service.get_access_token( + response, + in_memory_session, + id_token, + real_acc.id, + effective_account_id=eff_acc.id, + ) + + real_acc.role = UserRole.SUPER_ADMIN + in_memory_session.add(real_acc) + in_memory_session.commit() + + access_resp = auth_service.get_access_token( + response, + in_memory_session, + id_token, + real_acc.id, + effective_account_id=eff_acc.id, + ) + assert isinstance(access_resp.access_token, AccessToken) + + +def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "regen-key" + config_module.settings.token_issuer_id = "regen-issuer" + config_module.settings.skip_otk_validation = False + + email = "regen@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + auth_service.request_otk(in_memory_session, email, password) + secret1 = in_memory_session.exec( + select(Secret).where(Secret.account_id == acc.id) + ).first() + assert secret1 is not None + first_value = secret1.secret_value + + auth_service.request_otk(in_memory_session, email, password) + secret2 = in_memory_session.exec( + select(Secret).where(Secret.account_id == acc.id) + ).first() + + assert secret2 is not None + assert first_value != secret2.secret_value + + with pytest.raises(HTTPException): + auth_service.login(in_memory_session, Response(), acc.id, first_value) + + login_res = auth_service.login( + in_memory_session, Response(), acc.id, secret2.secret_value + ) + assert isinstance(login_res.id_token, IdToken) + + +def test_otk_deleted_after_login(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "del-key" + config_module.settings.token_issuer_id = "del-issuer" + config_module.settings.skip_otk_validation = False + + email = "single@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + auth_service.request_otk(in_memory_session, email, password) + secret = in_memory_session.exec( + select(Secret).where(Secret.account_id == acc.id) + ).first() + assert secret is not None + + auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value) + post = in_memory_session.exec( + select(Secret).where(Secret.account_id == acc.id) + ).first() + assert post is None + + +def test_access_token_fp_mismatch(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "act-key" + config_module.settings.token_issuer_id = "act-issuer" + + email = "act@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + response = Response() + raw = auth_service._set_act_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=raw, + ) + + 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, + session=in_memory_session, + ) + + +def test_expired_jwt_token_raises(in_memory_session, settings_backup): + config_module.settings.token_hmac_key = "exp-key" + config_module.settings.token_issuer_id = "exp-issuer" + + email = "exp@example.com" + password = "pw" + org, acc = create_org_and_account(in_memory_session, email, password) + 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) + payload = { + auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EPOCH_KEY: acc.epoch, + auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw, + } + bad_token = auth_service._build_token( + payload=payload, + expiration_datetime=past, + token_type=auth_service.TokenType.ID_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, + session=in_memory_session, + ) + + +def test_missing_hmac_key_raises_value_error(settings_backup): + orig = config_module.get_settings() + saved = orig.token_hmac_key + config_module.settings.token_hmac_key = None + with pytest.raises(ValueError): + auth_service._build_token( + payload={}, + expiration_datetime=_dt.datetime.now(_dt.timezone.utc), + token_type=auth_service.TokenType.ID_TOKEN, + ) + config_module.settings.token_hmac_key = saved + + +def test_get_account_epoch_not_found(in_memory_session): + random_id = uuid.uuid4() + with pytest.raises(Exception): + auth_service._get_account_epoch(in_memory_session, random_id) diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 87ebf721..09f63402 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -30,7 +30,6 @@ class Settings(BaseSettings): openalex_works_search_index: str = "openalex-works*" openalex_works_search_timeout_seconds: float = 30.0 # OpenAlex public API config - openalex_api_base_url: str = "https://api.openalex.org" openalex_api_key: Optional[str] = None openalex_api_timeout_seconds: float = 30.0 diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index d001c646..17388849 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -8,7 +8,6 @@ import logging from copy import deepcopy from typing import Any, Optional -import httpx from pydantic import ValidationError from inse.exceptions import UpstreamAPIException, BadRequestException @@ -60,34 +59,17 @@ async def list_institutions( openalex_client = client or OpenAlexInstitutionsClient() - try: - data = await openalex_client.list_institutions( - search=search, - filter=filter, - sort=sort, - group_by=group_by, - per_page=per_page, - page=page, - cursor=cursor, - sample=sample, - select=select, - ) - except httpx.HTTPStatusError as exc: - status_code = exc.response.status_code - detail = "OpenAlex institutions request failed." - try: - error_body = exc.response.json() - detail = error_body.get("message") or error_body.get("error") or detail - except ValueError: - if exc.response.text: - detail = exc.response.text - raise UpstreamAPIException(message=detail, status_code=status_code) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex institutions request failed.") - raise UpstreamAPIException( - message="OpenAlex institutions request failed.", - status_code=502, - ) from exc + data = await openalex_client.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) try: normalized_data = _normalize_institutions_response(data) diff --git a/service/src/main/inse/institutions/search_client.py b/service/src/main/inse/institutions/search_client.py index 9839e24c..cc70ff78 100644 --- a/service/src/main/inse/institutions/search_client.py +++ b/service/src/main/inse/institutions/search_client.py @@ -1,36 +1,18 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -""" -HTTP client for OpenAlex institutions. -""" +"""Elasticsearch client for OpenAlex institutions.""" from typing import Any -import httpx - -from .. import config +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex class OpenAlexInstitutionsClient: - def __init__( - self, - base_url: str | None = None, - api_key: str | None = None, - timeout: float | None = None, - transport: httpx.AsyncBaseTransport | None = None, - ): - self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") - self.api_key = ( - api_key if api_key is not None else config.settings.openalex_api_key - ) - self.timeout = ( - timeout - if timeout is not None - else config.settings.openalex_api_timeout_seconds - ) - self.transport = transport + def __init__(self, index: str | ESIndex = ESIndex.OPENALEX_INSTITUTIONS): + self.index = index - def list_institutions_params( + def list_institutions_query( self, *, search: str | None = None, @@ -43,60 +25,144 @@ class OpenAlexInstitutionsClient: sample: int | None = None, select: str | None = None, ) -> dict[str, Any]: - params: dict[str, Any] = {"per_page": per_page} - + must: list[dict[str, Any]] = [] if search: - params["search"] = search - if filter: - params["filter"] = filter - if sort: - params["sort"] = sort - if group_by: - params["group_by"] = group_by - if cursor: - params["cursor"] = cursor - elif page is not None: - params["page"] = page - if sample is not None: - params["sample"] = sample - if select: - params["select"] = select - if self.api_key: - params["api_key"] = self.api_key - - return params - - async def list_institutions( - self, - *, - search: str | None = None, - filter: str | None = None, - sort: str | None = None, - group_by: str | None = None, - per_page: int = 25, - page: int | None = 1, - cursor: str | None = None, - sample: int | None = None, - select: str | None = None, - ) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.get( - "/institutions", - params=self.list_institutions_params( - search=search, - filter=filter, - sort=sort, - group_by=group_by, - per_page=per_page, - page=page, - cursor=cursor, - sample=sample, - select=select, - ), + must.append( + { + "multi_match": { + "query": search, + "fields": [ + "display_name^3", + "display_name_alternatives^2", + "display_name_acronyms^2", + ], + } + } ) - response.raise_for_status() - return response.json() + + query: dict[str, Any] = { + "bool": { + "must": must or [{"match_all": {}}], + "filter": self._filters(filter), + } + } + if sample is not None: + query = { + "function_score": { + "query": query, + "random_score": {"seed": sample}, + } + } + + body: dict[str, Any] = { + "query": query, + "from": max((page or 1) - 1, 0) * per_page, + "size": per_page, + "track_total_hits": True, + } + if select: + body["_source"] = [ + field.strip() for field in select.split(",") if field.strip() + ] + if sort: + body["sort"] = self._sort(sort) + if cursor and cursor != "*": + body["search_after"] = cursor.split(",") + body.pop("from", None) + if group_by: + body["aggs"] = { + "group_by": { + "terms": { + "field": self._keyword_field(group_by), + "size": per_page, + } + } + } + return body + + async def list_institutions(self, **kwargs: Any) -> dict[str, Any]: + response = await elasticsearch.search( + index=self.index, + body=self.list_institutions_query(**kwargs), + cluster=ESCluster.NES, + ) + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + total_value = hits_block.get("total", 0) + total = ( + total_value.get("value", 0) + if isinstance(total_value, dict) + else total_value + ) + result: dict[str, Any] = { + "meta": { + "count": total, + "page": kwargs.get("page", 1), + "per_page": kwargs.get("per_page", 25), + "next_cursor": self._next_cursor(hits), + }, + "results": [hit.get("_source", {}) for hit in hits], + } + + buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets") + if buckets is not None: + result["group_by"] = [ + { + "key": bucket.get("key"), + "key_display_name": bucket.get( + "key_as_string", bucket.get("key") + ), + "count": bucket.get("doc_count"), + } + for bucket in buckets + ] + return result + + @staticmethod + def _filters(value: str | None) -> list[dict[str, Any]]: + clauses: list[dict[str, Any]] = [] + for item in (value or "").split(","): + if not item or ":" not in item: + continue + field, raw_value = item.split(":", 1) + field = field.strip() + raw_value = raw_value.strip() + if raw_value.startswith((">", "<")): + operator = "gt" if raw_value[0] == ">" else "lt" + clauses.append({"range": {field: {operator: raw_value[1:]}}}) + else: + clauses.append( + {"term": {OpenAlexInstitutionsClient._keyword_field(field): raw_value}} + ) + return clauses + + @staticmethod + def _sort(value: str) -> list[dict[str, Any]]: + result = [] + for item in value.split(","): + field, _, direction = item.partition(":") + result.append( + { + OpenAlexInstitutionsClient._sortable_field(field.strip()): { + "order": direction or "desc", + "missing": "_last", + } + } + ) + return result + + @staticmethod + def _keyword_field(field: str) -> str: + if field in {"id", "ror", "display_name"}: + return f"{field}.keyword" + return field + + @staticmethod + def _sortable_field(field: str) -> str: + return "display_name.keyword" if field == "display_name" else field + + @staticmethod + def _next_cursor(hits: list[dict[str, Any]]) -> str | None: + if not hits or not hits[-1].get("sort"): + return None + return ",".join(str(value) for value in hits[-1]["sort"]) diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index 11544b19..9537f49e 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -1,9 +1,7 @@ -import httpx import pytest -from inse.exceptions import BadRequestException +from inse.exceptions import BadRequestException from inse.institutions import logic -from inse.institutions.search_client import OpenAlexInstitutionsClient @pytest.fixture @@ -11,166 +9,72 @@ def anyio_backend(): return "asyncio" -@pytest.mark.anyio -async def test_list_institutions_maps_openalex_response_to_model(): - def handler(_: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ - { - "id": "https://openalex.org/I123", - "ror": "https://ror.org/04mz5ra38", - "display_name": "University of Duisburg-Essen", - "country_code": "DE", - "type": "education", - "homepage_url": "https://www.uni-due.de", - "image_url": "https://example.org/image.jpg", - "image_thumbnail_url": "https://example.org/thumb.jpg", - "display_name_acronyms": ["UDE"], - "display_name_alternatives": ["Universitaet Duisburg-Essen"], - "works_count": 123, - "cited_by_count": 456, - "summary_stats": { - "2yr_mean_citedness": 1.5, - "h_index": 42, - "i10_index": 99, - }, - "geo": { - "city": "Duisburg", - "geonames_city_id": "2934691", - "region": "North Rhine-Westphalia", - "country_code": "DE", - "country": "Germany", - "latitude": 51.4344, - "longitude": 6.7623, - }, - "lineage": ["https://openalex.org/I123"], - "ids": { - "openalex": "https://openalex.org/I123", - "ror": "https://ror.org/04mz5ra38", - "mag": 123, - "grid": "grid.12345.6", - "wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen", - "wikidata": "https://www.wikidata.org/wiki/Q317070", - }, - "counts_by_year": [ - { - "year": 2024, - "works_count": 12, - "cited_by_count": 34, - } - ], - "works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123", - "created_date": "2023-12-25", - "updated_date": "2023-11-07T05:31:56Z", - } - ], - "group_by": [ - { - "key": "DE", - "key_display_name": "Germany", - "count": 1, - } - ], - }, - ) +class StubInstitutionsClient: + def __init__(self, response): + self.response = response + self.kwargs = None - client = OpenAlexInstitutionsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), + async def list_institutions(self, **kwargs): + self.kwargs = kwargs + return self.response + + +@pytest.mark.anyio +async def test_list_institutions_maps_elasticsearch_response_to_model(): + client = StubInstitutionsClient( + { + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/012345678", + "display_name": "Example University", + "country_code": "DE", + "type": "education", + "works_count": 123, + "cited_by_count": 456, + "geo": {"city": "Essen", "country": "Germany"}, + "ids": {"openalex": "https://openalex.org/I123"}, + } + ], + } ) - result = await logic.list_institutions(search="Duisburg Essen", client=client) + result = await logic.list_institutions(search="Example", client=client) assert result.meta.count == 1 - institution = result.results[0] - assert institution.display_name == "University of Duisburg-Essen" - assert institution.summary_stats.h_index == 42 - assert institution.geo.country == "Germany" - assert institution.ids.mag == 123 - assert institution.counts_by_year[0].year == 2024 - assert result.group_by[0].key_display_name == "Germany" + assert result.results[0].display_name == "Example University" + assert result.results[0].geo.city == "Essen" + assert client.kwargs["search"] == "Example" @pytest.mark.anyio async def test_list_institutions_rejects_sample_with_sort(): - with pytest.raises(BadRequestException) as exc_info: + with pytest.raises(BadRequestException): await logic.list_institutions(sample=10, sort="works_count:desc") @pytest.mark.anyio -async def test_list_institutions_accepts_practical_openalex_type_variants(): - def handler(_: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ - { - "id": 123, - "ror": 456, - "display_name": "Example Institute", - "country_code": 789, - "type": "unknown-openalex-type", - "display_name_acronyms": ["EI", 123], - "display_name_alternatives": "not-a-list", - "works_count": "12", - "cited_by_count": "34.0", - "summary_stats": { - "2yr_mean_citedness": "1.25", - "h_index": "10.0", - "i10_index": True, - }, - "geo": { - "city": 123, - "geonames_city_id": 12345, - "latitude": "51.4", - "longitude": "6", - }, - "ids": {"openalex": 123, "mag": "123"}, - "counts_by_year": [ - { - "year": "2024", - "works_count": "12.0", - "cited_by_count": False, - } - ], - "created_date": "2023-12-25T10:11:12Z", - "updated_date": "2023-12-25", - } - ], - "group_by": [{"key": True, "count": 1}], - }, - ) - - client = OpenAlexInstitutionsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), +async def test_list_institutions_normalizes_elasticsearch_values(): + client = StubInstitutionsClient( + { + "meta": {"count": "1", "page": "1", "per_page": "25"}, + "results": [ + { + "id": 123, + "display_name": 456, + "type": "unknown-type", + "works_count": "12.0", + "ids": {"openalex": 123, "mag": "123"}, + } + ], + } ) result = await logic.list_institutions(client=client) assert result.results[0].id == "123" - assert result.results[0].ror == "456" - assert result.results[0].country_code == "789" + assert result.results[0].display_name == "456" assert result.results[0].type is None - assert result.results[0].display_name_acronyms == ["EI", "123"] - assert result.results[0].display_name_alternatives is None assert result.results[0].works_count == 12 - assert result.results[0].cited_by_count == 34 - assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25 - assert result.results[0].summary_stats.h_index == 10 - assert result.results[0].summary_stats.i10_index is None - assert result.results[0].geo.city == "123" - assert result.results[0].geo.geonames_city_id == "12345" - assert result.results[0].geo.latitude == 51.4 - assert result.results[0].geo.longitude == 6 - assert result.results[0].ids.openalex == "123" assert result.results[0].ids.mag == 123 - assert result.results[0].counts_by_year[0].year == 2024 - assert result.results[0].counts_by_year[0].works_count == 12 - assert result.results[0].counts_by_year[0].cited_by_count is None - assert result.group_by[0].key == "true" - diff --git a/service/src/main/inse/institutions/test_search_client.py b/service/src/main/inse/institutions/test_search_client.py index 0051b8cf..c83e2a36 100644 --- a/service/src/main/inse/institutions/test_search_client.py +++ b/service/src/main/inse/institutions/test_search_client.py @@ -1,6 +1,8 @@ -import httpx +from unittest.mock import AsyncMock, patch + import pytest +from inse.model import ESCluster, ESIndex from inse.institutions.search_client import OpenAlexInstitutionsClient @@ -9,69 +11,47 @@ def anyio_backend(): return "asyncio" -def test_list_institutions_params_include_openalex_query_parameters(): - client = OpenAlexInstitutionsClient(api_key="test-key") - - params = client.list_institutions_params( +def test_list_institutions_query_builds_elasticsearch_query(): + body = OpenAlexInstitutionsClient().list_institutions_query( search="Duisburg Essen", - filter="country_code:DE,type:education", + filter="country_code:DE,type:education,works_count:>1000", sort="works_count:desc", - group_by="country_code", per_page=10, page=2, select="id,display_name", ) - assert params == { - "search": "Duisburg Essen", - "filter": "country_code:DE,type:education", - "sort": "works_count:desc", - "group_by": "country_code", - "per_page": 10, - "page": 2, - "select": "id,display_name", - "api_key": "test-key", - } - - -def test_list_institutions_params_prefers_cursor_over_page(): - client = OpenAlexInstitutionsClient(api_key="test-key") - - params = client.list_institutions_params(cursor="*", page=3) - - assert params["cursor"] == "*" - assert "page" not in params + assert body["from"] == 10 + assert body["size"] == 10 + assert body["_source"] == ["id", "display_name"] + assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "Duisburg Essen" + assert {"term": {"country_code": "DE"}} in body["query"]["bool"]["filter"] + assert {"term": {"type": "education"}} in body["query"]["bool"]["filter"] + assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"] + assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}] @pytest.mark.anyio -async def test_list_institutions_calls_openalex_institutions_endpoint(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.method == "GET" - assert request.url.path == "/institutions" - assert request.url.params["search"] == "Duisburg Essen" - assert request.url.params["api_key"] == "test-key" - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ - { +async def test_list_institutions_calls_elasticsearch_and_maps_hits(): + response = { + "hits": { + "total": {"value": 1}, + "hits": [ + { + "_source": { "id": "https://openalex.org/I123", - "display_name": "University of Duisburg-Essen", - "country_code": "DE", - "type": "education", + "display_name": "Example University", } - ], - }, - ) - - client = OpenAlexInstitutionsClient( - base_url="https://api.openalex.org", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - result = await client.list_institutions(search="Duisburg Essen") + } + ], + } + } + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search: + search.return_value = response + result = await OpenAlexInstitutionsClient().list_institutions(search="Example") + search.assert_awaited_once() + assert search.await_args.kwargs["index"] == ESIndex.OPENALEX_INSTITUTIONS + assert search.await_args.kwargs["cluster"] == ESCluster.NES assert result["meta"]["count"] == 1 - assert result["results"][0]["display_name"] == "University of Duisburg-Essen" + assert result["results"][0]["display_name"] == "Example University" diff --git a/service/src/main/inse/organization_management/__init__ 2.py b/service/src/main/inse/organization_management/__init__ 2.py new file mode 100644 index 00000000..9955b679 --- /dev/null +++ b/service/src/main/inse/organization_management/__init__ 2.py @@ -0,0 +1 @@ +"""Organization management API.""" diff --git a/service/src/main/inse/organization_management/model 2.py b/service/src/main/inse/organization_management/model 2.py new file mode 100644 index 00000000..e5e0a615 --- /dev/null +++ b/service/src/main/inse/organization_management/model 2.py @@ -0,0 +1,30 @@ +import uuid +from typing import List, Optional + +from pydantic import BaseModel, Field + + +class OrganizationProfile(BaseModel): + id: uuid.UUID + name: str + other_inst_id: Optional[str] = None + deleted: bool + member_count: int + + +class OrganizationPage(BaseModel): + items: List[OrganizationProfile] + total: int + page: int + page_size: int + + +class CreateOrganizationRequest(BaseModel): + name: str = Field(min_length=1) + other_inst_id: Optional[str] = None + + +class UpdateOrganizationRequest(BaseModel): + name: Optional[str] = Field(default=None, min_length=1) + other_inst_id: Optional[str] = None + deleted: Optional[bool] = None diff --git a/service/src/main/inse/organization_management/router 2.py b/service/src/main/inse/organization_management/router 2.py new file mode 100644 index 00000000..0a8b82ca --- /dev/null +++ b/service/src/main/inse/organization_management/router 2.py @@ -0,0 +1,81 @@ +import uuid +from typing import Optional + +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.database import get_session +from inse.tags import Tags + +from . import service +from .model import ( + CreateOrganizationRequest, + OrganizationPage, + OrganizationProfile, + UpdateOrganizationRequest, +) + +router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION]) + + +@router.get("", operation_id="getOrganisations", response_model=OrganizationPage) +async def get_organizations( + 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), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> OrganizationPage: + return service.get_organizations( + session=session, + access_token=access_token, + page=page, + page_size=page_size, + offset=offset, + ) + + +@router.post( + "", + operation_id="createOrganisation", + response_model=OrganizationProfile, + status_code=status.HTTP_201_CREATED, +) +async def create_organization( + payload: CreateOrganizationRequest, + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> OrganizationProfile: + return service.create_organization(session, access_token, payload) + + +@router.put( + "/{organization_id}", + operation_id="updateOrganisation", + response_model=OrganizationProfile, +) +async def update_organization( + organization_id: uuid.UUID, + payload: UpdateOrganizationRequest, + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> OrganizationProfile: + return service.update_organization( + session, access_token, organization_id, payload + ) + + +@router.delete( + "/{organization_id}", + operation_id="deleteOrganisation", + status_code=status.HTTP_204_NO_CONTENT, +) +async def delete_organization( + organization_id: uuid.UUID, + session: Session = Depends(get_session), + access_token: AccessToken = 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 2.py b/service/src/main/inse/organization_management/service 2.py new file mode 100644 index 00000000..56d97db2 --- /dev/null +++ b/service/src/main/inse/organization_management/service 2.py @@ -0,0 +1,183 @@ +import uuid +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 .model import ( + CreateOrganizationRequest, + OrganizationPage, + OrganizationProfile, + UpdateOrganizationRequest, +) + + +def _require_super_admin(access_token: AccessToken) -> None: + if access_token.effective_role != UserRole.SUPER_ADMIN: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only superadmins can manage organizations.", + ) + + +def _normalize_name(name: str) -> str: + normalized_name = name.strip() + if not normalized_name: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Organization name must not be empty.", + ) + return normalized_name + + +def _ensure_name_available( + session: Session, + name: str, + excluded_organization_id: Optional[uuid.UUID] = None, +) -> None: + statement = select(Organization).where( + func.lower(Organization.name) == name.lower() + ) + if excluded_organization_id is not None: + statement = statement.where(Organization.id != excluded_organization_id) + + if session.exec(statement).first() is not None: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="An organization with this name already exists.", + ) + + +def _get_organization_or_404( + session: Session, organization_id: uuid.UUID +) -> Organization: + organization = session.get(Organization, organization_id) + if organization is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Organization not found.", + ) + return organization + + +def _member_counts( + session: Session, organization_ids: list[uuid.UUID] +) -> dict[uuid.UUID, int]: + if not organization_ids: + return {} + + rows = session.exec( + select(Account.organization_id, func.count(Account.id)) + .where( + Account.organization_id.in_(organization_ids), + Account.deleted == False, # noqa: E712 + ) + .group_by(Account.organization_id) + ).all() + return {organization_id: count for organization_id, count in rows} + + +def _to_profile( + organization: Organization, member_count: int +) -> OrganizationProfile: + return OrganizationProfile( + id=organization.id, + name=organization.name, + other_inst_id=organization.openalex_institution_id, + deleted=organization.deleted, + member_count=member_count, + ) + + +def get_organizations( + session: Session, + access_token: AccessToken, + page: int, + page_size: int, + offset: Optional[int] = None, +) -> OrganizationPage: + statement = select(Organization) + count_statement = select(func.count()).select_from(Organization) + + if access_token.effective_role != UserRole.SUPER_ADMIN: + scope_filter = Organization.id == access_token.effective_organization_id + statement = statement.where(scope_filter) + count_statement = count_statement.where(scope_filter) + + total = session.exec(count_statement).one() + effective_offset = offset if offset is not None else page * page_size + organizations = session.exec( + statement.order_by(Organization.name) + .offset(effective_offset) + .limit(page_size) + ).all() + organization_ids = [organization.id for organization in organizations] + counts = _member_counts(session, organization_ids) + + return OrganizationPage( + items=[ + _to_profile(organization, counts.get(organization.id, 0)) + for organization in organizations + ], + total=total, + page=page, + page_size=page_size, + ) + + +def create_organization( + session: Session, + access_token: AccessToken, + payload: CreateOrganizationRequest, +) -> OrganizationProfile: + _require_super_admin(access_token) + name = _normalize_name(payload.name) + _ensure_name_available(session, name) + + organization = Organization( + name=name, + openalex_institution_id=(payload.other_inst_id or '').strip() or None, + ) + session.add(organization) + session.commit() + session.refresh(organization) + return _to_profile(organization, 0) + + +def update_organization( + session: Session, + access_token: AccessToken, + organization_id: uuid.UUID, + payload: UpdateOrganizationRequest, +) -> OrganizationProfile: + _require_super_admin(access_token) + organization = _get_organization_or_404(session, organization_id) + + if payload.name is not None: + name = _normalize_name(payload.name) + _ensure_name_available(session, name, organization.id) + organization.name = name + if payload.other_inst_id is not None: + organization.openalex_institution_id = payload.other_inst_id.strip() or None + if payload.deleted is not None: + organization.deleted = payload.deleted + + session.add(organization) + session.commit() + session.refresh(organization) + counts = _member_counts(session, [organization.id]) + return _to_profile(organization, counts.get(organization.id, 0)) + + +def delete_organization( + session: Session, + access_token: AccessToken, + organization_id: uuid.UUID, +) -> None: + _require_super_admin(access_token) + organization = _get_organization_or_404(session, organization_id) + organization.deleted = True + session.add(organization) + session.commit() diff --git a/service/src/main/inse/organization_management/test_service 2.py b/service/src/main/inse/organization_management/test_service 2.py new file mode 100644 index 00000000..ce3b3e03 --- /dev/null +++ b/service/src/main/inse/organization_management/test_service 2.py @@ -0,0 +1,181 @@ +from types import SimpleNamespace + +import pytest +from fastapi import HTTPException +from sqlmodel import Session, SQLModel, create_engine + +from inse.auth.model import Account, Organization, UserRole +from inse.organization_management import service +from inse.organization_management.model import ( + CreateOrganizationRequest, + UpdateOrganizationRequest, +) + + +@pytest.fixture() +def session(): + engine = create_engine( + "sqlite:///:memory:", connect_args={"check_same_thread": False} + ) + SQLModel.metadata.create_all(engine) + with Session(engine) as database_session: + yield database_session + + +def token(role: UserRole, organization_id): + return SimpleNamespace( + effective_role=role, + effective_organization_id=organization_id, + ) + + +def test_superadmin_lists_all_organizations_with_active_member_count(session): + first = Organization(name="Alpha") + second = Organization(name="Beta", deleted=True) + session.add(first) + session.add(second) + session.flush() + session.add( + Account( + email="active@example.org", + name="Active", + password_hash="hash", + organization_id=first.id, + ) + ) + session.add( + Account( + email="deleted@example.org", + name="Deleted", + password_hash="hash", + organization_id=first.id, + deleted=True, + ) + ) + session.commit() + + result = service.get_organizations( + session, token(UserRole.SUPER_ADMIN, first.id), page=0, page_size=10 + ) + + assert result.total == 2 + assert [item.name for item in result.items] == ["Alpha", "Beta"] + assert result.items[0].member_count == 1 + assert result.items[1].deleted is True + + +def test_non_superadmin_only_sees_own_organization(session): + own = Organization(name="Own") + session.add(own) + session.add(Organization(name="Other")) + session.commit() + + result = service.get_organizations( + session, token(UserRole.USER, own.id), page=0, page_size=10 + ) + + assert result.total == 1 + assert result.items[0].id == own.id + + +def test_superadmin_can_create_update_and_soft_delete(session): + scope = Organization(name="Scope") + session.add(scope) + session.commit() + access_token = token(UserRole.SUPER_ADMIN, scope.id) + + created = service.create_organization( + session, + access_token, + CreateOrganizationRequest(name=" New tenant ", other_inst_id="I123"), + ) + assert created.name == "New tenant" + assert created.other_inst_id == "I123" + + updated = service.update_organization( + session, + access_token, + created.id, + UpdateOrganizationRequest(name="Renamed", other_inst_id=""), + ) + assert updated.name == "Renamed" + assert updated.other_inst_id is None + + service.delete_organization(session, access_token, created.id) + assert session.get(Organization, created.id).deleted is True + + +@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER]) +def test_only_superadmin_can_create_organizations(session, role): + organization = Organization(name="Scope") + session.add(organization) + session.commit() + + with pytest.raises(HTTPException) as error: + service.create_organization( + session, + token(role, organization.id), + CreateOrganizationRequest(name="Forbidden"), + ) + + assert error.value.status_code == 403 + + +def test_organization_name_must_not_be_blank(session): + organization = Organization(name="Scope") + session.add(organization) + session.commit() + + with pytest.raises(HTTPException) as error: + service.create_organization( + session, + token(UserRole.SUPER_ADMIN, organization.id), + CreateOrganizationRequest(name=" "), + ) + + assert error.value.status_code == 422 + + +def test_organization_name_is_unique_ignoring_case(session): + existing = Organization(name="Unique tenant") + session.add(existing) + session.commit() + access_token = token(UserRole.SUPER_ADMIN, existing.id) + + with pytest.raises(HTTPException) as create_error: + service.create_organization( + session, + access_token, + CreateOrganizationRequest(name=" unique TENANT "), + ) + + assert create_error.value.status_code == 409 + + other = Organization(name="Other tenant") + session.add(other) + session.commit() + + with pytest.raises(HTTPException) as update_error: + service.update_organization( + session, + access_token, + other.id, + UpdateOrganizationRequest(name="UNIQUE TENANT"), + ) + + assert update_error.value.status_code == 409 + + +def test_organization_can_keep_its_name_when_updating(session): + organization = Organization(name="Same tenant") + session.add(organization) + session.commit() + + result = service.update_organization( + session, + token(UserRole.SUPER_ADMIN, organization.id), + organization.id, + UpdateOrganizationRequest(name="same TENANT"), + ) + + assert result.name == "same TENANT" diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index b956fc89..97f1c693 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -8,7 +8,6 @@ import logging from copy import deepcopy from typing import Any -import httpx from pydantic import ValidationError from inse.exceptions import ( UpstreamAPIException, @@ -46,34 +45,17 @@ async def list_topics( openalex_client = client or OpenAlexTopicsClient() - try: - data = await openalex_client.list_topics( - search=search, - filter=filter, - sort=sort, - group_by=group_by, - per_page=per_page, - page=page, - cursor=cursor, - sample=sample, - select=select, - ) - except httpx.HTTPStatusError as exc: - status_code = exc.response.status_code - detail = "OpenAlex topics request failed." - try: - error_body = exc.response.json() - detail = error_body.get("message") or error_body.get("error") or detail - except ValueError: - if exc.response.text: - detail = exc.response.text - raise UpstreamAPIException(message=detail, status_code=status_code) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex topics request failed.") - raise UpstreamAPIException( - message="OpenAlex topics request failed.", - status_code=502, - ) from exc + data = await openalex_client.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) try: normalized_data = _normalize_topics_response(data) diff --git a/service/src/main/inse/topics/search_client.py b/service/src/main/inse/topics/search_client.py index 7c70afa0..00d9e824 100644 --- a/service/src/main/inse/topics/search_client.py +++ b/service/src/main/inse/topics/search_client.py @@ -1,33 +1,18 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -""" -HTTP client for OpenAlex topics. -""" +"""Elasticsearch client for OpenAlex topics.""" + from typing import Any -import httpx - -from .. import config +from inse.integrations import elasticsearch +from inse.model import ESCluster class OpenAlexTopicsClient: - def __init__( - self, - base_url: str | None = None, - api_key: str | None = None, - timeout: float | None = None, - transport: httpx.AsyncBaseTransport | None = None, - ): - self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") - self.api_key = api_key if api_key is not None else config.settings.openalex_api_key - self.timeout = ( - timeout - if timeout is not None - else config.settings.openalex_api_timeout_seconds - ) - self.transport = transport + def __init__(self, index: str = "topicvectors"): + self.index = index - def list_topics_params( + def list_topics_query( self, *, search: str | None = None, @@ -40,60 +25,118 @@ class OpenAlexTopicsClient: sample: int | None = None, select: str | None = None, ) -> dict[str, Any]: - params: dict[str, Any] = {"per_page": per_page} - + filters = self._filters(filter) + must: list[dict[str, Any]] = [] if search: - params["search"] = search - if filter: - params["filter"] = filter - if sort: - params["sort"] = sort - if group_by: - params["group_by"] = group_by - if cursor: - params["cursor"] = cursor - elif page is not None: - params["page"] = page - if sample is not None: - params["sample"] = sample - if select: - params["select"] = select - if self.api_key: - params["api_key"] = self.api_key - - return params - - async def list_topics( - self, - *, - search: str | None = None, - filter: str | None = None, - sort: str | None = None, - group_by: str | None = None, - per_page: int = 25, - page: int | None = 1, - cursor: str | None = None, - sample: int | None = None, - select: str | None = None, - ) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.get( - "/topics", - params=self.list_topics_params( - search=search, - filter=filter, - sort=sort, - group_by=group_by, - per_page=per_page, - page=page, - cursor=cursor, - sample=sample, - select=select, - ), + must.append( + { + "multi_match": { + "query": search, + "fields": ["display_name^3", "keywords^2", "description"], + } + } ) - response.raise_for_status() - return response.json() + + query: dict[str, Any] = { + "bool": { + "must": must or [{"match_all": {}}], + "filter": filters, + } + } + if sample is not None: + query = {"function_score": {"query": query, "random_score": {"seed": sample}}} + + body: dict[str, Any] = { + "query": query, + "from": max((page or 1) - 1, 0) * per_page, + "size": per_page, + "track_total_hits": True, + "_source": ( + [field.strip() for field in select.split(",") if field.strip()] + if select + else {"excludes": ["display_name_vector", "keyword_vectors"]} + ), + } + if sort: + body["sort"] = self._sort(sort) + if cursor and cursor != "*": + body["search_after"] = cursor.split(",") + body.pop("from", None) + if group_by: + body["aggs"] = { + "group_by": { + "terms": {"field": self._keyword_field(group_by), "size": per_page} + } + } + return body + + async def list_topics(self, **kwargs: Any) -> dict[str, Any]: + body = self.list_topics_query(**kwargs) + response = await elasticsearch.search( + index=self.index, + body=body, + cluster=ESCluster.NES, + ) + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + total_value = hits_block.get("total", 0) + total = total_value.get("value", 0) if isinstance(total_value, dict) else total_value + per_page = kwargs.get("per_page", 25) + page = kwargs.get("page", 1) + + result: dict[str, Any] = { + "meta": { + "count": total, + "page": page, + "per_page": per_page, + "next_cursor": self._next_cursor(hits), + }, + "results": [hit.get("_source", {}) for hit in hits], + } + buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets") + if buckets is not None: + result["group_by"] = [ + { + "key": bucket.get("key"), + "key_display_name": bucket.get("key_as_string", bucket.get("key")), + "count": bucket.get("doc_count"), + } + for bucket in buckets + ] + return result + + @staticmethod + def _filters(value: str | None) -> list[dict[str, Any]]: + clauses: list[dict[str, Any]] = [] + for item in (value or "").split(","): + if not item or ":" not in item: + continue + field, raw_value = item.split(":", 1) + field = OpenAlexTopicsClient._keyword_field(field.strip()) + raw_value = raw_value.strip() + if raw_value.startswith((">", "<")): + operator = "gt" if raw_value[0] == ">" else "lt" + clauses.append({"range": {field.removesuffix(".keyword"): {operator: raw_value[1:]}}}) + else: + clauses.append({"term": {field: raw_value}}) + return clauses + + @staticmethod + def _sort(value: str) -> list[dict[str, Any]]: + result = [] + for item in value.split(","): + field, _, direction = item.partition(":") + result.append({field.strip(): {"order": direction or "desc", "missing": "_last"}}) + return result + + @staticmethod + def _keyword_field(field: str) -> str: + if field in {"id", "display_name", "domain.id", "field.id", "subfield.id"}: + return f"{field}.keyword" + return field + + @staticmethod + def _next_cursor(hits: list[dict[str, Any]]) -> str | None: + if not hits or not hits[-1].get("sort"): + return None + return ",".join(str(value) for value in hits[-1]["sort"]) diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py index 5e88a461..ddf7f43b 100644 --- a/service/src/main/inse/topics/test_logic.py +++ b/service/src/main/inse/topics/test_logic.py @@ -1,9 +1,7 @@ -import httpx import pytest -from inse.exceptions import BadRequestException +from inse.exceptions import BadRequestException from inse.topics import logic -from inse.topics.search_client import OpenAlexTopicsClient @pytest.fixture @@ -11,183 +9,71 @@ def anyio_backend(): return "asyncio" -@pytest.mark.anyio -async def test_list_topics_maps_openalex_response_to_model(): - def handler(_: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ - { - "id": "https://openalex.org/T12419", - "display_name": "Machine learning", - "description": "Methods that learn from data.", - "keywords": ["machine learning", "classification"], - "subfield": { - "id": "https://openalex.org/subfields/1702", - "display_name": "Artificial Intelligence", - }, - "field": { - "id": "https://openalex.org/fields/17", - "display_name": "Computer Science", - }, - "domain": { - "id": "https://openalex.org/domains/4", - "display_name": "Physical Sciences", - }, - "works_count": 123, - "cited_by_count": 456, - "ids": { - "openalex": "https://openalex.org/T12419", - "wikipedia": "https://en.wikipedia.org/wiki/Machine_learning", - }, - "works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419", - "created_date": "2023-12-25", - "updated_date": "2023-11-07T05:31:56Z", - } - ], - "group_by": [ - { - "key": "https://openalex.org/domains/4", - "key_display_name": "Physical Sciences", - "count": 1, - } - ], - }, - ) +class StubTopicsClient: + def __init__(self, response): + self.response = response + self.kwargs = None - client = OpenAlexTopicsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), + async def list_topics(self, **kwargs): + self.kwargs = kwargs + return self.response + + +@pytest.mark.anyio +async def test_list_topics_maps_elasticsearch_response_to_model(): + client = StubTopicsClient( + { + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "field": {"display_name": "Computer Science"}, + "subfield": {"display_name": "Artificial Intelligence"}, + "domain": {"display_name": "Physical Sciences"}, + "works_count": 123, + "cited_by_count": 456, + "ids": {"openalex": "https://openalex.org/T12419"}, + } + ], + } ) result = await logic.list_topics(search="machine learning", client=client) assert result.meta.count == 1 - topic = result.results[0] - assert topic.display_name == "Machine learning" - assert topic.var_field.display_name == "Computer Science" - assert topic.subfield.display_name == "Artificial Intelligence" - assert topic.domain.display_name == "Physical Sciences" - assert topic.ids.openalex == "https://openalex.org/T12419" - assert result.group_by[0].key_display_name == "Physical Sciences" + assert result.results[0].var_field.display_name == "Computer Science" + assert client.kwargs["search"] == "machine learning" @pytest.mark.anyio async def test_list_topics_rejects_sample_with_sort(): - with pytest.raises(BadRequestException) as exc_info: + with pytest.raises(BadRequestException): await logic.list_topics(sample=10, sort="works_count:desc") -@pytest.mark.anyio -async def test_list_topics_accepts_practical_openalex_type_variants(): - def handler(_: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "meta": {"count": "1", "page": "1", "per_page": "25"}, - "results": [ - { - "id": 123, - "display_name": 456, - "description": True, - "keywords": ["topic", 123], - "subfield": {"id": 1, "display_name": 2}, - "field": {"id": 3, "display_name": 4}, - "domain": {"id": 5, "display_name": 6}, - "works_count": "12.0", - "cited_by_count": False, - "ids": {"openalex": 123, "wikipedia": 456}, - "created_date": "2023-12-25T10:11:12Z", - "updated_date": "2023-12-25", - } - ], - "group_by": [{"key": True, "count": "1"}], - }, - ) - - client = OpenAlexTopicsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - result = await logic.list_topics(client=client) - - topic = result.results[0] - assert topic.id == "123" - assert topic.display_name == "456" - assert topic.description == "true" - assert topic.keywords == ["topic", "123"] - assert topic.works_count == 12 - assert topic.cited_by_count is None - assert topic.var_field.id == "3" - assert topic.domain.display_name == "6" - assert topic.ids.wikipedia == "456" - assert topic.created_date.isoformat() == "2023-12-25" - assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00" - assert result.group_by[0].key == "true" - - @pytest.mark.anyio async def test_autocomplete_topics_returns_frontend_options(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.url.params["search"] == "machine learning" - assert request.url.params["filter"] == ( - "domain.id:https://openalex.org/domains/4," - "field.id:https://openalex.org/fields/17," - "subfield.id:https://openalex.org/subfields/1702" - ) - assert request.url.params["sort"] == "works_count:desc" - assert request.url.params["per_page"] == "5" - assert request.url.params["select"] == ( - "id,display_name,description,keywords,subfield,field,domain," - "works_count,cited_by_count,ids" - ) - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "db_response_time_ms": 12}, - "results": [ - { - "id": "https://openalex.org/T12419", - "display_name": "Machine learning", - "description": "Methods that learn from data.", - "field": {"display_name": "Computer Science"}, - "subfield": {"display_name": "Artificial Intelligence"}, - "domain": {"display_name": "Physical Sciences"}, - "works_count": 123, - "cited_by_count": 456, - "ids": {"openalex": "https://openalex.org/T12419"}, - } - ], - }, - ) - - client = OpenAlexTopicsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), + client = StubTopicsClient( + { + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "field": {"display_name": "Computer Science"}, + "subfield": {"display_name": "Artificial Intelligence"}, + "domain": {"display_name": "Physical Sciences"}, + "works_count": 123, + "cited_by_count": 456, + "ids": {"openalex": "https://openalex.org/T12419"}, + } + ], + } ) - result = await logic.autocomplete_topics( - query="machine learning", - domain_id="https://openalex.org/domains/4", - field_id="https://openalex.org/fields/17", - subfield_id="https://openalex.org/subfields/1702", - limit=5, - client=client, - ) + result = await logic.autocomplete_topics(query="machine learning", limit=5, client=client) - assert result.meta.count == 1 - assert result.meta.db_response_time_ms == 12 - assert len(result.results) == 1 - option = result.results[0] - assert option.id == "https://openalex.org/T12419" - assert option.display_name == "Machine learning" - assert option.hint == ( - "Computer Science · Artificial Intelligence · Physical Sciences" - ) - assert option.works_count == 123 - assert option.cited_by_count == 456 - assert option.entity_type == "topic" - assert option.external_id == "https://openalex.org/T12419" + assert result.results[0].hint == "Computer Science · Artificial Intelligence · Physical Sciences" + assert result.results[0].entity_type == "topic" + assert client.kwargs["sort"] == "works_count:desc" diff --git a/service/src/main/inse/topics/test_search_client.py b/service/src/main/inse/topics/test_search_client.py index 69c16a82..324c529b 100644 --- a/service/src/main/inse/topics/test_search_client.py +++ b/service/src/main/inse/topics/test_search_client.py @@ -1,6 +1,8 @@ -import httpx +from unittest.mock import AsyncMock, patch + import pytest +from inse.model import ESCluster from inse.topics.search_client import OpenAlexTopicsClient @@ -9,67 +11,39 @@ def anyio_backend(): return "asyncio" -def test_list_topics_params_include_openalex_query_parameters(): - client = OpenAlexTopicsClient(api_key="test-key") - - params = client.list_topics_params( +def test_list_topics_query_builds_elasticsearch_query(): + body = OpenAlexTopicsClient().list_topics_query( search="machine learning", - filter="domain.id:4,works_count:>1000", + filter="domain.id:https://openalex.org/domains/4,works_count:>1000", sort="works_count:desc", - group_by="domain.id", per_page=10, page=2, select="id,display_name", ) - assert params == { - "search": "machine learning", - "filter": "domain.id:4,works_count:>1000", - "sort": "works_count:desc", - "group_by": "domain.id", - "per_page": 10, - "page": 2, - "select": "id,display_name", - "api_key": "test-key", - } - - -def test_list_topics_params_prefers_cursor_over_page(): - client = OpenAlexTopicsClient(api_key="test-key") - - params = client.list_topics_params(cursor="*", page=3) - - assert params["cursor"] == "*" - assert "page" not in params + assert body["from"] == 10 + assert body["size"] == 10 + assert body["_source"] == ["id", "display_name"] + assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "machine learning" + assert {"term": {"domain.id.keyword": "https://openalex.org/domains/4"}} in body["query"]["bool"]["filter"] + assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"] + assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}] @pytest.mark.anyio -async def test_list_topics_calls_openalex_topics_endpoint(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.method == "GET" - assert request.url.path == "/topics" - assert request.url.params["search"] == "machine learning" - assert request.url.params["api_key"] == "test-key" - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ - { - "id": "https://openalex.org/T12419", - "display_name": "Machine learning", - } - ], - }, - ) - - client = OpenAlexTopicsClient( - base_url="https://api.openalex.org", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - result = await client.list_topics(search="machine learning") +async def test_list_topics_calls_elasticsearch_and_maps_hits(): + response = { + "hits": { + "total": {"value": 1}, + "hits": [{"_source": {"id": "T1", "display_name": "Machine learning"}}], + } + } + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search: + search.return_value = response + result = await OpenAlexTopicsClient(index="topicvectors").list_topics(search="machine") + search.assert_awaited_once() + assert search.await_args.kwargs["index"] == "topicvectors" + assert search.await_args.kwargs["cluster"] == ESCluster.NES assert result["meta"]["count"] == 1 assert result["results"][0]["display_name"] == "Machine learning" diff --git a/service/src/main/inse/works/test_openalex_logic.py b/service/src/main/inse/works/test_openalex_logic.py index 48f01cef..b74c2279 100644 --- a/service/src/main/inse/works/test_openalex_logic.py +++ b/service/src/main/inse/works/test_openalex_logic.py @@ -1,176 +1,94 @@ -import json - -import httpx import pytest -from fastapi import HTTPException from inse.works import logic -from inse.works.search_client import OpenAlexWorksSearchClient -# @pytest.fixture -# def anyio_backend(): -# return "asyncio" +@pytest.fixture +def anyio_backend(): + return "asyncio" -# @pytest.mark.anyio -# async def test_get_author_works_maps_elasticsearch_response_to_work_page(): -# def handler(request: httpx.Request) -> httpx.Response: -# return httpx.Response( -# 200, -# json={ -# "hits": { -# "total": {"value": 1}, -# "hits": [ -# { -# "_source": { -# "id": "https://openalex.org/W2741809807", -# "doi": "https://doi.org/10.7717/peerj.4375", -# "display_name": "Example work", -# "type": "article", -# "language": "en", -# "publication_year": 2023, -# "cited_by_count": 42, -# "topics": [ -# { -# "id": "https://openalex.org/T10102", -# "display_name": "Machine learning", -# "score": 0.91, -# } -# ], -# "primary_location": { -# "source": { -# "id": "https://openalex.org/S123", -# "display_name": "Example Source", -# "issn": None, -# } -# }, -# "authorships": [ -# { -# "author": { -# "id": "https://openalex.org/A5023888391", -# "display_name": "Example Author", -# } -# } -# ], -# } -# } -# ], -# }, -# }, -# ) - -# client = OpenAlexWorksSearchClient( -# base_url="https://project.nes.uni-due.de/elastic", -# api_key="test-key", -# transport=httpx.MockTransport(handler), -# ) - -# page = await logic.get_author_works("A5023888391", page=1, size=20, client=client) - -# assert page.total == 1 -# assert page.elements[0].doi == "https://doi.org/10.7717/peerj.4375" -# assert page.elements[0].title == "Example work" -# assert page.elements[0].type == "article" -# assert page.elements[0].language == "en" -# assert page.elements[0].publication_year == 2023 -# assert page.elements[0].cited_by_count == 42 -# assert page.elements[0].topics == ["Machine learning"] +def work_hit(identifier: str, title: str) -> dict: + return { + "_source": { + "id": f"https://openalex.org/{identifier}", + "doi": f"https://doi.org/10.1234/{identifier.lower()}", + "title": title, + "display_name": title, + "type": "article", + "language": "en", + "publication_year": 2024, + "publication_date": "2024-01-01", + "cited_by_count": 42, + "topics": [ + { + "id": "https://openalex.org/T10102", + "display_name": "Machine learning", + "score": 0.91, + } + ], + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5023888391", + "display_name": "Example Author", + } + } + ], + } + } -# @pytest.mark.anyio -# async def test_get_all_author_works_collects_all_pages(): -# requested_pages = [] +class StubWorksSearchClient: + def __init__(self, pages: list[list[dict]], total: int): + self.pages = pages + self.total = total + self.calls: list[dict] = [] -# def handler(request: httpx.Request) -> httpx.Response: -# payload = json_from_request(request) -# requested_pages.append(payload["from"] // payload["size"] + 1) -# page = requested_pages[-1] -# hits = [ -# { -# "_source": { -# "id": f"https://openalex.org/W{page}", -# "doi": f"https://doi.org/10.1234/example-{page}", -# "title": f"Example work {page}", -# "display_name": f"Example work {page}", -# "type": "article", -# "language": "en", -# "publication_year": 2024, -# "publication_date": "2024-01-01", -# "cited_by_count": page, -# "primary_location": { -# "is_oa": True, -# "source": { -# "id": "https://openalex.org/S123", -# "display_name": "Example Source", -# }, -# }, -# "authorships": [ -# { -# "author": { -# "id": "https://openalex.org/A5023888391", -# "display_name": "Example Author", -# }, -# }, -# ], -# "topics": [], -# } -# } -# ] -# return httpx.Response( -# 200, -# json={ -# "hits": { -# "total": {"value": 2}, -# "hits": hits, -# }, -# }, -# ) - -# client = OpenAlexWorksSearchClient( -# base_url="https://project.nes.uni-due.de/elastic", -# api_key="test-key", -# transport=httpx.MockTransport(handler), -# ) - -# works = await logic.get_all_author_works("A5023888391", client=client) - -# assert requested_pages == [1, 2] -# assert works.total == 2 -# assert [work.title for work in works.elements] == ["Example work 1", "Example work 2"] -# assert works.elements[0].id == "https://openalex.org/W1" -# assert works.elements[0].display_name == "Example work 1" -# assert works.elements[0].publication_date == "2024-01-01" -# assert works.elements[0].primary_location.is_oa is True -# assert works.elements[0].authorships[0].author.id == "https://openalex.org/A5023888391" + async def search_author_works(self, author_id, page, size, **filters): + self.calls.append( + { + "author_id": author_id, + "page": page, + "size": size, + **filters, + } + ) + hits = self.pages[page - 1] if page <= len(self.pages) else [] + return {"hits": {"total": {"value": self.total}, "hits": hits}} -# @pytest.mark.anyio -# async def test_get_author_works_maps_missing_api_key_to_service_unavailable(): -# client = OpenAlexWorksSearchClient(api_key="") +@pytest.mark.anyio +async def test_get_author_works_maps_elasticsearch_response_to_work_page(): + client = StubWorksSearchClient( + pages=[[work_hit("W2741809807", "Example work")]], + total=1, + ) -# with pytest.raises(HTTPException) as exc: -# await logic.get_author_works("A5023888391", page=1, size=20, client=client) + page = await logic.get_author_works( + "A5023888391", + page=1, + size=20, + publication_year=[2024], + client=client, + ) -# assert exc.value.status_code == 503 + assert page.total == 1 + assert page.last_page is True + assert page.elements[0].title == "Example work" + assert page.elements[0].doi == "https://doi.org/10.1234/w2741809807" + assert client.calls[0]["publication_year"] == [2024] -# @pytest.mark.anyio -# async def test_get_author_works_maps_elasticsearch_errors_to_bad_gateway(): -# def handler(request: httpx.Request) -> httpx.Response: -# return httpx.Response(500, json={"error": "upstream failed"}) +@pytest.mark.anyio +async def test_get_all_author_works_collects_all_elasticsearch_pages(): + first_page = [work_hit(f"W{number}", f"Example work {number}") for number in range(100)] + second_page = [work_hit("W100", "Example work 100")] + client = StubWorksSearchClient(pages=[first_page, second_page], total=101) -# client = OpenAlexWorksSearchClient( -# base_url="https://project.nes.uni-due.de/elastic", -# api_key="test-key", -# transport=httpx.MockTransport(handler), -# ) + response = await logic.get_all_author_works("A5023888391", client=client) -# with pytest.raises(HTTPException) as exc: -# await logic.get_author_works("A5023888391", page=1, size=20, client=client) - -# assert exc.value.status_code == 502 - - -# def json_from_request(request: httpx.Request) -> dict: -# return json.loads(request.content.decode("utf-8")) + assert response.meta.count == 101 + assert len(response.results) == 101 + assert response.results[-1].title == "Example work 100" + assert [call["page"] for call in client.calls] == [1, 2] diff --git a/webapp/src/app/api/api/auth.service 2.ts b/webapp/src/app/api/api/auth.service 2.ts new file mode 100644 index 00000000..a927c77c --- /dev/null +++ b/webapp/src/app/api/api/auth.service 2.ts @@ -0,0 +1,871 @@ +/** + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { AccessResponse } from '../model/accessResponse'; +// @ts-ignore +import { AccessToken } from '../model/accessToken'; +// @ts-ignore +import { AccountPage } from '../model/accountPage'; +// @ts-ignore +import { AccountProfile } from '../model/accountProfile'; +// @ts-ignore +import { BodyChangePassword } from '../model/bodyChangePassword'; +// @ts-ignore +import { BodyGetAccessToken } from '../model/bodyGetAccessToken'; +// @ts-ignore +import { BodyLogin } from '../model/bodyLogin'; +// @ts-ignore +import { BodyRequestOtk } from '../model/bodyRequestOtk'; +// @ts-ignore +import { CreateAccountRequest } from '../model/createAccountRequest'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { LoginResponse } from '../model/loginResponse'; +// @ts-ignore +import { OrganizationProfile } from '../model/organizationProfile'; +// @ts-ignore +import { UpdateAccountRequest } from '../model/updateAccountRequest'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class AuthService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Change Password + * Change the user\'s password and invalidate existing tokens. + * @endpoint post /api/auth/v2/change-password + * @param bodyChangePassword + * @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 { + if (bodyChangePassword === null || bodyChangePassword === undefined) { + throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.'); + } + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/change-password`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyChangePassword, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Create Account + * @endpoint post /api/accounts + * @param createAccountRequest + * @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 { + if (createAccountRequest === null || createAccountRequest === undefined) { + throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.'); + } + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: createAccountRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Delete Account + * @endpoint delete /api/accounts/{account_id} + * @param accountId + * @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 { + if (accountId === null || accountId === undefined) { + throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.'); + } + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('delete', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Get Access Token + * Retrieve an access token for the authenticated user. + * @endpoint post /api/auth/v2/access + * @param bodyGetAccessToken + * @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 { + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/access`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyGetAccessToken, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Get Current Account + * @endpoint get /api/accounts/me + * @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 { + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/me`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Health Check + * @endpoint get /api/auth/v2/health + * @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 healthCheckApiAuthV2HealthGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/health`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * List Organizations + * @endpoint get /api/accounts/organizations + * @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 { + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * List Accounts + * @endpoint get /api/accounts + * @param page + * @param pageSize + * @param offset + * @param search + * @param organizationId + * @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 { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + offset, 'offset'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + organizationId, 'organization_id'); + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Login with One-Time Key + * Login using a one-time key (OTK) sent to the user\'s email. + * @endpoint post /api/auth/v2/login + * @param bodyLogin + * @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 login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (bodyLogin === null || bodyLogin === undefined) { + throw new Error('Required parameter bodyLogin was null or undefined when calling login.'); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/login`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyLogin, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Logout + * Logout the authenticated user. + * @endpoint post /api/auth/v2/logout + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/logout`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Refresh Access Token + * Refresh the access token using a valid refresh token. + * @endpoint post /api/auth/v2/refresh + * @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 { + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/refresh`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Request One-Time Key + * Request a one-time key (OTK) for authentication using email and password. + * @endpoint post /api/auth/v2/request-otk + * @param bodyRequestOtk + * @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: 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.'); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/request-otk`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyRequestOtk, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Update Account + * @endpoint put /api/accounts/{account_id} + * @param accountId + * @param updateAccountRequest + * @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 { + if (accountId === null || accountId === undefined) { + throw new Error('Required parameter accountId was null or undefined when calling updateAccount.'); + } + if (updateAccountRequest === null || updateAccountRequest === undefined) { + throw new Error('Required parameter updateAccountRequest was null or undefined when calling updateAccount.'); + } + + 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' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('put', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: updateAccountRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/model/accessResponse 2.ts b/webapp/src/app/api/model/accessResponse 2.ts new file mode 100644 index 00000000..f1610895 --- /dev/null +++ b/webapp/src/app/api/model/accessResponse 2.ts @@ -0,0 +1,24 @@ +/** + * 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 { RefreshToken } from './refreshToken'; +import { AccessToken } from './accessToken'; + + +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 2.ts b/webapp/src/app/api/model/accessToken 2.ts new file mode 100644 index 00000000..ce3ea930 --- /dev/null +++ b/webapp/src/app/api/model/accessToken 2.ts @@ -0,0 +1,55 @@ +/** + * 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 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. + */ + 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 AccessToken { +} + + diff --git a/webapp/src/app/api/model/accountPage 2.ts b/webapp/src/app/api/model/accountPage 2.ts new file mode 100644 index 00000000..c92c4ba3 --- /dev/null +++ b/webapp/src/app/api/model/accountPage 2.ts @@ -0,0 +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 { AccountProfile } from './accountProfile'; + + +export interface AccountPage { + items: Array; + total: number; + page: number; + page_size: number; +} + diff --git a/webapp/src/app/api/model/accountProfile 2.ts b/webapp/src/app/api/model/accountProfile 2.ts new file mode 100644 index 00000000..17a68e22 --- /dev/null +++ b/webapp/src/app/api/model/accountProfile 2.ts @@ -0,0 +1,28 @@ +/** + * 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 { UserRole } from './userRole'; + + +export interface AccountProfile { + id: string; + email: string; + name: string; + role: UserRole; + organization_id: string; + organization_name: string; + deleted: boolean; + is_current?: boolean; + is_real_account?: boolean; + is_impersonating?: boolean; +} +export namespace AccountProfile { +} + + diff --git a/webapp/src/app/api/model/bodyChangePassword 2.ts b/webapp/src/app/api/model/bodyChangePassword 2.ts new file mode 100644 index 00000000..b6454f0e --- /dev/null +++ b/webapp/src/app/api/model/bodyChangePassword 2.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 BodyChangePassword { + /** + * Current password + */ + current_password: string; + /** + * New password + */ + new_password: string; +} + diff --git a/webapp/src/app/api/model/bodyGetAccessToken 2.ts b/webapp/src/app/api/model/bodyGetAccessToken 2.ts new file mode 100644 index 00000000..8e5df2ed --- /dev/null +++ b/webapp/src/app/api/model/bodyGetAccessToken 2.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 BodyGetAccessToken { + /** + * User\'s account ID + */ + real_account_id: string; + /** + * Effective account ID for the access token + */ + effective_account_id: string; +} + diff --git a/webapp/src/app/api/model/bodyLogin 2.ts b/webapp/src/app/api/model/bodyLogin 2.ts new file mode 100644 index 00000000..f4022b0b --- /dev/null +++ b/webapp/src/app/api/model/bodyLogin 2.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 BodyLogin { + /** + * User\'s account ID + */ + account_id: string; + /** + * One-time code sent to user\'s email + */ + email_code: string; +} + diff --git a/webapp/src/app/api/model/bodyRequestOtk 2.ts b/webapp/src/app/api/model/bodyRequestOtk 2.ts new file mode 100644 index 00000000..ba1a396d --- /dev/null +++ b/webapp/src/app/api/model/bodyRequestOtk 2.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 BodyRequestOtk { + /** + * User\'s email address + */ + email: string; + /** + * User\'s password + */ + password: string; +} + diff --git a/webapp/src/app/api/model/createAccountRequest 2.ts b/webapp/src/app/api/model/createAccountRequest 2.ts new file mode 100644 index 00000000..3be9003b --- /dev/null +++ b/webapp/src/app/api/model/createAccountRequest 2.ts @@ -0,0 +1,24 @@ +/** + * 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 { UserRole } from './userRole'; + + +export interface CreateAccountRequest { + email: string; + name: string; + role?: UserRole; + organization_id: string; + password: string; + openalex_person_id?: string | null; +} +export namespace CreateAccountRequest { +} + + diff --git a/webapp/src/app/api/model/idToken 2.ts b/webapp/src/app/api/model/idToken 2.ts new file mode 100644 index 00000000..e6a88cd3 --- /dev/null +++ b/webapp/src/app/api/model/idToken 2.ts @@ -0,0 +1,42 @@ +/** + * 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'; + + +export interface IdToken { + /** + * The type of the token, which is always ID_TOKEN for this class. + */ + token_type?: TokenType; + /** + * The unique identifier of the real account associated with this token. + */ + 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; +} +export namespace IdToken { +} + + diff --git a/webapp/src/app/api/model/loginResponse 2.ts b/webapp/src/app/api/model/loginResponse 2.ts new file mode 100644 index 00000000..ace8f15d --- /dev/null +++ b/webapp/src/app/api/model/loginResponse 2.ts @@ -0,0 +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'; + + +export interface LoginResponse { + /** + * The ID token issued upon successful login. + */ + id_token: IdToken; +} + diff --git a/webapp/src/app/api/model/refreshToken 2.ts b/webapp/src/app/api/model/refreshToken 2.ts new file mode 100644 index 00000000..89506b70 --- /dev/null +++ b/webapp/src/app/api/model/refreshToken 2.ts @@ -0,0 +1,55 @@ +/** + * 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 2.ts b/webapp/src/app/api/model/tokenType 2.ts new file mode 100644 index 00000000..06231c11 --- /dev/null +++ b/webapp/src/app/api/model/tokenType 2.ts @@ -0,0 +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 const TokenType = { + Id: 'ID', + Refresh: 'REFRESH', + Access: 'ACCESS' +} as const; +export type TokenType = typeof TokenType[keyof typeof TokenType]; + diff --git a/webapp/src/app/api/model/updateAccountRequest 2.ts b/webapp/src/app/api/model/updateAccountRequest 2.ts new file mode 100644 index 00000000..15b0043d --- /dev/null +++ b/webapp/src/app/api/model/updateAccountRequest 2.ts @@ -0,0 +1,25 @@ +/** + * 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 { UserRole } from './userRole'; + + +export interface UpdateAccountRequest { + email?: string | null; + name?: string | null; + role?: UserRole | null; + organization_id?: string | null; + password?: string | null; + openalex_person_id?: string | null; + deleted?: boolean | null; +} +export namespace UpdateAccountRequest { +} + + diff --git a/webapp/src/app/api/model/userRole 2.ts b/webapp/src/app/api/model/userRole 2.ts new file mode 100644 index 00000000..83b5c595 --- /dev/null +++ b/webapp/src/app/api/model/userRole 2.ts @@ -0,0 +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 const UserRole = { + SuperAdmin: 'SUPER_ADMIN', + Admin: 'ADMIN', + Manager: 'MANAGER', + User: 'USER' +} as const; +export type UserRole = typeof UserRole[keyof typeof UserRole]; + diff --git a/webapp/src/app/modules/accounts/account-dialog.component 2.html b/webapp/src/app/modules/accounts/account-dialog.component 2.html new file mode 100644 index 00000000..0e08dbc8 --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component 2.html @@ -0,0 +1,71 @@ +

+ {{ data.mode === 'create' ? 'Account erstellen' : 'Account bearbeiten' }} +

+ + + + + + + + + diff --git a/webapp/src/app/modules/accounts/account-dialog.component 2.scss b/webapp/src/app/modules/accounts/account-dialog.component 2.scss new file mode 100644 index 00000000..ccc5f64e --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component 2.scss @@ -0,0 +1,22 @@ +.account-form { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px 14px; + min-width: min(680px, calc(100vw - 64px)); + padding-top: 4px; +} + +.account-form mat-form-field { + width: 100%; +} + +mat-dialog-actions { + padding: 12px 24px 20px; +} + +@media (max-width: 720px) { + .account-form { + grid-template-columns: 1fr; + min-width: 0; + } +} diff --git a/webapp/src/app/modules/accounts/account-dialog.component 2.ts b/webapp/src/app/modules/accounts/account-dialog.component 2.ts new file mode 100644 index 00000000..a10cff43 --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component 2.ts @@ -0,0 +1,153 @@ +import { CommonModule } from '@angular/common'; +import { Component, inject } from '@angular/core'; +import { + FormControl, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +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, + AccountProfile, + AccountRole, + CreateAccountPayload, + OrganizationProfile, +} from '../../shared/services/account-management.service'; + +export type AccountDialogMode = 'create' | 'edit'; + +export interface AccountDialogData { + mode: AccountDialogMode; + account?: AccountProfile; + organizations: OrganizationProfile[]; + canSelectOrganization: boolean; + roles: AccountRole[]; +} + +export type AccountDialogResult = + | { mode: 'create'; payload: CreateAccountPayload } + | { mode: 'edit'; accountId: string; payload: AccountPayload }; + +@Component({ + selector: 'app-account-dialog', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatSelectModule, + ], + templateUrl: './account-dialog.component.html', + styleUrl: './account-dialog.component.scss', + standalone: true, +}) +export class AccountDialogComponent { + private readonly dialogRef = + inject< + MatDialogRef + >(MatDialogRef); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly form = new FormGroup({ + email: new FormControl(this.data.account?.email ?? '', [ + Validators.required, + Validators.email, + ]), + name: new FormControl(this.data.account?.name ?? '', [ + Validators.required, + ]), + role: new FormControl(this.data.account?.role ?? 'USER', [ + Validators.required, + ]), + organizationId: new FormControl( + this.data.account?.organization_id ?? + (this.data.organizations.length === 1 + ? this.data.organizations[0].id + : ''), + [Validators.required], + ), + password: new FormControl('', [ + ...(this.data.mode === 'create' ? [Validators.required] : []), + Validators.minLength(8), + ]), + }); + + protected submit(): void { + if (this.form.invalid) { + this.form.markAllAsTouched(); + return; + } + + const value = this.form.getRawValue(); + + if (this.data.mode === 'create') { + this.dialogRef.close({ + mode: 'create', + payload: { + email: value.email ?? '', + name: value.name ?? '', + role: value.role ?? 'USER', + organization_id: value.organizationId ?? '', + password: value.password ?? '', + }, + }); + return; + } + + const account = this.data.account!; + const payload: AccountPayload = {}; + + const email = (value.email ?? '').trim(); + const name = (value.name ?? '').trim(); + const role = value.role ?? account.role; + const organizationId = value.organizationId ?? account.organization_id; + const password = value.password?.trim() ?? ''; + + if (email !== account.email) { + payload.email = email; + } + + if (name !== account.name) { + payload.name = name; + } + + if (role !== account.role) { + payload.role = role; + } + + if (password) { + payload.password = password; + } + + if ( + this.data.canSelectOrganization && + organizationId && + organizationId !== account.organization_id + ) { + payload.organization_id = organizationId; + } + + this.dialogRef.close({ + mode: 'edit', + accountId: account.id, + payload, + }); + } + + protected close(): void { + this.dialogRef.close(undefined); + } +} diff --git a/webapp/src/app/modules/accounts/accounts.component 2.html b/webapp/src/app/modules/accounts/accounts.component 2.html new file mode 100644 index 00000000..8137c2f2 --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component 2.html @@ -0,0 +1,146 @@ +
+ + +
+ + 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... + } +
+ +
+ + + + + + + + + + + + + @for (account of accounts; track account.id) { + + + + + + + + + } @empty { + + + + } + +
NameE-MailOrganisationRolleStatusAktionen
+ + {{ account.email }}{{ account.organization_name }} + {{ account.role }} + + + {{ account.deleted ? 'deleted' : 'active' }} + + +
+ + + +
+
Keine Accounts gefunden.
+
+ + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component 2.scss b/webapp/src/app/modules/accounts/accounts.component 2.scss new file mode 100644 index 00000000..53149e49 --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component 2.scss @@ -0,0 +1,147 @@ +.accounts-page { + display: flex; + flex-direction: column; + gap: 20px; + padding: 24px; +} + +.page-header, +.filters, +.table-header, +.pagination, +.row-actions { + display: flex; + align-items: center; +} + +.page-header { + justify-content: space-between; + gap: 16px; +} + +h1, +h2, +p { + margin: 0; +} + +.page-header p { + color: #64748b; + margin-top: 6px; +} + +.filters { + gap: 12px; + flex-wrap: wrap; +} + +.filters mat-form-field { + width: min(320px, 100%); +} + +.filter-actions { + display: flex; + gap: 8px; + margin-bottom: 22px; +} + +.table-panel { + border: 1px solid #d7dde6; + border-radius: 8px; + background: #fff; +} + +.table-header { + justify-content: space-between; + padding: 16px; + border-bottom: 1px solid #e5e7eb; +} + +.table-header span { + color: #64748b; +} + +.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; +} + +.link-button { + border: 0; + background: transparent; + color: #1d4ed8; + padding: 0; + font: inherit; + cursor: pointer; +} + +.role, +.status { + display: inline-flex; + align-items: center; + min-height: 24px; + border-radius: 999px; + padding: 2px 10px; + background: #eef2ff; + color: #3730a3; + font-size: 12px; + font-weight: 700; +} + +.status { + background: #dcfce7; + color: #166534; +} + +.status--deleted { + background: #fee2e2; + 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) { + .accounts-page { + padding: 16px; + } + + .page-header { + align-items: flex-start; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/accounts/accounts.component 2.ts b/webapp/src/app/modules/accounts/accounts.component 2.ts new file mode 100644 index 00000000..845f0990 --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component 2.ts @@ -0,0 +1,247 @@ +import { CommonModule } from '@angular/common'; +import { Component, OnInit, inject } from '@angular/core'; +import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +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 { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +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'; + +@Component({ + selector: 'app-accounts', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatIconModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + MatSnackBarModule, + MatDialogModule, + ], + 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); + + protected get availableRoles(): AccountRole[] { + 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(''), + }); + + ngOnInit(): void { + 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; + }, + }); + } + + protected applyFilters(): void { + this.loadAccounts(0); + } + + protected resetFilters(): void { + this.filterForm.reset({ search: '', organizationId: '' }); + this.loadAccounts(0); + } + + protected startCreate(): void { + this.openAccountDialog({ mode: 'create' }); + } + + protected startEdit(account: AccountProfile): void { + this.openAccountDialog({ mode: 'edit', account }); + } + + private saveDialogResult(result: AccountDialogResult): void { + const request = + result.mode === 'create' + ? this.accountService.createAccount(result.payload) + : this.accountService.updateAccount(result.accountId, result.payload); + + request.subscribe({ + next: () => { + this.snackBar.open('Account wurde gespeichert.', 'OK', { + duration: 3000, + }); + this.loadAccounts(0); + }, + error: (error) => { + const message = + error.status === 409 + ? 'Diese E-Mail-Adresse wird bereits verwendet.' + : 'Account konnte nicht gespeichert werden.'; + this.snackBar.open(message, 'OK', { duration: 5000 }); + }, + }); + } + + private openAccountDialog(data: { + mode: 'create' | 'edit'; + account?: AccountProfile; + }): void { + import('./account-dialog.component').then(({ AccountDialogComponent }) => { + const dialogRef = this.dialog.open< + AccountDialogComponent, + { + mode: 'create' | 'edit'; + account?: AccountProfile; + organizations: OrganizationProfile[]; + canSelectOrganization: boolean; + roles: AccountRole[]; + }, + AccountDialogResult | undefined + >(AccountDialogComponent, { + width: '760px', + maxWidth: 'calc(100vw - 32px)', + data: { + ...data, + organizations: this.organizations, + canSelectOrganization: + this.credentialService.isEffectiveSuperAdmin(), + roles: this.availableRoles, + }, + }); + + dialogRef.afterClosed().subscribe((result) => { + if (result) { + this.saveDialogResult(result); + } + }); + }); + } + + protected deleteAccount(account: AccountProfile): void { + if (account.is_current) { + return; + } + + this.accountService.deleteAccount(account.id).subscribe({ + next: () => { + this.snackBar.open('Account wurde deaktiviert.', 'OK', { + duration: 3000, + }); + this.loadAccounts(); + }, + error: () => { + this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', { + duration: 5000, + }); + }, + }); + } + + protected impersonate(account: AccountProfile): void { + if (!this.canImpersonate(account)) { + return; + } + + this.credentialService.impersonateAccount(account.id).subscribe({ + next: () => { + this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { + duration: 4000, + }); + this.router.navigate(['/dashboard']); + }, + error: () => { + this.snackBar.open( + 'Impersonation konnte nicht gestartet werden.', + 'OK', + { + duration: 5000, + }, + ); + }, + }); + } + + protected get canPageBack(): boolean { + return this.page > 0; + } + + protected get canPageForward(): boolean { + return (this.page + 1) * this.pageSize < this.total; + } + + protected canImpersonate(account: AccountProfile): boolean { + if (account.is_current || account.deleted) { + return false; + } + + if (this.credentialService.isEffectiveSuperAdmin()) { + return true; + } + + return ( + this.credentialService.isEffectiveAdmin() && + (account.role === 'MANAGER' || account.role === 'USER') + ); + } +} diff --git a/webapp/src/app/modules/organizations/organizations.component 2.html b/webapp/src/app/modules/organizations/organizations.component 2.html new file mode 100644 index 00000000..a6486b74 --- /dev/null +++ b/webapp/src/app/modules/organizations/organizations.component 2.html @@ -0,0 +1,105 @@ +
+ + +
+
+ {{ total }} Organisationen + @if (isLoading) { + Wird geladen... + } +
+ +
+ + + + + + + + + + + + @for (organization of organizations; track organization.id) { + + + + + + + + } @empty { + + + + } + +
NameExterne Institutions-IDMitgliederStatusAktionen
+ + {{ organization.other_inst_id || '–' }}{{ organization.member_count }} + + {{ organization.deleted ? 'deleted' : 'active' }} + + +
+ + +
+
Keine Organisationen gefunden.
+
+ + +
+
diff --git a/webapp/src/app/modules/organizations/organizations.component 2.scss b/webapp/src/app/modules/organizations/organizations.component 2.scss new file mode 100644 index 00000000..b558f858 --- /dev/null +++ b/webapp/src/app/modules/organizations/organizations.component 2.scss @@ -0,0 +1,130 @@ +.organizations-page { + display: flex; + flex-direction: column; + gap: 20px; + padding: 24px; +} + +.page-header, +.table-header, +.pagination, +.row-actions { + display: flex; + align-items: center; +} + +.page-header { + justify-content: space-between; + gap: 16px; +} + +h1, +p { + margin: 0; +} + +.page-header p, +.table-header span { + color: #64748b; +} + +.page-header 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; + min-height: 24px; + border-radius: 999px; + padding: 2px 10px; + background: #dcfce7; + color: #166534; + font-size: 12px; + font-weight: 700; +} + +.status--deleted { + background: #fee2e2; + 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; + } + + .page-header { + align-items: flex-start; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/organizations/organizations.component 2.ts b/webapp/src/app/modules/organizations/organizations.component 2.ts new file mode 100644 index 00000000..0d061c50 --- /dev/null +++ b/webapp/src/app/modules/organizations/organizations.component 2.ts @@ -0,0 +1,158 @@ +import { CommonModule } from '@angular/common'; +import { Component, OnInit, inject } 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'; + +@Component({ + selector: 'app-organizations', + imports: [ + CommonModule, + MatButtonModule, + MatDialogModule, + MatIconModule, + MatSnackBarModule, + ], + templateUrl: './organizations.component.html', + styleUrl: './organizations.component.scss', + standalone: true, +}) +export class OrganizationsComponent implements OnInit { + private readonly organizationService = inject(OrganizationManagementService); + private readonly dialog = inject(MatDialog); + private readonly snackBar = inject(MatSnackBar); + + protected organizations: OrganizationProfile[] = []; + protected total = 0; + protected page = 0; + protected readonly pageSize = 10; + protected isLoading = false; + + 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.'), + }); + } + + protected startCreate(): void { + this.openDialog({ mode: 'create' }); + } + + protected startEdit(organization: OrganizationProfile): void { + this.openDialog({ mode: 'edit', organization }); + } + + protected deleteOrganization(organization: OrganizationProfile): void { + if (organization.deleted) return; + + import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( + ({ ConfirmationDialogComponent }) => { + const dialogRef = this.dialog.open(ConfirmationDialogComponent, { + data: { + title: 'Organisation deaktivieren', + message: `Möchtest Du die Organisation „${organization.name}“ wirklich deaktivieren?`, + confirmText: 'Deaktivieren', + cancelText: 'Abbrechen', + }, + }); + + dialogRef.componentInstance.confirmDelete.subscribe(() => { + this.softDeleteOrganization(organization); + }); + }, + ); + } + + private softDeleteOrganization(organization: OrganizationProfile): void { + this.organizationService.deleteOrganization(organization.id).subscribe({ + next: () => { + this.snackBar.open('Organisation wurde deaktiviert.', 'OK', { + duration: 3000, + }); + this.loadOrganizations(); + }, + 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 }) => { + const dialogRef = this.dialog.open< + OrganizationDialogComponent, + OrganizationDialogData, + OrganizationDialogResult | undefined + >(OrganizationDialogComponent, { + width: '620px', + maxWidth: 'calc(100vw - 32px)', + data, + }); + + dialogRef.afterClosed().subscribe((result) => { + if (result) this.save(result); + }); + }, + ); + } + + private save(result: OrganizationDialogResult): void { + const request = + result.mode === 'create' + ? this.organizationService.createOrganization(result.payload) + : this.organizationService.updateOrganization( + result.organizationId, + result.payload, + ); + + request.subscribe({ + next: () => { + this.snackBar.open('Organisation wurde gespeichert.', 'OK', { + duration: 3000, + }); + this.loadOrganizations(0); + }, + error: (error) => + this.showError( + error.status === 409 + ? 'Eine Organisation mit diesem Namen existiert bereits.' + : 'Organisation konnte nicht gespeichert werden.', + ), + }); + } + + private showError(message: string): void { + this.snackBar.open(message, 'OK', { duration: 5000 }); + } +} diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index 183f3caf..521fddef 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -5,7 +5,6 @@ import { ViewChild, inject, } from '@angular/core'; -import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; import { @@ -37,7 +36,12 @@ import { switchMap, } from 'rxjs'; -import { Work, WorksService } from '../../api'; +import { + InstitutionsService, + TopicsService, + Work, + WorksService, +} from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; import { createLoadError } from '../../resolvers/utils/errorHandler'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; @@ -52,10 +56,6 @@ interface InstitutionAutocompleteOption { external_id?: string | null; } -interface InstitutionAutocompleteResponse { - results?: InstitutionAutocompleteOption[] | null; -} - interface TopicAutocompleteOption { id?: string | null; display_name?: string | null; @@ -66,10 +66,6 @@ interface TopicAutocompleteOption { external_id?: string | null; } -interface TopicAutocompleteResponse { - results?: TopicAutocompleteOption[] | null; -} - interface PublicationFilterQueryState { pageIndex: number; pageSize: number; @@ -184,7 +180,8 @@ export class PersonPublicationsComponent implements OnInit { private readonly route: ActivatedRoute, private readonly router: Router, private readonly workService: WorksService, - private readonly httpClient: HttpClient, + private readonly institutionsService: InstitutionsService, + private readonly topicsService: TopicsService, public readonly paginationService: PaginationService, private readonly snackBar: MatSnackBar, ) {} @@ -438,27 +435,14 @@ export class PersonPublicationsComponent implements OnInit { } private searchInstitutions(query: string) { - const params = new HttpParams().set('query', query).set('limit', '10'); - - const basePath = this.workService.configuration.basePath ?? ''; - return this.httpClient - .get( - `${basePath}/api/institutions/autocomplete`, - { - params, - }, - ) + return this.institutionsService + .autocompleteInstitutions(query, undefined, undefined, 10) .pipe(map((response) => response.results ?? [])); } private searchTopics(query: string) { - const params = new HttpParams().set('query', query).set('limit', '10'); - - const basePath = this.workService.configuration.basePath ?? ''; - return this.httpClient - .get(`${basePath}/api/topics/autocomplete`, { - params, - }) + return this.topicsService + .autocompleteTopics(query, undefined, undefined, undefined, 10) .pipe(map((response) => response.results ?? [])); } diff --git a/webapp/src/app/shared/guards/super-admin.guard 2.ts b/webapp/src/app/shared/guards/super-admin.guard 2.ts new file mode 100644 index 00000000..b1936483 --- /dev/null +++ b/webapp/src/app/shared/guards/super-admin.guard 2.ts @@ -0,0 +1,31 @@ +import { inject } 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); + + return credentialService.validating.pipe( + filter((validating) => !validating), + take(1), + switchMap(() => { + if (!credentialService.isAuthenticated.value) { + void router.navigate(['/login']); + return of(false); + } + + return credentialService.validateCurrentSession().pipe( + switchMap(() => { + if (!credentialService.isEffectiveSuperAdmin()) { + void router.navigate(['/dashboard']); + return of(false); + } + return of(true); + }), + catchError(() => of(false)), + ); + }), + ); +}; diff --git a/webapp/src/app/shared/services/account-management.service 2.ts b/webapp/src/app/shared/services/account-management.service 2.ts new file mode 100644 index 00000000..bc64586f --- /dev/null +++ b/webapp/src/app/shared/services/account-management.service 2.ts @@ -0,0 +1,117 @@ +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; + 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; +} + +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/organization-management.service 2.ts b/webapp/src/app/shared/services/organization-management.service 2.ts new file mode 100644 index 00000000..9597a005 --- /dev/null +++ b/webapp/src/app/shared/services/organization-management.service 2.ts @@ -0,0 +1,75 @@ +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/services/ui-focus.service 2.ts b/webapp/src/app/shared/services/ui-focus.service 2.ts new file mode 100644 index 00000000..ba149da8 --- /dev/null +++ b/webapp/src/app/shared/services/ui-focus.service 2.ts @@ -0,0 +1,14 @@ +import { Injectable } from '@angular/core'; + +@Injectable({ + providedIn: 'root', +}) +export class UiFocusService { + public blurActiveElement(): void { + const activeElement = document.activeElement; + + if (activeElement instanceof HTMLElement) { + activeElement.blur(); + } + } +}