From 81441dc5887dfe183ae29c3036d92d5462117d9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 23 Jun 2026 21:21:08 +0200 Subject: [PATCH 01/31] Added models for auth and account, cleaned up old models --- service/Dockerfile | 4 +- service/pyproject.toml | 3 +- service/src/main/inse/.env | 8 +- service/src/main/inse/auth/model.py | 163 +++++++++++++ service/src/main/inse/auth/router.py | 115 +++++++++ service/src/main/inse/auth/service.py | 27 +++ service/src/main/inse/config.py | 6 +- service/src/main/inse/database.py | 52 +++-- service/src/main/inse/exceptions.py | 5 + service/src/main/inse/logic.py | 286 ----------------------- service/src/main/inse/main.py | 23 +- service/src/main/inse/model.py | 27 +-- service/src/main/inse/persons/logic.py | 14 +- service/src/main/inse/projects/router.py | 1 - service/src/main/inse/schema.py | 24 -- service/src/main/inse/security.py | 75 ++++-- service/src/main/inse/service.py | 220 ----------------- service/src/main/inse/tags.py | 6 +- service/src/main/inse/works/service.py | 11 - service/uv.lock | 79 ++----- 20 files changed, 445 insertions(+), 704 deletions(-) create mode 100644 service/src/main/inse/auth/model.py create mode 100644 service/src/main/inse/auth/router.py create mode 100644 service/src/main/inse/auth/service.py delete mode 100644 service/src/main/inse/logic.py delete mode 100644 service/src/main/inse/schema.py delete mode 100644 service/src/main/inse/service.py diff --git a/service/Dockerfile b/service/Dockerfile index 90d1a619..d984e6b2 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -13,8 +13,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "pytest~=8.1.0" \ "httpx~=0.27.0" \ "python-multipart~=0.0.19"\ - "elasticsearch~=9.4.0" \ - "openai~=2.41.0" + "openai~=2.41.0" \ + "sqlmodel~=0.0.33" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/pyproject.toml b/service/pyproject.toml index 9e45ebc4..5307b6e8 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -7,7 +7,6 @@ requires-python = ">=3.12" dependencies = [ "cryptography~=42.0.0", "dotenv>=0.9.9", - "elasticsearch~=9.4.0", "fastapi~=0.115.0", "httpx~=0.27.0", "openai~=2.41.0", @@ -17,10 +16,10 @@ dependencies = [ "pytest~=8.1.0", "python-multipart~=0.0.19", "pyyaml~=6.0.1", - "sqlalchemy~=2.0.0", "uvicorn~=0.29.0", "sentence-transformers~=5.5.1", "torch", + "sqlmodel~=0.0.33", ] [[tool.uv.index]] diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 8a044d29..e886c6a1 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -1,6 +1,3 @@ -ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/ -ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ - LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 LLM_MODEL=gemma4-e4b @@ -8,15 +5,12 @@ LLM_MODEL=gemma4-e4b # Patent search (EPO + USPTO) PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== + ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== -LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ -LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 -LLM_MODEL=gemma4-e4b - # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2 diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py new file mode 100644 index 00000000..3ffe0cb2 --- /dev/null +++ b/service/src/main/inse/auth/model.py @@ -0,0 +1,163 @@ +from datetime import datetime +from enum import StrEnum +from typing import List +import uuid +from pydantic import BaseModel +from sqlmodel import Field, Relationship, SQLModel + + +class UserRole(StrEnum): + SUPER_ADMIN = "super_admin" + ADMIN = "admin" + MANAGER = "manager" + USER = "user" + + +class Durable(SQLModel): + deleted: bool = Field( + default=False, + nullable=False, + index=True, + description="Indicates whether the record is marked as deleted.", + ) + + +class Organization(SQLModel, 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, nullable=False, description="The 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, + 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): + 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.", + ) + + +class IdToken(Token): + pass + + +class AccessToken(Token): + 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.", + ) + role: UserRole = Field( + default=UserRole.USER, + index=True, + nullable=False, + description="The specific role this access token grants within its organization.", + ) + 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): + pass diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py new file mode 100644 index 00000000..5f9eaf6e --- /dev/null +++ b/service/src/main/inse/auth/router.py @@ -0,0 +1,115 @@ +import logging +from typing import Annotated +import uuid + +from fastapi import APIRouter, Body, Depends, status +from sqlmodel import Session + +from inse.tags import Tags + +import inse.auth.service as auth_service +from inse.auth.model import IdToken, RefreshToken +from inse.database import SessionDep + +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")], +): + auth_service.request_otk(email, 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, + email_code: Annotated[str, Body(description="One-time code sent to user's email")], +): + auth_service.login(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_access_token( + session: SessionDep, + account_id: Annotated[uuid.UUID, Body(description="User's account ID")], + id_token: IdToken, +): + auth_service.get_access_token(account_id, 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( + session: SessionDep, + refresh_token: RefreshToken, +): + auth_service.refresh_access_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: SessionDep, +): + auth_service.logout() + + +@router.post( + "/change-password", + summary="Change Password", + description="Change the user's password and optionally invalidate existing tokens.", + operation_id="changePassword", + responses={status.HTTP_200_OK: {"description": "Password changed successfully."}}, +) +async def change_password( + session: SessionDep, + new_password: Annotated[str, Body(description="New password", min_length=8)], + invalidate_tokens: Annotated[ + bool, Body(description="Whether to invalidate existing tokens") + ] = True, +): + auth_service.change_password(new_password, invalidate_tokens) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py new file mode 100644 index 00000000..e54f8550 --- /dev/null +++ b/service/src/main/inse/auth/service.py @@ -0,0 +1,27 @@ +import uuid + +from inse.auth.model import IdToken, RefreshToken + + +def request_otk(email: str, password: str): + pass + + +def login(emailCode: str): + pass + + +def get_access_token(account_id: uuid.UUID, id_token: IdToken): + pass + + +def refresh_access_token(refresh_token: RefreshToken): + pass + + +def logout(): + pass + + +def change_password(new_password: str, invalidate_tokens: bool = True): + pass diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index cdb123a1..9aa5fb17 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -7,7 +7,7 @@ that can be adjusted via environment variables. from functools import lru_cache import logging -from typing import Dict, List, Optional +from typing import Dict, List, Literal, Optional from pydantic_settings import BaseSettings, SettingsConfigDict from dotenv import load_dotenv @@ -34,12 +34,10 @@ class Settings(BaseSettings): openalex_api_key: Optional[str] = None openalex_api_timeout_seconds: float = 30.0 - # Patent Elasticsearch config patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic" patent_elasticsearch_api_key: Optional[str] = None - # LLM config llm_api_url: Optional[str] = None llm_api_key: Optional[str] = None @@ -64,6 +62,8 @@ class Settings(BaseSettings): logging_level: str = "DEBUG" + environment: Literal["dev", "prod"] = "dev" + settings = Settings() diff --git a/service/src/main/inse/database.py b/service/src/main/inse/database.py index ac3c24c7..728b750f 100644 --- a/service/src/main/inse/database.py +++ b/service/src/main/inse/database.py @@ -1,25 +1,33 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module contains the code to bootstrap the database - using our schema and sqlalchemy. -""" -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from . import schema -from . import config +from typing import Annotated -engine = create_engine(config.settings.database_url, echo=config.settings.database_debug) +from fastapi import Depends +from sqlmodel import SQLModel, Session, create_engine -if config.settings.database_init: - schema.Base.metadata.create_all(engine) +from inse import config -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -def get(): - ''' Returns a database connection and closes it when done. ''' - db = SessionLocal() - try: - yield db - finally: - db.close() +settings = config.get_settings() + +connect_args = {"check_same_thread": False} +engine = create_engine( + url=settings.database_url, + echo=settings.database_debug, + connect_args=connect_args, +) + + +def create_db_and_tables(): + """Creates the database and tables based on the SQLModel metadata.""" + SQLModel.metadata.create_all(engine) + + +def get_session(): + """Yields a database session for use in FastAPI endpoints. + + Yields: + Session: A SQLModel session connected to the database. + """ + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py index 772a9607..d7e2d972 100644 --- a/service/src/main/inse/exceptions.py +++ b/service/src/main/inse/exceptions.py @@ -1,3 +1,8 @@ class NotFoundException(Exception): + """Exception raised when a requested resource is not found. + + Args: + Exception (_type_): Base exception class. + """ def __init__(self, message: str): super().__init__(message) diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py deleted file mode 100644 index 19e9dda3..00000000 --- a/service/src/main/inse/logic.py +++ /dev/null @@ -1,286 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -This module defines the business logic for our -web service. -""" - -from typing import List -from typing import TypeVar -from typing import Optional -from typing import Type -from sqlalchemy.orm import Session -from sqlalchemy import select -from sqlalchemy import func -import logging -import httpx -import json -from . import schema -from . import model -from . import config - - -from inse.models.openalex.topic import Topic -from inse.models.openalex.topic_subfield import TopicSubfield -from inse.models.openalex.topic_field import TopicField -from inse.models.openalex.topic_domain import TopicDomain - - -logger = logging.getLogger(__name__) - - - -topic_cache_filename: str = "topic_hierarchy_cache.json" - -S = TypeVar('S', bound=schema.Base) -M = TypeVar('M', bound=model.BaseModel) - -def filter_none(): - return True - - -def get_page( - db: Session, - schema_type: Type[S], - model_type: Type[M], - offset: int, - limit: int, - filter=filter_none, -) -> model.Page[M]: - result = model.Page[model_type]() - result.offset = offset - result.total = get_count(db, schema_type, filter) - result.size = limit - if result.total > result.offset: - result.elements = get_elements(db, schema_type, offset, limit, filter) - else: - result.elements = [] - return result - - -def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int: - return db.scalar(select(func.count()).select_from(schema_type).where(filter)) - - -def get_elements( - db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none -) -> List[S]: - return db.scalars( - select(schema_type).where(filter).offset(offset).limit(limit) - ).all() - - -def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]: - return db.scalars( - select(schema_type).where(schema_type.id == element_id).limit(1) - ).first() - - -def delete_element(db: Session, schema_type: Type[S], element_id: int): - element = get_element(db, schema_type, element_id) - db.delete(element) - - -def insert_element(db: Session, value: S) -> S: - db.add(value) - db.flush() - db.refresh(value) - return value - - -def _load_topic_cache() -> dict: - """Loads the topic hierarchy cache from a JSON file.""" - import os - try: - cache_path = "/data/" + topic_cache_filename - if not os.path.exists(cache_path): - current_dir = os.path.dirname(__file__) - cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename) - with open(cache_path, "r", encoding="utf-8") as f: - return json.load(f) - except Exception as exc: - logger.warning("Failed to load topic hierarchy cache: %s", exc) - return {} - - -def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict: - """ - Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task). - - Arguments: - page_size (int): Number of topics to fetch per request (default: 200) - save_json (bool): Whether to save the cache as a JSON file (default: True) - - Returns: - taxonomy_cache (dict): The topic hierarchy dictionary. - """ - output_filename: str = "topic_hierarchy_cache.json" - headers = { - "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", - "Content-Type": "application/json", - } - - taxonomy_cache = {} - offset = 0 - - with httpx.Client(timeout=30.0) as client: - while True: - payload = {"query": {"match_all": {}}, "from": offset, "size": page_size} - response = client.post( - config.settings.elasticsearch_url + "/openalex-topics/_search", - json=payload, - headers=headers, - ) - response.raise_for_status() - data = response.json() - - hits = data.get("hits", {}).get("hits", []) - if not hits: - break - - for hit in hits: - source = hit.get("_source", {}) - topic_name = source.get("display_name") or source.get("name") - if not topic_name: - continue - - taxonomy_cache[topic_name] = { - "topic_id": source.get("id") or hit.get("_id", ""), - "subfield": source.get("subfield", {}).get("display_name", ""), - "field": source.get("field", {}).get("display_name", ""), - "domain": source.get("domain", {}).get("display_name", ""), - } - - offset += len(hits) - logger.info("Processed %s topics total", len(taxonomy_cache)) - - if save_json: - data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True) - try: - output_path = "/data/" + output_filename - with open(output_path, "w", encoding="utf-8") as f: - f.write(data_json) - logger.info("Topic hierarchy cache written to %s", output_path) - except Exception as exc: - logger.warning("Failed to write topic hierarchy cache: %s", exc) - - return taxonomy_cache - - -def get_topics_from_cache(topic_names: List[str]) -> List[Topic]: - """ - Given a list of topic names, retrieves their hierarchy information from the cache and returns a list of Topic models. - Arguments: - topic_names (List[str]): A list of topic names to retrieve. - Returns: - List[Topic]: A list of Topic models. - """ - cache = _load_topic_cache() - topics = [] - for name in topic_names: - data = cache.get(name) - if not data: - continue - subfield_name = data.get("subfield", "") - field_name = data.get("field", "") - domain_name = data.get("domain", "") - topics.append( - Topic( - id=data.get("topic_id", ""), - display_name=name, - works_count=data.get("count", 1), - subfield=TopicSubfield(display_name=subfield_name) - if subfield_name - else None, - field=TopicField(display_name=field_name) if field_name else None, - domain=TopicDomain(display_name=domain_name) if domain_name else None, - ) - ) - return topics - - -def count_topic_hierarchy(topic_names: List[str]) -> dict: - """ - Given a list of topic names, counts the occurrences of each topic and their hierarchy levels (subfield, field, domain) using the cache. - Arguments: - topic_names (List[str]): A list of topic names to count. - Returns: - dict: A dictionary containing the counts of each hierarchy level. - """ - cache = _load_topic_cache() - counts = {"topics": {}, "subfields": {}, "fields": {}, "domains": {}} - - for name in topic_names: - data = cache.get(name) - if not data: - continue - - counts["topics"][name] = counts["topics"].get(name, 0) + 1 - - subfield = data.get("subfield", "") - if subfield: - counts["subfields"][subfield] = counts["subfields"].get(subfield, 0) + 1 - - field = data.get("field", "") - if field: - counts["fields"][field] = counts["fields"].get(field, 0) + 1 - - domain = data.get("domain", "") - if domain: - counts["domains"][domain] = counts["domains"].get(domain, 0) + 1 - - return counts - -def get_topic_hierarchy() -> dict: - """ - Builds and returns a hierarchical tree structure of topics: - Domains -> Fields -> Subfields -> Topics - """ - flat_cache = _load_topic_cache() - tree = {} - - for topic_name, info in flat_cache.items(): - domain = info.get("domain") or "Unbekannter Bereich" - field = info.get("field") or "Unbekanntes Feld" - subfield = info.get("subfield") or "Unbekanntes Teilfeld" - topic_id = info.get("topic_id", "") - - # Clean topic ID to just be the trailing ID or keep full URL - # For querying, display name is used in persons search, but ID is useful - - if domain not in tree: - tree[domain] = {} - if field not in tree[domain]: - tree[domain][field] = {} - if subfield not in tree[domain][field]: - tree[domain][field][subfield] = [] - - tree[domain][field][subfield].append({ - "id": topic_id, - "name": topic_name - }) - - formatted_domains = [] - for d_name, d_fields in tree.items(): - formatted_fields = [] - for f_name, f_subfields in d_fields.items(): - formatted_subfields = [] - for sf_name, sf_topics in f_subfields.items(): - sf_topics.sort(key=lambda x: x["name"]) - formatted_subfields.append({ - "name": sf_name, - "topics": sf_topics - }) - formatted_subfields.sort(key=lambda x: x["name"]) - formatted_fields.append({ - "name": f_name, - "subfields": formatted_subfields - }) - formatted_fields.sort(key=lambda x: x["name"]) - formatted_domains.append({ - "name": d_name, - "fields": formatted_fields - }) - formatted_domains.sort(key=lambda x: x["name"]) - - return {"domains": formatted_domains} diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 24c763de..40f6b2e9 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -6,6 +6,7 @@ for fastapi that loads the service and the webapp. """ +from contextlib import asynccontextmanager import logging from fastapi import FastAPI, Request @@ -18,22 +19,21 @@ from inse.exceptions import NotFoundException from inse.funders.service import router as funders_service_router from inse.projects.router import router as projects_router from inse.university_ranking.router import router as university_ranking_router + # caching from inse.middleware.etag_cache import ETagCacheMiddleware from inse.persons.service import router as persons_service_router -from inse.projects.router import router as projects_router from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router -from inse.persons.service import router as persons_service_router -from inse.funders.service import router as funders_service_router from inse.news.service import router as news_service_router -from inse.projects.router import router as projects_router from inse.patents.service import router as patents_service_router +from inse.auth.router import router as auth_router + from inse.institutions.router import router as institutions_router +from inse.database import create_db_and_tables from . import config from .account.service import router as account_router -from .service import router as service_router logger = logging.getLogger(__name__) @@ -41,12 +41,22 @@ logger = logging.getLogger(__name__) settings = config.get_settings() + +@asynccontextmanager +async def lifespan(app: FastAPI): + logger.info("Starting up the application...") + create_db_and_tables() + yield + logger.info("Shutting down the application...") + + app = FastAPI( redoc_url=None, title="Innovation Search Engine API", description="API for the Innovation Search Engine (INSE) application.", version="0.1.0", servers=settings.servers, + lifespan=lifespan, ) app.include_router(collaboration_network_router) app.include_router(institutions_router) @@ -56,12 +66,13 @@ app.include_router(persons_service_router) app.include_router(funders_service_router) app.include_router(news_service_router) app.include_router(company_connections_router) -app.include_router(service_router) app.include_router(account_router) app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) +app.include_router(auth_router) + app.add_middleware( ETagCacheMiddleware, ttl=300, # 5 minutes expiration time diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 98aaf28c..961fe9f9 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -8,41 +8,20 @@ our api using pydantic. from enum import StrEnum from pydantic import BaseModel -from pydantic import ConfigDict from pydantic import Field from typing import List from typing import TypeVar from typing import Generic -from typing import Optional T = TypeVar("T", bound=BaseModel) -class Entity(BaseModel): - id: int = Field(description="The id of the entity.") - - -class Item(Entity): - model_config = ConfigDict(from_attributes=True) - name: str = Field(description="The name of the item.") - description: str = Field(description="The description of the item.") - - -class ItemCreate(BaseModel): - name: str = Field(description="The name of the item.") - description: str = Field(description="The description of the item.") - - class Page(BaseModel, Generic[T]): elements: List[T] = Field(default=[], description="The elements of the page.") - offset: int = Field(default=0, description="The page offset in elements.") - total: int = Field(default=0, description="The total number of elements.") + offset: int = Field(default=0, description="The page number. (0-based)") size: int = Field(default=20, description="The page size in elements.") - - -class ItemPage(Page[Item]): - pass + total: int = Field(default=0, description="The total number of elements.") class ESCluster(StrEnum): @@ -61,4 +40,4 @@ class ESIndex(StrEnum): CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" PROJECTS_BUND_V1 = "projects_bund_v1" - PROJECTS_DFG_ALL = "projects_dfg_all" \ No newline at end of file + PROJECTS_DFG_ALL = "projects_dfg_all" diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 8c5238f9..2ab1e22b 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -8,8 +8,7 @@ import json import logging import time from datetime import datetime -from typing import Optional, Callable, Any, List -from elasticsearch import ApiError, NotFoundError +from typing import Optional, List import hashlib import httpx from fastapi import HTTPException @@ -20,14 +19,12 @@ from .. import util from ..integrations import llm from inse.models.openalex.author import Author from inse.models.openalex.authors_list_response import AuthorsListResponse -from inse import util from inse.integrations import elasticsearch from inse.models.openalex.meta import Meta from inse.persons.query_builder import build_authors_search_rescored from inse.persons.model import ( CustomAuthor, CustomAuthorsListResponse, - PersonSearchRequest, CareerMetrics, ) @@ -35,17 +32,14 @@ logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen + def find_ude_author_by_name(display_name: str) -> Optional[dict]: query = { "_source": ["display_name"], "query": { "bool": { "must": [ - { - "match_phrase": { - "display_name": display_name - } - }, + {"match_phrase": {"display_name": display_name}}, { "nested": { "path": "affiliations", @@ -454,7 +448,7 @@ def get_person_by_id( elapsed_time = time.time() - start_time logger.info( - f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds" + f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds" ) custom_author = CustomAuthor( diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 509f5d8b..07530826 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -1,4 +1,3 @@ -from functools import lru_cache import logging from typing import Annotated, Optional, Set diff --git a/service/src/main/inse/schema.py b/service/src/main/inse/schema.py deleted file mode 100644 index d03a1b33..00000000 --- a/service/src/main/inse/schema.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module defines the schema for the database - used by the service using sql alchemy. -""" -from sqlalchemy import String -from sqlalchemy.orm import DeclarativeBase -from sqlalchemy.orm import Mapped -from sqlalchemy.orm import mapped_column - - -class Base(DeclarativeBase): - ''' Base class for all data models. ''' - pass - -class Item(Base): - ''' Data model to represent an item. ''' - __tablename__ = "item" - id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) - name: Mapped[str] = mapped_column(String(200)) - description: Mapped[str] = mapped_column(String(2000)) - def __repr__(self) -> str: - return f"Item(id={self.id!r}, name={self.name!r})" diff --git a/service/src/main/inse/security.py b/service/src/main/inse/security.py index d8f9d304..d6495cb9 100644 --- a/service/src/main/inse/security.py +++ b/service/src/main/inse/security.py @@ -1,13 +1,13 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ - This module defines the security-related code. +This module defines the security-related code. """ + from typing import Optional from typing import List from typing import Callable from typing import Literal -from typing import Union from starlette.status import HTTP_403_FORBIDDEN from fastapi import Depends from fastapi.security import HTTPBearer @@ -15,63 +15,97 @@ from fastapi.security import HTTPAuthorizationCredentials from fastapi import HTTPException from pydantic import BaseModel from pydantic import Field -from sqlalchemy.orm import Session import jwt import logging from . import config from . import database + class Account(BaseModel): id: int = Field(description="The id of the account.") login: Optional[str] = Field(description="The optional login of the account.") organization: int = Field(description="The organization id of the account.") + class Principal(BaseModel): account: Account = Field(description="The account of the principal.") - delegate: Optional[Account] = Field(default=None, description="The optional delegate of the principal.") + delegate: Optional[Account] = Field( + default=None, description="The optional delegate of the principal." + ) roles: List[str] = Field(description="The roles of the principal.") + logger = logging.getLogger(__name__) -bearer = HTTPBearer(bearerFormat="JWT", scheme_name="bearer", description="JSON Web Token provided via bearer authorization.", auto_error=False) +bearer = HTTPBearer( + bearerFormat="JWT", + scheme_name="bearer", + description="JSON Web Token provided via bearer authorization.", + auto_error=False, +) -def principal(credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), db: Session = Depends(database.get)) -> Optional[Principal]: + +def principal( + db: database.SessionDep, + credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), +) -> Optional[Principal]: if config.settings.auth_disabled: account = Account(id=0, login="AUTH_DISABLED", organization=0) - return Principal(account=account, delegate=None, roles=[ 'SUPER_ADMIN' ]) + return Principal(account=account, delegate=None, roles=["SUPER_ADMIN"]) if credentials is None or credentials.credentials is None: return None - return _extract_principal(credentials.credentials, config.settings.auth_secret, 'HS256') + return _extract_principal( + credentials.credentials, config.settings.auth_secret, "HS256" + ) -def _extract_principal(token: str, secret_key, algorithm: Literal['RS256', 'HS256'], token_types: List[Literal['ID', 'ACCESS', 'REFRESH']] = [ 'ACCESS' ]) -> Optional[Principal]: + +def _extract_principal( + token: str, + secret_key, + algorithm: Literal["RS256", "HS256"], + token_types: List[Literal["ID", "ACCESS", "REFRESH"]] = ["ACCESS"], +) -> Optional[Principal]: try: - content = jwt.decode(token, secret_key, verify=True, issuer="my-app", algorithms=[ algorithm ], options={"require": [ "iss", "iat", "nbf", "exp", "inse"]}) + content = jwt.decode( + token, + secret_key, + verify=True, + issuer="my-app", + algorithms=[algorithm], + options={"require": ["iss", "iat", "nbf", "exp", "inse"]}, + ) except jwt.exceptions.ExpiredSignatureError as e: - logger.info(f'Received expired token, ignoring content ({e}).') + logger.info(f"Received expired token, ignoring content ({e}).") return None except Exception as e: - logger.info(f'Received invalid token content, ignoring content ({e}).') + logger.info(f"Received invalid token content, ignoring content ({e}).") return None scope = content.get("inse") if scope is None: return None - token_type = scope.get('t') + token_type = scope.get("t") if token_type not in token_types: - logger.info(f'Received invalid token type, ignoring content (Type was {token_type})') + logger.info( + f"Received invalid token type, ignoring content (Type was {token_type})" + ) return None - a = scope.get('a', {}) - account = Account(id=a.get('i', 0), login=a.get('l'), organization=a.get('o', 0)) + a = scope.get("a", {}) + account = Account(id=a.get("i", 0), login=a.get("l"), organization=a.get("o", 0)) delegate = None - d = scope.get('d') + d = scope.get("d") if d is not None: - delegate = Account(id=d.get('i', 0), login=d.get('l'), organization=d.get('o', 0)) - return Principal(account=account, delegate=delegate, roles=scope.get('r', [])) + delegate = Account( + id=d.get("i", 0), login=d.get("l"), organization=d.get("o", 0) + ) + return Principal(account=account, delegate=delegate, roles=scope.get("r", [])) -def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Principal]: + +def roles_allowed(roles: List[str] | str) -> Callable[[Optional[Principal]], Principal]: if isinstance(roles, str): roles = [roles] if len(roles) < 1: raise ValueError("Must specify at least one role in roles_allowed.") + def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal: if principal is None: logger.info("Rejecting call due to missing principal.") @@ -81,4 +115,5 @@ def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Princ return principal logger.info("Rejecting call due to missing roles.") raise HTTPException(status_code=HTTP_403_FORBIDDEN) + return verify_roles diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py deleted file mode 100644 index 6e3dadc5..00000000 --- a/service/src/main/inse/service.py +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -This module contains the rest api of the -service. -""" - -import logging -from typing import Annotated, List, Optional -from fastapi import FastAPI -from fastapi import Depends -from fastapi import Path -from fastapi import Query -from fastapi import Body -from fastapi import Response -from fastapi.responses import RedirectResponse -from starlette.status import HTTP_404_NOT_FOUND -from starlette.status import HTTP_200_OK -from sqlalchemy.orm import Session -from inse.config import get_settings -from fastapi import APIRouter - - -from . import model -from . import logic -from . import schema -from . import database -from . import security -from . import util - - - -logger = logging.getLogger(__name__) - -### startup - -settings = get_settings() - -router = APIRouter( - prefix="/api/inse-service", - tags=["INSE Service"], - responses={404: {"description": "Not found"}}, -) - -# @app.get("/", include_in_schema=False) -# async def show_api(): -# return RedirectResponse("api") - - -### items - - -@router.get( - "/items", - operation_id="getItems", - response_model=model.ItemPage, - summary="Returns a page of items.", - tags=["Items"], -) -def get_items( - page_offset: Annotated[ - int, Query(alias="pageOffset", description="The page offset.", ge=0) - ] = 0, - page_size: Annotated[ - int, Query(alias="pageSize", description="The page size.", ge=0, le=1000) - ] = 100, - db: Session = Depends(database.get), - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), -): - return logic.get_page(db, schema.Item, model.Item, page_offset, page_size) - - -@router.get( - "/items/{id}", - operation_id="getItem", - response_model=model.Item, - summary="Returns the item with the id.", - responses={HTTP_404_NOT_FOUND: {"model": None}}, - tags=["Items"], -) -def get_item( - id: Annotated[int, Path(description="The item id.", ge=0)], - db: Session = Depends(database.get), - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), -): - return util.raise_not_found_if_none(logic.get_element(db, schema.Item, id)) - - -@router.post( - "/items", - operation_id="addItem", - response_model=model.Item, - summary="Adds a new item.", - tags=["Items"], -) -def add_item( - item: Annotated[model.ItemCreate, Body(description="The item to add.")], - db: Session = Depends(database.get), - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), -): - i = schema.Item() - i.name = item.name - i.description = item.description - try: - return logic.insert_element(db, i) - finally: - db.commit() - - -@router.put( - "/items/{id}", - operation_id="updateItem", - response_model=model.Item, - summary="Updates the item with the id.", - responses={HTTP_404_NOT_FOUND: {"model": None}}, - tags=["Items"], -) -def update_item( - id: Annotated[int, Path(description="The item id.", ge=0)], - item: Annotated[model.ItemCreate, Body(description="The item data to update.")], - db: Session = Depends(database.get), - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), -): - i = util.raise_not_found_if_none(logic.get_element(db, schema.Item, id)) - i.name = item.name - i.description = item.description - db.flush() - db.refresh(i) - try: - return i - finally: - db.commit() - - -@router.delete( - "/items/{id}", - operation_id="deleteItem", - summary="Deletes the item with the id.", - response_model=None, - responses={HTTP_404_NOT_FOUND: {"model": None}}, - tags=["Items"], -) -def delete_item( - id: Annotated[int, Path(description="The item id.", ge=0)], - db: Session = Depends(database.get), - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), -): - util.raise_not_found_if_none(logic.get_element(db, schema.Item, id)) - try: - logic.delete_element(db, schema.Item, id) - return Response(status_code=HTTP_200_OK) - finally: - db.commit() - - -### topics -# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing) -@router.get( - "/topics/cache", - operation_id="buildTopicCache", - response_model=dict, - summary="Builds the topic hierarchy cache.", - tags=["Topics"], -) -def build_topic_cache( - page_size: Annotated[ - int, Query(description="Page size for each search page.", ge=1, le=1000) - ] = 200, - save_json: Annotated[ - bool, Query(description="Persist cache JSON to data folder.") - ] = True, -): - return logic.build_topic_cache(page_size=page_size, save_json=save_json) - - -@router.get( - "/topics/count", - operation_id="countTopicHierarchy", - response_model=dict, - summary="Counts topic hierarchy occurrences from cache.", - tags=["Topics"], -) -def count_topic_hierarchy( - topic_names: Annotated[ - List[str], - Query( - alias="topic", - description="Topic names (repeat parameter).", - example=[ - "Big Data and Business Intelligence", - "Big Data and Business Intelligence", - "Topic Modeling", - "Entrepreneurship Studies and Influences", - "Complex Network Analysis Techniques", - "Semantic Web and Ontologies", - ], - ), - ], -): - return logic.count_topic_hierarchy(topic_names) - -@router.get( - "/topics/hierarchy", - operation_id="getTopicHierarchy", - response_model=dict, - summary="Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).", - tags=["Topics"], -) -def get_topic_hierarchy(): - return logic.get_topic_hierarchy() diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index bd0b79c0..bcfcd086 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -1,7 +1,7 @@ -from enum import Enum +from enum import StrEnum -class Tags(Enum): +class Tags(StrEnum): PERSON = "Person" PERSON_NETWORK = "Person Network" INSTITUTIONS = "Institutions" @@ -9,3 +9,5 @@ class Tags(Enum): WORKS = "Works" NEWS = "News" PROJECTS = "Projects" + AUTH = "Auth" + ACCOUNT = "Account" diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index e0d84c57..6846dbc0 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -7,13 +7,11 @@ REST API for publication works. from typing import Annotated from fastapi import APIRouter -from fastapi import Depends from fastapi import Path from fastapi import Query from inse.tags import Tags -from .. import security from . import logic from inse.models.openalex.work_page import WorkPage from inse.models.openalex.work import Work @@ -56,9 +54,6 @@ async def get_author_works( list[str] | None, Query(description="Filter by OpenAlex topic id. Can be repeated."), ] = None, - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), ): return await logic.get_author_works( author_id, @@ -78,7 +73,6 @@ async def get_author_works( summary="Returns all works for an author.") async def get_all_author_works( author_id: Annotated[str, Path(description="The author id, for example A5023888391.")], - principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), ): return await logic.get_all_author_works(author_id) @@ -89,7 +83,6 @@ async def get_all_author_works( summary="Returns work counts per primary topic for an author.") async def get_primary_topic_counts( author_id: Annotated[str, Path(description="The author id, for example A5023888391.")], - principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), ): return await logic.get_primary_topic_counts(author_id) @@ -112,7 +105,6 @@ async def get_topics_by_time_by_author( bool, Query(description="If true, all publications are used for the timeline."), ] = False, - principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), ): return await logic.get_topics_by_time_by_author( author_id, @@ -132,8 +124,5 @@ async def get_work( work_id: Annotated[ str, Path(description="The OpenAlex work id, for example W2741809807.") ], - principal: security.Principal = Depends( - security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) - ), ): return await logic.get_work(work_id) diff --git a/service/uv.lock b/service/uv.lock index d4016c83..03c67be5 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -178,36 +178,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" }, ] -[[package]] -name = "elastic-transport" -version = "9.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "sniffio" }, - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" }, -] - -[[package]] -name = "elasticsearch" -version = "9.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "elastic-transport" }, - { name = "python-dateutil" }, - { name = "sniffio" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" }, -] - [[package]] name = "fastapi" version = "0.115.14" @@ -799,18 +769,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" }, ] -[[package]] -name = "python-dateutil" -version = "2.9.0.post0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, -] - [[package]] name = "python-dotenv" version = "1.2.2" @@ -1127,7 +1085,6 @@ source = { virtual = "." } dependencies = [ { name = "cryptography" }, { name = "dotenv" }, - { name = "elasticsearch" }, { name = "fastapi" }, { name = "httpx" }, { name = "openai" }, @@ -1138,7 +1095,7 @@ dependencies = [ { name = "python-multipart" }, { name = "pyyaml" }, { name = "sentence-transformers" }, - { name = "sqlalchemy" }, + { name = "sqlmodel" }, { name = "torch", version = "2.12.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform == 'darwin'" }, { name = "torch", version = "2.12.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'darwin'" }, { name = "uvicorn" }, @@ -1148,7 +1105,6 @@ dependencies = [ requires-dist = [ { name = "cryptography", specifier = "~=42.0.0" }, { name = "dotenv", specifier = ">=0.9.9" }, - { name = "elasticsearch", specifier = "~=9.4.0" }, { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, { name = "openai", specifier = "~=2.41.0" }, @@ -1159,7 +1115,7 @@ requires-dist = [ { name = "python-multipart", specifier = "~=0.0.19" }, { name = "pyyaml", specifier = "~=6.0.1" }, { name = "sentence-transformers", specifier = "~=5.5.1" }, - { name = "sqlalchemy", specifier = "~=2.0.0" }, + { name = "sqlmodel", specifier = "~=0.0.33" }, { name = "torch", index = "https://download.pytorch.org/whl/cpu" }, { name = "uvicorn", specifier = "~=0.29.0" }, ] @@ -1182,15 +1138,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] -[[package]] -name = "six" -version = "1.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, -] - [[package]] name = "sniffio" version = "1.3.1" @@ -1241,6 +1188,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d0/10/f7220e9b784d295d241c86ed99aeb537f92afcd469a64861f2717e9bb077/sqlalchemy-2.0.50-py3-none-any.whl", hash = "sha256:92064363517a3ff8212b5a93b8c62876579d8dfd1ca5b561335f30152d884fa9", size = 1943861, upload-time = "2026-05-24T19:59:01.119Z" }, ] +[[package]] +name = "sqlmodel" +version = "0.0.33" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "sqlalchemy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c4/62/22c287122598e61d07d005eec0b4eb97e6bde9a1b051bcd66c2bca846ea8/sqlmodel-0.0.33.tar.gz", hash = "sha256:b473544ed5fc2097894d89033049e569e1f138363dd3ec2ed4b6932cc9f29f5f", size = 95578, upload-time = "2026-02-11T15:23:39.504Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/39/13891bae4658133b489a4d8b6a2f193d56110e392289560f312748e796dc/sqlmodel-0.0.33-py3-none-any.whl", hash = "sha256:9045bb4d97d2ba099c5a068ee9525af2d106972dda1ff8488e187ce50556bf73", size = 27444, upload-time = "2026-02-11T15:23:38.678Z" }, +] + [[package]] name = "starlette" version = "0.46.2" @@ -1421,15 +1381,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] -[[package]] -name = "urllib3" -version = "2.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, -] - [[package]] name = "uvicorn" version = "0.29.0" From 40fcdba595f5bce21d043d29b72aef77f962ebab Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Wed, 24 Jun 2026 13:14:26 +0200 Subject: [PATCH 02/31] implement UI Frontend --- .../app-login/app-login.component.html | 216 ++++++++++++------ .../app-login/app-login.component.scss | 215 +++++++++++++---- .../modules/app-login/app-login.component.ts | 123 +++++++++- 3 files changed, 436 insertions(+), 118 deletions(-) diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index e7cb87a6..35a4fc3e 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -1,68 +1,154 @@ -
-
-

Anmeldung

-

- Um auf den Dienst zuzugreifen, musst Du Deine Anmeldedaten eingeben. -

- - - Login - - @if (loginForm.controls.login.hasError('required')) { - Fehler: Login erforderlich. - } @else if (loginForm.controls.login.hasError('minlength')) { - Fehler: Login ist unvollständig. - } - - - - Passwort - - @if (showPassword) { - visibility - } @else { - visibility_off - } - @if (loginForm.controls.password.hasError('required')) { - Fehler: Passwort erforderlich. - } @else if (loginForm.controls.password.hasError('minlength')) { - Fehler: Passwort ist unvollständig. - } - - - -
- +
+ diff --git a/webapp/src/app/modules/app-login/app-login.component.scss b/webapp/src/app/modules/app-login/app-login.component.scss index 034b92ac..e5cdaf91 100644 --- a/webapp/src/app/modules/app-login/app-login.component.scss +++ b/webapp/src/app/modules/app-login/app-login.component.scss @@ -1,54 +1,187 @@ -.container { - display: flex; - flex-direction: column; +.login-page { + display: grid; + min-height: calc(100svh - 41px); + place-items: center; + padding: 48px 20px; + background: + radial-gradient(circle at top left, rgba(61, 124, 255, 0.12), transparent 34%), + linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%); +} + +.login-panel { + width: min(100%, 480px); + padding: 34px; + background: var(--sg-surface); + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + box-shadow: var(--sg-shadow-md); +} + +.brand-block { + display: grid; + gap: 10px; + margin-bottom: 28px; +} + +.eyebrow { + color: var(--sg-blue-highlight); + font-size: 12px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +h1 { + margin: 0; + font-size: 32px; + line-height: 1.15; +} + +p { + margin: 0; + color: var(--sg-text-muted); +} + +.stepper { + display: grid; + grid-template-columns: auto 1fr auto; align-items: center; - justify-content: center; + gap: 12px; + margin-bottom: 28px; +} + +.step { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--sg-text-muted); + font-size: 13px; +} + +.step span { + display: grid; + width: 28px; + height: 28px; + place-items: center; + border: 1px solid var(--sg-border-strong); + border-radius: 50%; + background: var(--sg-surface); + font-weight: 700; +} + +.step--active { + color: var(--sg-text); +} + +.step--active span { + background: var(--sg-primary); + border-color: var(--sg-primary); + color: #ffffff; +} + +.step-line { + height: 1px; + background: var(--sg-border); +} + +.login-form { + display: grid; + gap: 18px; +} + +.field, +.submit-button { width: 100%; - height: 100%; - background: linear-gradient(160deg, #f4f6fb 0%, #e8ecf7 100%); } -.form { - display: flex; - flex-direction: column; - align-items: center; - background: white; - border: none; - border-radius: 12px; - box-shadow: - 0 2px 12px rgba(26, 58, 110, 0.1), - 0 1px 4px rgba(0, 0, 0, 0.06); - gap: 20px; - padding: 36px 32px 28px; -} - -.form h3 { - margin: 0 0 4px; - font-weight: 600; - color: #1a3a6e; -} - -.button { +.submit-button { min-height: 48px; - min-width: 140px; - border-radius: 8px; - font-weight: 500; - letter-spacing: 0.02em; + border-radius: var(--sg-radius-sm); + font-weight: 700; } -.field { - width: 400px; +.form-actions { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 40px; } -.progress { - padding-top: 5px; - width: 300px; - height: 2em; - text-align: center; - font-size: small; - color: #585f71; +.form-actions a, +.form-actions button { + color: var(--sg-text-muted); + font-size: 13px; } -.error { +.code-intro { + display: grid; + grid-template-columns: auto 1fr; + gap: 14px; + padding: 14px; + background: var(--sg-surface-soft); + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); +} + +.code-intro mat-icon { + color: var(--sg-blue-highlight); +} + +.code-intro div { + display: grid; + gap: 3px; +} + +.code-intro span { + color: var(--sg-text-muted); + font-size: 13px; + overflow-wrap: anywhere; +} + +.expiry { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--sg-success); + font-size: 13px; +} + +.expiry mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.expiry--expired { color: #ba1a1a; } + +@media (max-width: 560px) { + .login-page { + padding: 28px 14px; + place-items: start center; + } + + .login-panel { + padding: 24px 18px; + } + + h1 { + font-size: 28px; + } + + .stepper { + grid-template-columns: 1fr; + align-items: start; + } + + .step-line { + display: none; + } + + .form-actions { + align-items: stretch; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 24fd129f..3352060d 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -15,6 +15,8 @@ import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; +type LoginStep = 'credentials' | 'otk'; + @Component({ selector: 'app-app-login', imports: [ @@ -32,20 +34,29 @@ import { Router, RouterLink } from '@angular/router'; standalone: true, }) export class AppLoginComponent implements OnInit, OnDestroy { - loginForm = new FormGroup({ - login: new FormControl('', [ - Validators.required, - Validators.minLength(4), - ]), + credentialsForm = new FormGroup({ + email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ Validators.required, - Validators.minLength(4), + Validators.minLength(8), ]), }); + otkForm = new FormGroup({ + code: new FormControl('', [ + Validators.required, + Validators.pattern(/^[0-9A-Za-z]{6,10}$/), + ]), + }); + + currentStep: LoginStep = 'credentials'; showPassword = false; + isSubmitting = false; + codeExpiresIn = 0; + readonly codeLifetimeSeconds = 300; subscription?: Subscription; + private countdownInterval?: ReturnType; constructor( protected credentialService: CredentialService, @@ -57,9 +68,11 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.subscription = this.credentialService.validating.subscribe( (validating) => { if (validating) { - this.loginForm.disable(); + this.credentialsForm.disable(); + this.otkForm.disable(); } else { - this.loginForm.enable(); + this.credentialsForm.enable(); + this.otkForm.enable(); this.checkEnter(); } }, @@ -80,13 +93,99 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.subscription.unsubscribe(); this.subscription = undefined; } + this.stopCountdown(); + } + + requestOtk() { + if (this.credentialsForm.invalid || this.isSubmitting) { + this.credentialsForm.markAllAsTouched(); + return; + } + + this.isSubmitting = true; + this.credentialsForm.disable(); + + setTimeout(() => { + this.isSubmitting = false; + this.credentialsForm.enable(); + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open('OTK-Code wurde an die E-Mail-Adresse gesendet.', 'OK', { + duration: 4000, + }); + }, 450); + } + + resendCode() { + if (this.isSubmitting) { + return; + } + + this.requestOtk(); } login() { - let user = this.loginForm.controls.login.value; - let pass = this.loginForm.controls.password.value; - if (user && pass) { - this.credentialService.loginAccount(user, pass); + if (this.otkForm.invalid || this.isSubmitting) { + this.otkForm.markAllAsTouched(); + return; + } + + if (this.codeExpiresIn <= 0) { + this.snackBar.open( + 'Der Code ist abgelaufen. Bitte fordere einen neuen Code an.', + 'OK', + { duration: 5000 }, + ); + return; + } + + this.isSubmitting = true; + this.otkForm.disable(); + + setTimeout(() => { + this.isSubmitting = false; + this.otkForm.enable(); + this.snackBar.open( + 'Backend-Anbindung folgt: login(emailCode) wird hier ausgeführt.', + 'OK', + { duration: 5000 }, + ); + }, 450); + } + + editCredentials() { + this.currentStep = 'credentials'; + this.stopCountdown(); + this.otkForm.reset(); + } + + formatCountdown(): string { + const minutes = Math.floor(this.codeExpiresIn / 60); + const seconds = this.codeExpiresIn % 60; + return `${minutes}:${seconds.toString().padStart(2, '0')}`; + } + + private startCountdown(): void { + this.stopCountdown(); + this.codeExpiresIn = this.codeLifetimeSeconds; + this.countdownInterval = setInterval(() => { + this.codeExpiresIn = Math.max(this.codeExpiresIn - 1, 0); + + if (this.codeExpiresIn === 0) { + this.stopCountdown(false); + } + }, 1000); + } + + private stopCountdown(reset = true): void { + if (this.countdownInterval) { + clearInterval(this.countdownInterval); + this.countdownInterval = undefined; + } + + if (reset) { + this.codeExpiresIn = 0; } } } From bea26c70ec822cb5d0fbfbdf33dcf2486f70fbba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Wed, 24 Jun 2026 22:31:44 +0200 Subject: [PATCH 03/31] Added prototype for fingerprinted token generation --- service/src/main/inse/.env | 3 + service/src/main/inse/auth/model.py | 4 +- service/src/main/inse/auth/service.py | 429 +++++++++++++++++++++++++- service/src/main/inse/config.py | 3 + 4 files changed, 432 insertions(+), 7 deletions(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index e886c6a1..492450e9 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -14,3 +14,6 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2 + +TOKEN_ISSUER_ID=inse +TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7 \ No newline at end of file diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 3ffe0cb2..ed954b00 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -139,13 +139,13 @@ class AccessToken(Token): 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.", ) - role: UserRole = Field( + effective_role: UserRole = Field( default=UserRole.USER, index=True, nullable=False, description="The specific role this access token grants within its organization.", ) - organization_id: uuid.UUID = Field( + effective_organization_id: uuid.UUID = Field( nullable=False, description="The unique identifier of the organization associated with this access token.", ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index e54f8550..64e46d94 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,18 +1,437 @@ +import datetime +import hashlib +import secrets +from typing import Annotated, Any, Literal, Optional, Dict import uuid -from inse.auth.model import IdToken, RefreshToken +from fastapi import Depends, HTTPException, Request, Response, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +import jwt + +from inse.auth.model import AccessToken, RefreshToken, UserRole +from inse.config import get_settings + + +ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days +REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes +ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes + +REAL_ACCOUNT_ID_KEY = "real_account_id" +EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id" +EFFECTIVE_ROLE_KEY = "effective_role" +EPOCH_KEY = "epoch" +ORGANIZATION_ID_KEY = "organization_id" +USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" + +settings = get_settings() + +security_scheme = HTTPBearer() def request_otk(email: str, password: str): pass -def login(emailCode: str): - pass +def login(response: Response, emailCode: str) -> str: + # TODO: validate emailCode and retrieve the associated account IDF + real_account_id = uuid.uuid4() + # TODO: Replace with actual account ID retrieval logic + + epoch = _get_account_epoch(real_account_id) + return _build_id_token(response, real_account_id, epoch) -def get_access_token(account_id: uuid.UUID, id_token: IdToken): - pass +def _get_current_user_token_payload( + request: Request, + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], +) -> AccessToken: + """Extracts and verifies the current user's token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. + + Args: + request (Request): The FastAPI request object containing the cookies. + credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials extracted from the request. + + Returns: + Dict[str, Any]: The verified token payload. + """ + + token = credentials.credentials + + access_token_payload = _verify_fp_token(request, "__Secure-Fgp-Act", token) + # 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[ORGANIZATION_ID_KEY]), + ) + + +CurrentUserTokenPayloadDep = Depends(_get_current_user_token_payload) + + +def _get_account_epoch(account_id: uuid.UUID) -> int: + """Retrieves the current epoch for the given account ID. The epoch is used to manage token versioning and invalidation. + + Args: + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch. + + Returns: + int: The current epoch for the given account ID. + """ + + return 0 # TODO: Replace with actual logic to retrieve the epoch for the account + + +def _get_account_role(account_id: uuid.UUID) -> UserRole: + """Retrieves the role for the given account ID. + + Args: + 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. + """ + return ( + UserRole.USER + ) # TODO: Replace with actual logic to retrieve the role for the account + + +def _get_account_organization(account_id: uuid.UUID) -> uuid.UUID: + """Retrieves the organization ID for the given account ID. + + Args: + 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. + """ + return ( + uuid.uuid4() + ) # TODO: Replace with actual logic to retrieve the organization ID for the account + + +def _is_valid_impersonation( + real_account_id: uuid.UUID, effective_account_id: uuid.UUID +) -> bool: + """Checks if the real account is allowed to impersonate the effective account. + + Args: + 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. + """ + return True # TODO: Replace with actual logic to check if impersonation is allowed + + +def get_access_token( + request: Request, + response: Response, + id_token: str, + real_account_id: uuid.UUID, + effective_account_id: Optional[uuid.UUID] = None, +) -> Dict[str, Any]: + """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: + Dict[str, Any]: A dictionary containing the generated access and refresh tokens. + """ + + id_token_payload = _verify_fp_token( + request=request, + cookie_key="__Secure-Fgp-ID", + token=id_token, + ) + # If reaches here, the id_token is valid and the fingerprint matches + + if str(real_account_id) != id_token_payload[REAL_ACCOUNT_ID_KEY]: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Real account ID does not match ID token", + ) + + if effective_account_id: + if not _is_valid_impersonation(real_account_id, effective_account_id): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Impersonation not allowed", + ) + else: + # No impersonation, set effective_account_id to real_account_id + effective_account_id = real_account_id + + role = _get_account_role(effective_account_id) + epoch = _get_account_epoch(real_account_id) + organization_id = _get_account_organization(effective_account_id) + + user_fingerprint_hash = _set_act_fp_cookie(response=response) + + access_token_payload = { + REAL_ACCOUNT_ID_KEY: str(real_account_id), + EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id), + EPOCH_KEY: epoch, + EFFECTIVE_ROLE_KEY: role.value, + ORGANIZATION_ID_KEY: str(organization_id), + USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, + } + + return _build_action_tokens( + payload=access_token_payload, + ) + + +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, "__Secure-Fgp-ID", 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, "__Secure-Fgp-Act" + ) # 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(request: Request, refresh_token: str) -> str: + """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 (str): The refresh token to verify. + current_user_epoch (int): The epoch value for the tokens. + + Returns: + str: The refreshed access token. + """ + refresh_payload = _verify_fp_token( + request=request, + cookie_key="__Secure-Fgp-Act", + token=refresh_token, + ) + + access_payload = { + REAL_ACCOUNT_ID_KEY: refresh_payload[REAL_ACCOUNT_ID_KEY], + EFFECTIVE_ACCOUNT_ID_KEY: refresh_payload[EFFECTIVE_ACCOUNT_ID_KEY], + EPOCH_KEY: refresh_payload[EPOCH_KEY], + EFFECTIVE_ROLE_KEY: refresh_payload[EFFECTIVE_ROLE_KEY], + ORGANIZATION_ID_KEY: refresh_payload[ORGANIZATION_ID_KEY], + USER_FINGERPRINT_HASH_KEY: refresh_payload[USER_FINGERPRINT_HASH_KEY], + } + return _build_token( + payload=access_payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES + ) + + +def _build_id_token(response: Response, real_account_id: uuid.UUID, epoch: int) -> str: + """Builds an ID token for the specified real account ID 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. + epoch (int): The epoch value for the tokens. + + Returns: + str: The built ID token. + """ + + 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, + } + return _build_token(payload=payload, expiration_min=ID_TOKEN_EXPIRATION_MINUTES) + + +def _build_action_tokens( + payload: Dict[str, Any], +) -> Dict[str, str]: + """Builds both access and refresh tokens for the specified account IDs and sets the appropriate fingerprint cookies. + + Args: + response (Response): The FastAPI response object to which the cookies 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. + epoch (int): The epoch value for the tokens. + + Returns: + Dict[str, str]: A dictionary containing the built access and refresh tokens. + """ + + return { + "access_token": _build_token( + payload=payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES + ), + "refresh_token": _build_token( + payload=payload, expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES + ), + } + + +def _build_token(payload: Dict[str, Any], expiration_min: int) -> 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_min (int): The expiration time in minutes. + + Returns: + str: The encoded JWT token. + """ + now = datetime.datetime.now(datetime.timezone.utc) + expiration_date = now + datetime.timedelta(minutes=expiration_min) + payload.update( + { + "exp": expiration_date, + "iss": settings.token_issuer_id, + "iat": now, + "nbf": now, + } + ) + 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) -> 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", + ) + + real_account_epoch = _get_account_epoch(uuid.UUID(real_account_id)) + token_epoch = payload.get(EPOCH_KEY) + if token_epoch is None or token_epoch != real_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 refresh_access_token(refresh_token: RefreshToken): diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 9aa5fb17..8e7639ff 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -64,6 +64,9 @@ class Settings(BaseSettings): environment: Literal["dev", "prod"] = "dev" + token_issuer_id: Optional[str] = None + token_hmac_key: Optional[str] = None + settings = Settings() From 699dc32b0d97983dc09ea7c88e101f53bf61b5ce Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 25 Jun 2026 05:38:17 +0200 Subject: [PATCH 04/31] Added logout epoch invalidation and change password --- service/Dockerfile | 3 +- service/src/main/inse/auth/model.py | 5 +- service/src/main/inse/auth/router.py | 33 ++++--- service/src/main/inse/auth/service.py | 131 +++++++++++++++++++++----- 4 files changed, 134 insertions(+), 38 deletions(-) diff --git a/service/Dockerfile b/service/Dockerfile index d984e6b2..cfbb7094 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -14,7 +14,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "httpx~=0.27.0" \ "python-multipart~=0.0.19"\ "openai~=2.41.0" \ - "sqlmodel~=0.0.33" + "sqlmodel~=0.0.33" \ + "argon2-cffi~=25.1.0" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index ed954b00..31b6825f 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -1,7 +1,8 @@ +import uuid from datetime import datetime from enum import StrEnum from typing import List -import uuid + from pydantic import BaseModel from sqlmodel import Field, Relationship, SQLModel @@ -22,7 +23,7 @@ class Durable(SQLModel): ) -class Organization(SQLModel, table=True): +class Organization(Durable, table=True): id: uuid.UUID | None = Field( default_factory=uuid.uuid4, primary_key=True, diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 5f9eaf6e..e8ec22ec 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -8,8 +8,8 @@ from sqlmodel import Session from inse.tags import Tags import inse.auth.service as auth_service -from inse.auth.model import IdToken, RefreshToken -from inse.database import SessionDep +from inse.auth.model import IdToken, RefreshToken, AccessToken +from inse.database import SessionDep, get_session logger = logging.getLogger(__name__) @@ -93,23 +93,34 @@ async def refresh_access_token( responses={status.HTTP_200_OK: {"description": "Logout successful."}}, ) async def logout( - session: SessionDep, + session: Annotated[Session, Depends(get_session)], + access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep, ): - auth_service.logout() + return auth_service.logout(session, access_token) @router.post( "/change-password", summary="Change Password", - description="Change the user's password and optionally invalidate existing tokens.", + 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: SessionDep, - new_password: Annotated[str, Body(description="New password", min_length=8)], - invalidate_tokens: Annotated[ - bool, Body(description="Whether to invalidate existing tokens") - ] = True, + 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: AccessToken = auth_service.CurrentUserTokenPayloadDep, ): - auth_service.change_password(new_password, invalidate_tokens) + return auth_service.change_password( + session, + access_token, + current_password, + new_password, + ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 64e46d94..6cbaf648 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,16 +1,18 @@ import datetime import hashlib import secrets -from typing import Annotated, Any, Literal, Optional, Dict 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 -import jwt - -from inse.auth.model import AccessToken, RefreshToken, UserRole +from inse.auth.model import AccessToken, Account, RefreshToken, UserRole from inse.config import get_settings - +from inse.database import get_session +from sqlmodel import Session ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes @@ -27,6 +29,19 @@ settings = get_settings() security_scheme = HTTPBearer() +_password_hasher = PasswordHasher() + + +def _hash_password(password: str) -> str: + return _password_hasher.hash(password) + + +def _verify_password(password: str, password_hash: str) -> bool: + try: + return _password_hasher.verify(password_hash, password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + return False + def request_otk(email: str, password: str): pass @@ -42,6 +57,7 @@ def login(response: Response, emailCode: str) -> str: def _get_current_user_token_payload( + session: Annotated[Session, Depends(get_session)], request: Request, credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], ) -> AccessToken: @@ -57,7 +73,12 @@ def _get_current_user_token_payload( token = credentials.credentials - access_token_payload = _verify_fp_token(request, "__Secure-Fgp-Act", token) + access_token_payload = _verify_fp_token( + request=request, + cookie_key="__Secure-Fgp-Act", + token=token, + session=session, + ) # If reaches here, the access token is valid and the fingerprint matches return AccessToken( @@ -75,17 +96,19 @@ def _get_current_user_token_payload( CurrentUserTokenPayloadDep = Depends(_get_current_user_token_payload) -def _get_account_epoch(account_id: uuid.UUID) -> int: - """Retrieves the current epoch for the given account ID. The epoch is used to manage token versioning and invalidation. +def _get_account_epoch( + account_id: uuid.UUID, + session: Session, +) -> int: + account = session.get(Account, account_id) - Args: - account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch. + if account is None or account.deleted: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) - Returns: - int: The current epoch for the given account ID. - """ - - return 0 # TODO: Replace with actual logic to retrieve the epoch for the account + return account.epoch def _get_account_role(account_id: uuid.UUID) -> UserRole: @@ -136,6 +159,7 @@ def get_access_token( response: Response, id_token: str, real_account_id: uuid.UUID, + session: Session, effective_account_id: Optional[uuid.UUID] = None, ) -> Dict[str, Any]: """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. @@ -159,6 +183,7 @@ def get_access_token( request=request, cookie_key="__Secure-Fgp-ID", token=id_token, + session=session, ) # If reaches here, the id_token is valid and the fingerprint matches @@ -179,7 +204,7 @@ def get_access_token( effective_account_id = real_account_id role = _get_account_role(effective_account_id) - epoch = _get_account_epoch(real_account_id) + epoch = _get_account_epoch(effective_account_id, session=session) organization_id = _get_account_organization(effective_account_id) user_fingerprint_hash = _set_act_fp_cookie(response=response) @@ -254,7 +279,11 @@ def _set_fingerprint_cookie( return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() -def _refresh_access_token(request: Request, refresh_token: str) -> str: +def _refresh_access_token( + request: Request, + refresh_token: str, + session: Session, +) -> str: """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. Args: @@ -269,6 +298,7 @@ def _refresh_access_token(request: Request, refresh_token: str) -> str: request=request, cookie_key="__Secure-Fgp-Act", token=refresh_token, + session=session, ) access_payload = { @@ -356,7 +386,12 @@ def _build_token(payload: Dict[str, Any], expiration_min: int) -> str: return token -def _verify_fp_token(request: Request, cookie_key: str, token: str) -> Dict[str, Any]: +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: @@ -412,9 +447,19 @@ def _verify_fp_token(request: Request, cookie_key: str, token: str) -> Dict[str, detail="Token missing real account ID", ) - real_account_epoch = _get_account_epoch(uuid.UUID(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( + epoch_account_id, + session=session, + ) + token_epoch = payload.get(EPOCH_KEY) - if token_epoch is None or token_epoch != real_account_epoch: + if token_epoch is None or token_epoch != current_account_epoch: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token epoch mismatch", @@ -438,9 +483,47 @@ def refresh_access_token(refresh_token: RefreshToken): pass -def logout(): - pass +def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: + account = session.get(Account, account_id) + + if account is None or account.deleted: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) + + return account -def change_password(new_password: str, invalidate_tokens: bool = True): - pass +def logout(session: Session, access_token: AccessToken) -> dict: + 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: + 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"} From 8390764ff4c89719cc9939491c14774dce0e020c Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Thu, 25 Jun 2026 12:06:58 +0200 Subject: [PATCH 05/31] Implement OTK login --- service/src/main/inse/auth/router.py | 9 +-- service/src/main/inse/auth/service.py | 86 +++++++++++++++++++++++---- 2 files changed, 81 insertions(+), 14 deletions(-) diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index e8ec22ec..7e8eadf4 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -2,7 +2,7 @@ import logging from typing import Annotated import uuid -from fastapi import APIRouter, Body, Depends, status +from fastapi import APIRouter, Body, Depends, Response, status from sqlmodel import Session from inse.tags import Tags @@ -35,7 +35,7 @@ async def request_otk( email: Annotated[str, Body(description="User's email address")], password: Annotated[str, Body(description="User's password")], ): - auth_service.request_otk(email, password) + return auth_service.request_otk(session, email, password) @router.post( @@ -47,9 +47,10 @@ async def request_otk( ) async def login( session: SessionDep, - email_code: Annotated[str, Body(description="One-time code sent to user's email")], + response: Response, + email_code: Annotated[str, Body(embed=True, description="One-time code sent to user's email")], ): - auth_service.login(email_code) + return auth_service.login(session, response, email_code) @router.post( diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 6cbaf648..fc0237f2 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -2,6 +2,7 @@ import datetime import hashlib import secrets import uuid +import logging from typing import Annotated, Any, Dict, Literal, Optional import jwt @@ -9,10 +10,10 @@ 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 AccessToken, Account, RefreshToken, UserRole +from inse.auth.model import AccessToken, Account, RefreshToken, Secret, UserRole from inse.config import get_settings from inse.database import get_session -from sqlmodel import Session +from sqlmodel import Session, select ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes @@ -27,6 +28,8 @@ USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" settings = get_settings() +logger = logging.getLogger(__name__) + security_scheme = HTTPBearer() _password_hasher = PasswordHasher() @@ -43,17 +46,80 @@ def _verify_password(password: str, password_hash: str) -> bool: return False -def request_otk(email: str, password: str): - pass +def request_otk(session: Session, email: str, password: str): + account = session.exec( + select(Account).where( + Account.email == email, + Account.deleted == False, + ) + ).first() + + if account is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid email or password", + ) + + if not _verify_password(password, account.password_hash): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid email or password", + ) + + otk_code = f"{secrets.randbelow(1_000_000):06d}" + + secret = session.exec( + select(Secret).where(Secret.account_id == account.id) + ).first() + + expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( + minutes=5 + ) + + 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() + + logger.info("OTK code for account %s: %s", account.id, otk_code) + + return {"status": "ok"} -def login(response: Response, emailCode: str) -> str: - # TODO: validate emailCode and retrieve the associated account IDF - real_account_id = uuid.uuid4() - # TODO: Replace with actual account ID retrieval logic +def login(session: Session, response: Response, email_code: str): + now = datetime.datetime.now(datetime.timezone.utc) + + secret = session.exec( + select(Secret).where(Secret.secret_value == email_code) + ).first() + + if secret is None or secret.expires_at <= now: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired code", + ) + + account = _get_active_account(session, secret.account_id) + + id_token = _build_id_token( + response, + account.id, + account.epoch, + ) + + session.delete(secret) + session.commit() + + return {"idToken": id_token} - epoch = _get_account_epoch(real_account_id) - return _build_id_token(response, real_account_id, epoch) def _get_current_user_token_payload( From 3d8fc2431fca73a5c95bbdfff5202c8cf0201d1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 25 Jun 2026 14:58:06 +0200 Subject: [PATCH 06/31] Integrated different auth methods with eachother --- service/pyproject.toml | 1 + service/src/main/inse/auth/model.py | 5 + service/src/main/inse/auth/router.py | 57 ++-- service/src/main/inse/auth/service.py | 380 +++++++++++++++++++++----- service/uv.lock | 57 +++- 5 files changed, 402 insertions(+), 98 deletions(-) diff --git a/service/pyproject.toml b/service/pyproject.toml index 5307b6e8..118c8fe1 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -20,6 +20,7 @@ dependencies = [ "sentence-transformers~=5.5.1", "torch", "sqlmodel~=0.0.33", + "argon2-cffi~=25.1.0", ] [[tool.uv.index]] diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 31b6825f..c2458204 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -129,6 +129,11 @@ class Token(BaseModel): 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.", + ) class IdToken(Token): diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 7e8eadf4..eeeeaa88 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -1,5 +1,5 @@ import logging -from typing import Annotated +from typing import Annotated, Dict import uuid from fastapi import APIRouter, Body, Depends, Response, status @@ -8,8 +8,8 @@ from sqlmodel import Session from inse.tags import Tags import inse.auth.service as auth_service -from inse.auth.model import IdToken, RefreshToken, AccessToken from inse.database import SessionDep, get_session +from inse.auth.model import AccessToken, IdToken, RefreshToken logger = logging.getLogger(__name__) @@ -48,7 +48,9 @@ async def request_otk( async def login( session: SessionDep, response: Response, - email_code: Annotated[str, Body(embed=True, description="One-time code sent to user's email")], + email_code: Annotated[ + str, Body(embed=True, description="One-time code sent to user's email") + ], ): return auth_service.login(session, response, email_code) @@ -62,12 +64,22 @@ async def login( status.HTTP_200_OK: {"description": "Access token retrieved successfully."} }, ) -async def get_access_token( +async def get_action_tokens( + response: Response, session: SessionDep, - account_id: Annotated[uuid.UUID, Body(description="User's account ID")], - id_token: IdToken, -): - auth_service.get_access_token(account_id, id_token) + 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], +) -> Dict[str, str]: + 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( @@ -80,10 +92,11 @@ async def get_access_token( }, ) async def refresh_access_token( - session: SessionDep, - refresh_token: RefreshToken, -): - auth_service.refresh_access_token(refresh_token) + refresh_token: Annotated[ + RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep + ], +) -> str: + return auth_service.refresh_access_token(refresh_token=refresh_token) @router.post( @@ -95,9 +108,12 @@ async def refresh_access_token( ) async def logout( session: Annotated[Session, Depends(get_session)], - access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep, + access_token: Annotated[ + AccessToken, + auth_service.CurrentUserAccessTokenPayloadDep, + ], ): - return auth_service.logout(session, access_token) + return auth_service.logout(session=session, access_token=access_token) @router.post( @@ -117,11 +133,14 @@ async def change_password( str, Body(description="New password", min_length=8), ], - access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep, + access_token: Annotated[ + AccessToken, + auth_service.CurrentUserAccessTokenPayloadDep, + ], ): return auth_service.change_password( - session, - access_token, - current_password, - new_password, + session=session, + access_token=access_token, + current_password=current_password, + new_password=new_password, ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index fc0237f2..0f82d101 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -10,7 +10,14 @@ 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 AccessToken, Account, RefreshToken, Secret, UserRole +from inse.auth.model import ( + AccessToken, + Account, + IdToken, + RefreshToken, + Secret, + UserRole, +) from inse.config import get_settings from inse.database import get_session from sqlmodel import Session, select @@ -19,6 +26,8 @@ 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" @@ -26,6 +35,9 @@ EPOCH_KEY = "epoch" ORGANIZATION_ID_KEY = "organization_id" 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__) @@ -34,12 +46,34 @@ security_scheme = HTTPBearer() _password_hasher = PasswordHasher() +AccountNotFoundException = HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Account not found.", +) + 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): @@ -47,20 +81,36 @@ def _verify_password(password: str, password_hash: str) -> bool: 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. + """ account = session.exec( select(Account).where( Account.email == email, - Account.deleted == False, + not Account.deleted, ) ).first() - if account is None: + if account is None or account.deleted or account.id is None: + logger.warning("OTK request failed for email %s: account not found", email) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, 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", @@ -68,12 +118,10 @@ def request_otk(session: Session, email: str, password: str): otk_code = f"{secrets.randbelow(1_000_000):06d}" - secret = session.exec( - select(Secret).where(Secret.account_id == account.id) - ).first() + secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first() expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( - minutes=5 + minutes=OTK_EXPIRATION_MINUTES ) if secret is None: @@ -89,12 +137,25 @@ def request_otk(session: Session, email: str, password: str): session.commit() - logger.info("OTK code for account %s: %s", account.id, otk_code) + logger.info( + "Saved OTK for account %s with expiration at %s", account.id, expires_at + ) return {"status": "ok"} def login(session: Session, response: Response, email_code: str): + """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. + 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. + """ now = datetime.datetime.now(datetime.timezone.utc) secret = session.exec( @@ -102,12 +163,19 @@ def login(session: Session, response: Response, email_code: str): ).first() if secret is None or secret.expires_at <= 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", ) account = _get_active_account(session, secret.account_id) + if not account or account.deleted or account.id is None: + logger.warning("Login failed: account is not active %s", secret.account_id) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) id_token = _build_id_token( response, @@ -118,30 +186,30 @@ def login(session: Session, response: Response, email_code: str): session.delete(secret) session.commit() - return {"idToken": id_token} + return {"id_token": id_token} - -def _get_current_user_token_payload( +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 token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. + """Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: - request (Request): The FastAPI request object containing the cookies. - credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials extracted from the request. + 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: - Dict[str, Any]: The verified token payload. + AccessToken: The verified access token payload. """ token = credentials.credentials access_token_payload = _verify_fp_token( request=request, - cookie_key="__Secure-Fgp-Act", + cookie_key=ACT_FP_COOKIE_KEY, token=token, session=session, ) @@ -159,73 +227,191 @@ def _get_current_user_token_payload( ) -CurrentUserTokenPayloadDep = Depends(_get_current_user_token_payload) +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 + return 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[ORGANIZATION_ID_KEY]), + ) + + +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: + Dict[str, Any]: The verified ID token payload. + """ + token = credentials.credentials + + 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], + ) + + +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( - account_id: uuid.UUID, 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: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Account is not active.", - ) + if account is None or account.deleted or account.id is None: + raise AccountNotFoundException return account.epoch -def _get_account_role(account_id: uuid.UUID) -> UserRole: +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. """ - return ( - UserRole.USER - ) # TODO: Replace with actual logic to retrieve the role for the account + 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(account_id: uuid.UUID) -> uuid.UUID: +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. """ - return ( - uuid.uuid4() - ) # TODO: Replace with actual logic to retrieve the organization ID for the account + 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( - real_account_id: uuid.UUID, effective_account_id: uuid.UUID + 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. """ - return True # TODO: Replace with actual logic to check if impersonation is allowed + 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 + + return False def get_access_token( - request: Request, response: Response, - id_token: str, - real_account_id: uuid.UUID, session: Session, + id_token: IdToken, + real_account_id: uuid.UUID, effective_account_id: Optional[uuid.UUID] = None, ) -> Dict[str, Any]: """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. @@ -244,23 +430,20 @@ def get_access_token( Returns: Dict[str, Any]: A dictionary 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. - id_token_payload = _verify_fp_token( - request=request, - cookie_key="__Secure-Fgp-ID", - token=id_token, - session=session, - ) - # If reaches here, the id_token is valid and the fingerprint matches - - if str(real_account_id) != id_token_payload[REAL_ACCOUNT_ID_KEY]: + if str(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", ) if effective_account_id: - if not _is_valid_impersonation(real_account_id, effective_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", @@ -269,9 +452,11 @@ def get_access_token( # No impersonation, set effective_account_id to real_account_id effective_account_id = real_account_id - role = _get_account_role(effective_account_id) - epoch = _get_account_epoch(effective_account_id, session=session) - organization_id = _get_account_organization(effective_account_id) + role = _get_account_role(session=session, account_id=effective_account_id) + epoch = _get_account_epoch(account_id=effective_account_id, session=session) + organization_id = _get_account_organization( + session=session, account_id=effective_account_id + ) user_fingerprint_hash = _set_act_fp_cookie(response=response) @@ -299,7 +484,7 @@ def _set_id_fp_cookie(response: Response) -> str: str: The hashed value of the fingerprint. """ return _set_fingerprint_cookie( - response, "__Secure-Fgp-ID", max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 + response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 ) @@ -313,7 +498,7 @@ def _set_act_fp_cookie(response: Response) -> str: str: The hashed value of the fingerprint. """ return _set_fingerprint_cookie( - response, "__Secure-Fgp-Act" + response, ACT_FP_COOKIE_KEY ) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. @@ -345,35 +530,46 @@ def _set_fingerprint_cookie( return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() +def refresh_access_token(refresh_token: RefreshToken) -> str: + """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: + str: 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( - request: Request, - refresh_token: str, - session: Session, + refresh_token: RefreshToken, ) -> str: """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 (str): The refresh token to verify. + refresh_token (RefreshToken): The refresh token to verify. current_user_epoch (int): The epoch value for the tokens. Returns: str: The refreshed access token. """ - refresh_payload = _verify_fp_token( - request=request, - cookie_key="__Secure-Fgp-Act", - token=refresh_token, - session=session, - ) + # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. access_payload = { - REAL_ACCOUNT_ID_KEY: refresh_payload[REAL_ACCOUNT_ID_KEY], - EFFECTIVE_ACCOUNT_ID_KEY: refresh_payload[EFFECTIVE_ACCOUNT_ID_KEY], - EPOCH_KEY: refresh_payload[EPOCH_KEY], - EFFECTIVE_ROLE_KEY: refresh_payload[EFFECTIVE_ROLE_KEY], - ORGANIZATION_ID_KEY: refresh_payload[ORGANIZATION_ID_KEY], - USER_FINGERPRINT_HASH_KEY: refresh_payload[USER_FINGERPRINT_HASH_KEY], + REAL_ACCOUNT_ID_KEY: refresh_token.real_account_id, + EFFECTIVE_ACCOUNT_ID_KEY: refresh_token.effective_account_id, + EPOCH_KEY: refresh_token.epoch, + EFFECTIVE_ROLE_KEY: refresh_token.effective_role, + ORGANIZATION_ID_KEY: refresh_token.effective_organization_id, + USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash, } return _build_token( payload=access_payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES @@ -520,8 +716,8 @@ def _verify_fp_token( epoch_account_id = uuid.UUID(effective_account_id) current_account_epoch = _get_account_epoch( - epoch_account_id, session=session, + account_id=epoch_account_id, ) token_epoch = payload.get(EPOCH_KEY) @@ -545,14 +741,22 @@ def _verify_fp_token( ) -def refresh_access_token(refresh_token: RefreshToken): - pass - - 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: + 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.", @@ -561,7 +765,18 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: return account -def logout(session: Session, access_token: AccessToken) -> dict: +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 @@ -577,7 +792,22 @@ def change_password( access_token: AccessToken, current_password: str, new_password: str, -) -> dict: +) -> 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): diff --git a/service/uv.lock b/service/uv.lock index 03c67be5..0881f9d2 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -2,8 +2,10 @@ version = 1 revision = 3 requires-python = ">=3.12" resolution-markers = [ - "sys_platform != 'darwin'", - "sys_platform == 'darwin'", + "python_full_version >= '3.14' and sys_platform != 'darwin'", + "python_full_version < '3.14' and sys_platform != 'darwin'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version < '3.14' and sys_platform == 'darwin'", ] [[package]] @@ -37,6 +39,49 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" }, ] +[[package]] +name = "argon2-cffi" +version = "25.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "argon2-cffi-bindings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" }, +] + +[[package]] +name = "argon2-cffi-bindings" +version = "25.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/97/3c0a35f46e52108d4707c44b95cfe2afcafc50800b5450c197454569b776/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:3d3f05610594151994ca9ccb3c771115bdb4daef161976a266f0dd8aa9996b8f", size = 54393, upload-time = "2025-07-30T10:01:40.97Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/98bbd6ee89febd4f212696f13c03ca302b8552e7dbf9c8efa11ea4a388c3/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8b8efee945193e667a396cbc7b4fb7d357297d6234d30a489905d96caabde56b", size = 29328, upload-time = "2025-07-30T10:01:41.916Z" }, + { url = "https://files.pythonhosted.org/packages/43/24/90a01c0ef12ac91a6be05969f29944643bc1e5e461155ae6559befa8f00b/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3c6702abc36bf3ccba3f802b799505def420a1b7039862014a65db3205967f5a", size = 31269, upload-time = "2025-07-30T10:01:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/d4/d3/942aa10782b2697eee7af5e12eeff5ebb325ccfb86dd8abda54174e377e4/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1c70058c6ab1e352304ac7e3b52554daadacd8d453c1752e547c76e9c99ac44", size = 86558, upload-time = "2025-07-30T10:01:43.943Z" }, + { url = "https://files.pythonhosted.org/packages/0d/82/b484f702fec5536e71836fc2dbc8c5267b3f6e78d2d539b4eaa6f0db8bf8/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2fd3bfbff3c5d74fef31a722f729bf93500910db650c925c2d6ef879a7e51cb", size = 92364, upload-time = "2025-07-30T10:01:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/c9/c1/a606ff83b3f1735f3759ad0f2cd9e038a0ad11a3de3b6c673aa41c24bb7b/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c4f9665de60b1b0e99bcd6be4f17d90339698ce954cfd8d9cf4f91c995165a92", size = 85637, upload-time = "2025-07-30T10:01:46.225Z" }, + { url = "https://files.pythonhosted.org/packages/44/b4/678503f12aceb0262f84fa201f6027ed77d71c5019ae03b399b97caa2f19/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ba92837e4a9aa6a508c8d2d7883ed5a8f6c308c89a4790e1e447a220deb79a85", size = 91934, upload-time = "2025-07-30T10:01:47.203Z" }, + { url = "https://files.pythonhosted.org/packages/f0/c7/f36bd08ef9bd9f0a9cff9428406651f5937ce27b6c5b07b92d41f91ae541/argon2_cffi_bindings-25.1.0-cp314-cp314t-win32.whl", hash = "sha256:84a461d4d84ae1295871329b346a97f68eade8c53b6ed9a7ca2d7467f3c8ff6f", size = 28158, upload-time = "2025-07-30T10:01:48.341Z" }, + { url = "https://files.pythonhosted.org/packages/b3/80/0106a7448abb24a2c467bf7d527fe5413b7fdfa4ad6d6a96a43a62ef3988/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b55aec3565b65f56455eebc9b9f34130440404f27fe21c3b375bf1ea4d8fbae6", size = 32597, upload-time = "2025-07-30T10:01:49.112Z" }, + { url = "https://files.pythonhosted.org/packages/05/b8/d663c9caea07e9180b2cb662772865230715cbd573ba3b5e81793d580316/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87c33a52407e4c41f3b70a9c2d3f6056d88b10dad7695be708c5021673f55623", size = 28231, upload-time = "2025-07-30T10:01:49.92Z" }, + { url = "https://files.pythonhosted.org/packages/1d/57/96b8b9f93166147826da5f90376e784a10582dd39a393c99bb62cfcf52f0/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:aecba1723ae35330a008418a91ea6cfcedf6d31e5fbaa056a166462ff066d500", size = 54121, upload-time = "2025-07-30T10:01:50.815Z" }, + { url = "https://files.pythonhosted.org/packages/0a/08/a9bebdb2e0e602dde230bdde8021b29f71f7841bd54801bcfd514acb5dcf/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2630b6240b495dfab90aebe159ff784d08ea999aa4b0d17efa734055a07d2f44", size = 29177, upload-time = "2025-07-30T10:01:51.681Z" }, + { url = "https://files.pythonhosted.org/packages/b6/02/d297943bcacf05e4f2a94ab6f462831dc20158614e5d067c35d4e63b9acb/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:7aef0c91e2c0fbca6fc68e7555aa60ef7008a739cbe045541e438373bc54d2b0", size = 31090, upload-time = "2025-07-30T10:01:53.184Z" }, + { url = "https://files.pythonhosted.org/packages/c1/93/44365f3d75053e53893ec6d733e4a5e3147502663554b4d864587c7828a7/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e021e87faa76ae0d413b619fe2b65ab9a037f24c60a1e6cc43457ae20de6dc6", size = 81246, upload-time = "2025-07-30T10:01:54.145Z" }, + { url = "https://files.pythonhosted.org/packages/09/52/94108adfdd6e2ddf58be64f959a0b9c7d4ef2fa71086c38356d22dc501ea/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3e924cfc503018a714f94a49a149fdc0b644eaead5d1f089330399134fa028a", size = 87126, upload-time = "2025-07-30T10:01:55.074Z" }, + { url = "https://files.pythonhosted.org/packages/72/70/7a2993a12b0ffa2a9271259b79cc616e2389ed1a4d93842fac5a1f923ffd/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87b72589133f0346a1cb8d5ecca4b933e3c9b64656c9d175270a000e73b288d", size = 80343, upload-time = "2025-07-30T10:01:56.007Z" }, + { url = "https://files.pythonhosted.org/packages/78/9a/4e5157d893ffc712b74dbd868c7f62365618266982b64accab26bab01edc/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1db89609c06afa1a214a69a462ea741cf735b29a57530478c06eb81dd403de99", size = 86777, upload-time = "2025-07-30T10:01:56.943Z" }, + { url = "https://files.pythonhosted.org/packages/74/cd/15777dfde1c29d96de7f18edf4cc94c385646852e7c7b0320aa91ccca583/argon2_cffi_bindings-25.1.0-cp39-abi3-win32.whl", hash = "sha256:473bcb5f82924b1becbb637b63303ec8d10e84c8d241119419897a26116515d2", size = 27180, upload-time = "2025-07-30T10:01:57.759Z" }, + { url = "https://files.pythonhosted.org/packages/e2/c6/a759ece8f1829d1f162261226fbfd2c6832b3ff7657384045286d2afa384/argon2_cffi_bindings-25.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:a98cd7d17e9f7ce244c0803cad3c23a7d379c301ba618a5fa76a67d116618b98", size = 31715, upload-time = "2025-07-30T10:01:58.56Z" }, + { url = "https://files.pythonhosted.org/packages/42/b9/f8d6fa329ab25128b7e98fd83a3cb34d9db5b059a9847eddb840a0af45dd/argon2_cffi_bindings-25.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:b0fdbcf513833809c882823f98dc2f931cf659d9a1429616ac3adebb49f5db94", size = 27149, upload-time = "2025-07-30T10:01:59.329Z" }, +] + [[package]] name = "certifi" version = "2026.5.20" @@ -1083,6 +1128,7 @@ name = "service" version = "0.1.0" source = { virtual = "." } dependencies = [ + { name = "argon2-cffi" }, { name = "cryptography" }, { name = "dotenv" }, { name = "fastapi" }, @@ -1103,6 +1149,7 @@ dependencies = [ [package.metadata] requires-dist = [ + { name = "argon2-cffi", specifier = "~=25.1.0" }, { name = "cryptography", specifier = "~=42.0.0" }, { name = "dotenv", specifier = ">=0.9.9" }, { name = "fastapi", specifier = "~=0.115.0" }, @@ -1265,7 +1312,8 @@ name = "torch" version = "2.12.0" source = { registry = "https://download.pytorch.org/whl/cpu" } resolution-markers = [ - "sys_platform == 'darwin'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version < '3.14' and sys_platform == 'darwin'", ] dependencies = [ { name = "filelock", marker = "sys_platform == 'darwin'" }, @@ -1289,7 +1337,8 @@ name = "torch" version = "2.12.0+cpu" source = { registry = "https://download.pytorch.org/whl/cpu" } resolution-markers = [ - "sys_platform != 'darwin'", + "python_full_version >= '3.14' and sys_platform != 'darwin'", + "python_full_version < '3.14' and sys_platform != 'darwin'", ] dependencies = [ { name = "filelock", marker = "sys_platform != 'darwin'" }, From 6d25d5c51f1d6d59ee6dfa831fd1faa64c533d91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 25 Jun 2026 15:28:57 +0200 Subject: [PATCH 07/31] Added functionality to populate predefined accounts --- service/src/data/predefined_accounts.json | 17 +++++++ service/src/main/inse/auth/model.py | 8 +-- service/src/main/inse/auth/service.py | 62 ++++++++++++++++++++++- service/src/main/inse/main.py | 7 ++- 4 files changed, 87 insertions(+), 7 deletions(-) create mode 100644 service/src/data/predefined_accounts.json diff --git a/service/src/data/predefined_accounts.json b/service/src/data/predefined_accounts.json new file mode 100644 index 00000000..51ea8a4f --- /dev/null +++ b/service/src/data/predefined_accounts.json @@ -0,0 +1,17 @@ +{ + "organizations": [ + { + "id": "c001beef-cafe-4000-8000-d34db33f000d", + "name": "The Super Admin Organization" + } + ], + "accounts": [ + { + "email": "super@admin.com", + "password": "superadmin", + "name": "Super Admin", + "organization_id": "c001beef-cafe-4000-8000-d34db33f000d", + "role": "SUPER_ADMIN" + } + ] +} diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index c2458204..56cfd635 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -8,10 +8,10 @@ from sqlmodel import Field, Relationship, SQLModel class UserRole(StrEnum): - SUPER_ADMIN = "super_admin" - ADMIN = "admin" - MANAGER = "manager" - USER = "user" + SUPER_ADMIN = "SUPER_ADMIN" + ADMIN = "ADMIN" + MANAGER = "MANAGER" + USER = "USER" class Durable(SQLModel): diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 0f82d101..a88b7c9c 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,5 +1,6 @@ import datetime import hashlib +import json import secrets import uuid import logging @@ -14,13 +15,14 @@ from inse.auth.model import ( AccessToken, Account, IdToken, + Organization, RefreshToken, Secret, UserRole, ) from inse.config import get_settings from inse.database import get_session -from sqlmodel import Session, select +from sqlmodel import Session, select, func ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes @@ -52,6 +54,64 @@ AccountNotFoundException = HTTPException( ) +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 = json.loads(file.read()) + for organization_data in data.get("organizations", []): + organization_id = uuid.UUID(organization_data["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. diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 40f6b2e9..63724547 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -6,7 +6,7 @@ for fastapi that loads the service and the webapp. """ -from contextlib import asynccontextmanager +from contextlib import asynccontextmanager, contextmanager import logging from fastapi import FastAPI, Request @@ -31,7 +31,8 @@ from inse.patents.service import router as patents_service_router from inse.auth.router import router as auth_router from inse.institutions.router import router as institutions_router -from inse.database import create_db_and_tables +from inse.database import create_db_and_tables, get_session +from inse.auth.service import create_predefined_accounts from . import config from .account.service import router as account_router @@ -46,6 +47,8 @@ settings = config.get_settings() async def lifespan(app: FastAPI): logger.info("Starting up the application...") create_db_and_tables() + with contextmanager(get_session)() as session: + create_predefined_accounts(session, "../data/predefined_accounts.json") yield logger.info("Shutting down the application...") From d8a991cc3ae02587bd0c272126995630542ed9ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 25 Jun 2026 17:26:28 +0200 Subject: [PATCH 08/31] Fixed minor validation flaws --- service/src/main/inse/auth/model.py | 28 +- service/src/main/inse/auth/router.py | 14 +- service/src/main/inse/auth/service.py | 78 +- service/src/main/inse/config.py | 2 + service/src/main/inse/logic.py | 213 ++ service/src/main/inse/main.py | 5 + .../src/main/inse/middleware/etag_cache.py | 31 +- service/src/main/inse/service.py | 86 + service/src/main/inse/topics/logic.py | 142 +- webapp/src/app/api/.openapi-generator/FILES | 9 +- webapp/src/app/api/README.md | 91 +- webapp/src/app/api/api.base.service.ts | 158 +- webapp/src/app/api/api.module.ts | 52 +- webapp/src/app/api/api/api.ts | 20 +- webapp/src/app/api/api/auth.service.ts | 484 ++++ .../app/api/api/companyConnections.service.ts | 185 +- webapp/src/app/api/api/funding.service.ts | 366 +-- .../app/api/api/iNSEAccountService.service.ts | 657 ++--- webapp/src/app/api/api/iNSEService.service.ts | 1082 ++----- .../src/app/api/api/institutions.service.ts | 1045 +++---- webapp/src/app/api/api/items.service.ts | 634 ---- webapp/src/app/api/api/news.service.ts | 1500 ++++------ webapp/src/app/api/api/patents.service.ts | 185 +- .../src/app/api/api/personNetwork.service.ts | 215 +- webapp/src/app/api/api/persons.service.ts | 2576 ++++++----------- webapp/src/app/api/api/projects.service.ts | 1666 ++++------- webapp/src/app/api/api/topics.service.ts | 1150 +++----- webapp/src/app/api/api/works.service.ts | 1001 +++---- webapp/src/app/api/configuration.ts | 368 ++- webapp/src/app/api/encoder.ts | 24 +- webapp/src/app/api/model/accessGrant.ts | 16 +- webapp/src/app/api/model/authAccount.ts | 16 +- webapp/src/app/api/model/authScope.ts | 14 +- webapp/src/app/api/model/author.ts | 40 +- .../app/api/model/authorAffiliationsInner.ts | 10 +- .../app/api/model/authorCountsByYearInner.ts | 12 +- webapp/src/app/api/model/authorIds.ts | 12 +- webapp/src/app/api/model/authorNetworkNode.ts | 34 +- .../app/api/model/authorParsedLongestName.ts | 16 +- .../src/app/api/model/authorPositionCount.ts | 14 +- .../src/app/api/model/authorSummaryStats.ts | 12 +- .../app/api/model/authorsFilterProperties.ts | 30 +- .../src/app/api/model/authorsListResponse.ts | 12 +- webapp/src/app/api/model/authorship.ts | 20 +- .../src/app/api/model/autocompleteResponse.ts | 10 +- .../app/api/model/autocompleteResponseMeta.ts | 10 +- .../model/autocompleteResponseResultsInner.ts | 20 +- webapp/src/app/api/model/award.ts | 18 +- .../model/{item.ts => bodyChangePassword.ts} | 26 +- webapp/src/app/api/model/bodyCreateUser.ts | 16 +- .../src/app/api/model/bodyGetAccessToken.ts | 22 + webapp/src/app/api/model/bodyLogin.ts | 22 + .../{itemCreate.ts => bodyRequestOtk.ts} | 22 +- webapp/src/app/api/model/bundProject.ts | 62 +- .../src/app/api/model/bundProjectDetails.ts | 86 +- webapp/src/app/api/model/bundProjectPage.ts | 38 +- webapp/src/app/api/model/careerMetrics.ts | 46 +- .../src/app/api/model/collaborationNetwork.ts | 54 +- .../app/api/model/collaborationNetworkEdge.ts | 22 +- .../api/model/collaborationNetworkNodeType.ts | 13 +- webapp/src/app/api/model/companyConnection.ts | 30 +- .../api/model/companyConnectionsResponse.ts | 26 +- webapp/src/app/api/model/cordisEuProject.ts | 56 +- .../src/app/api/model/cordisEuProjectPage.ts | 38 +- webapp/src/app/api/model/costUsd.ts | 7 +- webapp/src/app/api/model/customAuthor.ts | 44 +- .../api/model/customAuthorsListResponse.ts | 14 +- webapp/src/app/api/model/dehydratedAuthor.ts | 12 +- webapp/src/app/api/model/dehydratedFunder.ts | 12 +- .../app/api/model/dehydratedInstitution.ts | 18 +- webapp/src/app/api/model/dehydratedSource.ts | 28 +- webapp/src/app/api/model/dfgProjectDetails.ts | 54 +- webapp/src/app/api/model/dfgProjectPage.ts | 38 +- webapp/src/app/api/model/dfgProjectSummary.ts | 32 +- .../api/model/euOrganizationProjectSummary.ts | 32 +- .../model/euOrganizationProjectSummaryPage.ts | 38 +- webapp/src/app/api/model/filterInformation.ts | 38 +- webapp/src/app/api/model/filterProperties.ts | 18 +- webapp/src/app/api/model/funderByAuthor.ts | 22 +- .../app/api/model/fundersByAuthorResponse.ts | 14 +- webapp/src/app/api/model/fundingProject.ts | 36 +- .../src/app/api/model/fundingProjectPage.ts | 38 +- webapp/src/app/api/model/fwci.ts | 7 +- webapp/src/app/api/model/groupByResult.ts | 12 +- .../src/app/api/model/hTTPValidationError.ts | 8 +- webapp/src/app/api/model/identityGrant.ts | 14 +- webapp/src/app/api/model/institution.ts | 46 +- .../app/api/model/institutionFunderSummary.ts | 34 +- webapp/src/app/api/model/institutionGeo.ts | 20 +- webapp/src/app/api/model/institutionIds.ts | 18 +- .../app/api/model/institutionInformation.ts | 22 +- .../app/api/model/institutionNetworkNode.ts | 34 +- webapp/src/app/api/model/institutionPage.ts | 38 +- .../app/api/model/institutionsListResponse.ts | 12 +- webapp/src/app/api/model/itemPage.ts | 29 - webapp/src/app/api/model/keywords.ts | 7 +- webapp/src/app/api/model/latitude.ts | 7 +- webapp/src/app/api/model/location.ts | 24 +- webapp/src/app/api/model/longitude.ts | 7 +- webapp/src/app/api/model/matchedOfficer.ts | 24 +- webapp/src/app/api/model/mentionedPerson.ts | 12 +- webapp/src/app/api/model/meta.ts | 20 +- .../app/api/model/model2YrMeanCitedness.ts | 7 +- webapp/src/app/api/model/models.ts | 7 +- webapp/src/app/api/model/newsArticle.ts | 20 +- webapp/src/app/api/model/newsArticleDetail.ts | 24 +- webapp/src/app/api/model/newsPage.ts | 14 +- webapp/src/app/api/model/openAccess.ts | 14 +- webapp/src/app/api/model/patentEntry.ts | 26 +- .../app/api/model/patentsByAuthorResponse.ts | 14 +- webapp/src/app/api/model/personBio.ts | 14 +- webapp/src/app/api/model/projectType.ts | 12 +- .../api/model/projectsFilteringProperties.ts | 54 +- webapp/src/app/api/model/projectsSortBy.ts | 15 +- .../api/model/publicationDetailByFunder.ts | 68 +- .../model/publicationIdsByAuthorPosition.ts | 14 +- .../api/model/publicationsByAuthorResponse.ts | 20 +- webapp/src/app/api/model/rankingResponse.ts | 10 +- webapp/src/app/api/model/score.ts | 7 +- webapp/src/app/api/model/sortDirection.ts | 10 +- webapp/src/app/api/model/topic.ts | 32 +- webapp/src/app/api/model/topicCount.ts | 44 +- webapp/src/app/api/model/topicDomain.ts | 10 +- webapp/src/app/api/model/topicField.ts | 10 +- webapp/src/app/api/model/topicIds.ts | 10 +- webapp/src/app/api/model/topicSubfield.ts | 10 +- webapp/src/app/api/model/topics.ts | 7 +- webapp/src/app/api/model/topicsByTime.ts | 46 +- webapp/src/app/api/model/topicsByYear.ts | 38 +- .../src/app/api/model/topicsListResponse.ts | 12 +- webapp/src/app/api/model/universityRanking.ts | 33 +- .../src/app/api/model/universityTopicData.ts | 27 +- webapp/src/app/api/model/user.ts | 64 +- webapp/src/app/api/model/validationError.ts | 12 +- .../app/api/model/validationErrorLocInner.ts | 7 +- webapp/src/app/api/model/value.ts | 7 +- webapp/src/app/api/model/work.ts | 82 +- webapp/src/app/api/model/workBiblio.ts | 14 +- .../model/workCitationNormalizedPercentile.ts | 12 +- .../api/model/workCitedByPercentileYear.ts | 10 +- .../app/api/model/workCountsByYearInner.ts | 10 +- webapp/src/app/api/model/workHasContent.ts | 10 +- webapp/src/app/api/model/workIds.ts | 16 +- webapp/src/app/api/model/workKeyword.ts | 12 +- webapp/src/app/api/model/workMeshInner.ts | 16 +- webapp/src/app/api/model/workNetworkNode.ts | 38 +- webapp/src/app/api/model/workPage.ts | 46 +- .../workSustainableDevelopmentGoalsInner.ts | 12 +- webapp/src/app/api/model/workTopic.ts | 18 +- webapp/src/app/api/model/workTopicDomain.ts | 10 +- webapp/src/app/api/model/workTopicField.ts | 10 +- .../src/app/api/model/workTopicInformation.ts | 22 +- webapp/src/app/api/model/workTopicSubfield.ts | 10 +- .../app/api/model/worksFilterProperties.ts | 46 +- webapp/src/app/api/model/worksListResponse.ts | 12 +- webapp/src/app/api/model/yearlyData.ts | 12 +- webapp/src/app/api/param.ts | 37 +- webapp/src/app/api/provide-api.ts | 24 +- webapp/src/app/api/variables.ts | 10 +- .../modules/app-login/app-login.component.ts | 5 +- .../authentication.interceptor.ts | 5 +- 161 files changed, 6651 insertions(+), 10419 deletions(-) create mode 100644 service/src/main/inse/logic.py create mode 100644 service/src/main/inse/service.py create mode 100644 webapp/src/app/api/api/auth.service.ts delete mode 100644 webapp/src/app/api/api/items.service.ts rename webapp/src/app/api/model/{item.ts => bodyChangePassword.ts} (50%) create mode 100644 webapp/src/app/api/model/bodyGetAccessToken.ts create mode 100644 webapp/src/app/api/model/bodyLogin.ts rename webapp/src/app/api/model/{itemCreate.ts => bodyRequestOtk.ts} (55%) delete mode 100644 webapp/src/app/api/model/itemPage.ts diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 56cfd635..43408c69 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -14,6 +14,12 @@ class UserRole(StrEnum): USER = "USER" +class TokenType(StrEnum): + ID_TOKEN = "ID_TOKEN" + REFRESH_TOKEN = "REFRESH_TOKEN" + ACCESS_TOKEN = "ACCESS_TOKEN" + + class Durable(SQLModel): deleted: bool = Field( default=False, @@ -98,7 +104,7 @@ class Secret(SQLModel, table=True): ) account_id: uuid.UUID = Field( foreign_key="account.id", - unique=True, + 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.", ) @@ -115,6 +121,9 @@ class Secret(SQLModel, table=True): 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.", @@ -137,10 +146,19 @@ class Token(BaseModel): class IdToken(Token): - pass + 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.", @@ -166,4 +184,8 @@ class AccessToken(Token): class RefreshToken(AccessToken): - pass + token_type: TokenType = Field( + default=TokenType.REFRESH_TOKEN, + const=True, + description="The type of the token, which is always REFRESH_TOKEN for this class.", + ) diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index eeeeaa88..8133c315 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -35,7 +35,7 @@ async def request_otk( email: Annotated[str, Body(description="User's email address")], password: Annotated[str, Body(description="User's password")], ): - return auth_service.request_otk(session, email, password) + return auth_service.request_otk(session=session, email=email, password=password) @router.post( @@ -48,11 +48,14 @@ async def request_otk( 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") ], ): - return auth_service.login(session, response, email_code) + return auth_service.login( + session=session, response=response, account_id=account_id, email_code=email_code + ) @router.post( @@ -73,6 +76,13 @@ async def get_action_tokens( ], id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], ) -> Dict[str, str]: + 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, diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index a88b7c9c..1c6be36c 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -9,7 +9,7 @@ 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 import Depends, HTTPException, Header, Request, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from inse.auth.model import ( AccessToken, @@ -37,14 +37,14 @@ EPOCH_KEY = "epoch" ORGANIZATION_ID_KEY = "organization_id" USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" -ID_FP_COOKIE_KEY = "__Secure-Fgp-ID" -ACT_FP_COOKIE_KEY = "__Secure-Fgp-Act" +ID_FP_COOKIE_KEY = "_Secure-Fgp-ID" +ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act" settings = get_settings() logger = logging.getLogger(__name__) -security_scheme = HTTPBearer() +security_scheme = HTTPBearer(auto_error=False) _password_hasher = PasswordHasher() @@ -153,13 +153,18 @@ def request_otk(session: Session, email: str, password: str): 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, - not Account.deleted, + 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( @@ -204,12 +209,13 @@ def request_otk(session: Session, email: str, password: str): return {"status": "ok"} -def login(session: Session, response: Response, email_code: str): +def login(session: Session, response: Response, account_id: uuid.UUID, email_code: str): """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: @@ -219,19 +225,37 @@ def login(session: Session, response: Response, email_code: str): now = datetime.datetime.now(datetime.timezone.utc) secret = session.exec( - select(Secret).where(Secret.secret_value == email_code) + 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 secret is None or secret.expires_at <= 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", - ) + if not settings.skip_otk_validation: + if secret is None or secret.expires_at <= 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) - account = _get_active_account(session, secret.account_id) + 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", secret.account_id) + logger.warning("Login failed: account is not active %s", account_id) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Account is not active.", @@ -243,7 +267,6 @@ def login(session: Session, response: Response, email_code: str): account.epoch, ) - session.delete(secret) session.commit() return {"id_token": id_token} @@ -284,6 +307,7 @@ def _get_current_user_access_token_payload( epoch=access_token_payload[EPOCH_KEY], effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]), effective_organization_id=uuid.UUID(access_token_payload[ORGANIZATION_ID_KEY]), + user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY], ) @@ -311,7 +335,7 @@ def _get_current_user_refresh_token_payload( session=session, ) # If reaches here, the refresh token is valid and the fingerprint matches - return RefreshToken( + 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( @@ -320,8 +344,13 @@ def _get_current_user_refresh_token_payload( epoch=refresh_token_payload[EPOCH_KEY], effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]), effective_organization_id=uuid.UUID(refresh_token_payload[ORGANIZATION_ID_KEY]), + user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY], ) + 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)], @@ -338,7 +367,13 @@ def _get_current_user_id_token_payload( Returns: Dict[str, Any]: 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, @@ -354,6 +389,7 @@ def _get_current_user_id_token_payload( id_token_payload["exp"], tz=datetime.timezone.utc ), epoch=id_token_payload[EPOCH_KEY], + user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY], ) @@ -492,7 +528,7 @@ def get_access_token( """ # IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here. - if str(real_account_id) != id_token.real_account_id: + 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", @@ -624,11 +660,11 @@ def _refresh_access_token( # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. access_payload = { - REAL_ACCOUNT_ID_KEY: refresh_token.real_account_id, - EFFECTIVE_ACCOUNT_ID_KEY: refresh_token.effective_account_id, + REAL_ACCOUNT_ID_KEY: str(refresh_token.real_account_id), + EFFECTIVE_ACCOUNT_ID_KEY: str(refresh_token.effective_account_id), EPOCH_KEY: refresh_token.epoch, EFFECTIVE_ROLE_KEY: refresh_token.effective_role, - ORGANIZATION_ID_KEY: refresh_token.effective_organization_id, + ORGANIZATION_ID_KEY: str(refresh_token.effective_organization_id), USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash, } return _build_token( diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 8e7639ff..717f01ea 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -67,6 +67,8 @@ class Settings(BaseSettings): token_issuer_id: Optional[str] = None token_hmac_key: Optional[str] = None + skip_otk_validation: bool = True + settings = Settings() diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py new file mode 100644 index 00000000..ed400e2c --- /dev/null +++ b/service/src/main/inse/logic.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +This module defines the business logic for our +web service. +""" + +from typing import List +import logging +import httpx +import json + +from . import config + + +from inse.models.openalex.topic import Topic +from inse.models.openalex.topic_subfield import TopicSubfield +from inse.models.openalex.topic_field import TopicField +from inse.models.openalex.topic_domain import TopicDomain + + +logger = logging.getLogger(__name__) + + +topic_cache_filename: str = "topic_hierarchy_cache.json" + + +def _load_topic_cache() -> dict: + """Loads the topic hierarchy cache from a JSON file.""" + import os + + try: + cache_path = "/data/" + topic_cache_filename + if not os.path.exists(cache_path): + current_dir = os.path.dirname(__file__) + cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename) + with open(cache_path, "r", encoding="utf-8") as f: + return json.load(f) + except Exception as exc: + logger.warning("Failed to load topic hierarchy cache: %s", exc) + return {} + + +def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict: + """ + Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task). + + Arguments: + page_size (int): Number of topics to fetch per request (default: 200) + save_json (bool): Whether to save the cache as a JSON file (default: True) + + Returns: + taxonomy_cache (dict): The topic hierarchy dictionary. + """ + output_filename: str = "topic_hierarchy_cache.json" + headers = { + "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", + "Content-Type": "application/json", + } + + taxonomy_cache = {} + offset = 0 + + with httpx.Client(timeout=30.0) as client: + while True: + payload = {"query": {"match_all": {}}, "from": offset, "size": page_size} + response = client.post( + config.settings.elasticsearch_url + "/openalex-topics/_search", + json=payload, + headers=headers, + ) + response.raise_for_status() + data = response.json() + + hits = data.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + topic_name = source.get("display_name") or source.get("name") + if not topic_name: + continue + + taxonomy_cache[topic_name] = { + "topic_id": source.get("id") or hit.get("_id", ""), + "subfield": source.get("subfield", {}).get("display_name", ""), + "field": source.get("field", {}).get("display_name", ""), + "domain": source.get("domain", {}).get("display_name", ""), + } + + offset += len(hits) + logger.info("Processed %s topics total", len(taxonomy_cache)) + + if save_json: + data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True) + try: + output_path = "/data/" + output_filename + with open(output_path, "w", encoding="utf-8") as f: + f.write(data_json) + logger.info("Topic hierarchy cache written to %s", output_path) + except Exception as exc: + logger.warning("Failed to write topic hierarchy cache: %s", exc) + + return taxonomy_cache + + +def get_topics_from_cache(topic_names: List[str]) -> List[Topic]: + """ + Given a list of topic names, retrieves their hierarchy information from the cache and returns a list of Topic models. + Arguments: + topic_names (List[str]): A list of topic names to retrieve. + Returns: + List[Topic]: A list of Topic models. + """ + cache = _load_topic_cache() + topics = [] + for name in topic_names: + data = cache.get(name) + if not data: + continue + subfield_name = data.get("subfield", "") + field_name = data.get("field", "") + domain_name = data.get("domain", "") + topics.append( + Topic( + id=data.get("topic_id", ""), + display_name=name, + works_count=data.get("count", 1), + subfield=TopicSubfield(display_name=subfield_name) + if subfield_name + else None, + field=TopicField(display_name=field_name) if field_name else None, + domain=TopicDomain(display_name=domain_name) if domain_name else None, + ) + ) + return topics + + +def count_topic_hierarchy(topic_names: List[str]) -> dict: + """ + Given a list of topic names, counts the occurrences of each topic and their hierarchy levels (subfield, field, domain) using the cache. + Arguments: + topic_names (List[str]): A list of topic names to count. + Returns: + dict: A dictionary containing the counts of each hierarchy level. + """ + cache = _load_topic_cache() + counts = {"topics": {}, "subfields": {}, "fields": {}, "domains": {}} + + for name in topic_names: + data = cache.get(name) + if not data: + continue + + counts["topics"][name] = counts["topics"].get(name, 0) + 1 + + subfield = data.get("subfield", "") + if subfield: + counts["subfields"][subfield] = counts["subfields"].get(subfield, 0) + 1 + + field = data.get("field", "") + if field: + counts["fields"][field] = counts["fields"].get(field, 0) + 1 + + domain = data.get("domain", "") + if domain: + counts["domains"][domain] = counts["domains"].get(domain, 0) + 1 + + return counts + + +def get_topic_hierarchy() -> dict: + """ + Builds and returns a hierarchical tree structure of topics: + Domains -> Fields -> Subfields -> Topics + """ + flat_cache = _load_topic_cache() + tree = {} + + for topic_name, info in flat_cache.items(): + domain = info.get("domain") or "Unbekannter Bereich" + field = info.get("field") or "Unbekanntes Feld" + subfield = info.get("subfield") or "Unbekanntes Teilfeld" + topic_id = info.get("topic_id", "") + + # Clean topic ID to just be the trailing ID or keep full URL + # For querying, display name is used in persons search, but ID is useful + + if domain not in tree: + tree[domain] = {} + if field not in tree[domain]: + tree[domain][field] = {} + if subfield not in tree[domain][field]: + tree[domain][field][subfield] = [] + + tree[domain][field][subfield].append({"id": topic_id, "name": topic_name}) + + formatted_domains = [] + for d_name, d_fields in tree.items(): + formatted_fields = [] + for f_name, f_subfields in d_fields.items(): + formatted_subfields = [] + for sf_name, sf_topics in f_subfields.items(): + sf_topics.sort(key=lambda x: x["name"]) + formatted_subfields.append({"name": sf_name, "topics": sf_topics}) + formatted_subfields.sort(key=lambda x: x["name"]) + formatted_fields.append({"name": f_name, "subfields": formatted_subfields}) + formatted_fields.sort(key=lambda x: x["name"]) + formatted_domains.append({"name": d_name, "fields": formatted_fields}) + formatted_domains.sort(key=lambda x: x["name"]) + + return {"domains": formatted_domains} diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 63724547..e1030d0e 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -30,12 +30,15 @@ from inse.patents.service import router as patents_service_router from inse.auth.router import router as auth_router + from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from . import config from .account.service import router as account_router +from .service import router as service_router + logger = logging.getLogger(__name__) ### startup @@ -74,6 +77,8 @@ app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) +app.include_router(service_router) + app.include_router(auth_router) app.add_middleware( diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index 547aecb4..934ca51e 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -4,6 +4,7 @@ from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response + class ETagCacheMiddleware(BaseHTTPMiddleware): def __init__(self, app, ttl: int = 60): super().__init__(app) @@ -14,6 +15,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): # Include query params and relevant headers in the key return f"{request.url.path}?{request.url.query}" + def _content_type(self, response: Response) -> str | None: + return response.headers.get("content-type") + async def dispatch(self, request: Request, call_next): if request.method != "GET": return await call_next(request) @@ -25,28 +29,37 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): # Cache hit + not expired if entry and time.time() < entry["expires"]: if client_etag == entry["etag"]: - return Response(status_code=304, headers={"ETag": entry["etag"]}) - + headers = {"ETag": entry["etag"]} + if entry.get("content_type"): + headers["Content-Type"] = entry["content_type"] + return Response(status_code=304, headers=headers) + # Client has stale ETag - return fresh cached body + headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} + if entry.get("content_type"): + headers["Content-Type"] = entry["content_type"] return Response( content=entry["body"], - media_type="application/json", - headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} + headers=headers, ) - + # Cache miss or expired → hit the actual route response = await call_next(request) body = b"".join([chunk async for chunk in response.body_iterator]) etag = f'"{hashlib.md5(body).hexdigest()}"' + content_type = self._content_type(response) self.cache[key] = { "body": body, "etag": etag, - "expires": time.time() + self.ttl + "expires": time.time() + self.ttl, + "content_type": content_type, } + headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} + if content_type: + headers["Content-Type"] = content_type return Response( content=body, status_code=response.status_code, - media_type="application/json", - headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} - ) \ No newline at end of file + headers=headers, + ) diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py new file mode 100644 index 00000000..4e4a6593 --- /dev/null +++ b/service/src/main/inse/service.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +This module contains the rest api of the +service. +""" + +import logging +from typing import Annotated, List +from fastapi import Query +from inse.config import get_settings +from fastapi import APIRouter + + +from . import logic + + +logger = logging.getLogger(__name__) + +### startup + +settings = get_settings() + +router = APIRouter( + prefix="/api/inse-service", + tags=["INSE Service"], + responses={404: {"description": "Not found"}}, +) + + +### topics +# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing) +@router.get( + "/topics/cache", + operation_id="buildTopicCache", + response_model=dict, + summary="Builds the topic hierarchy cache.", + tags=["Topics"], +) +def build_topic_cache( + page_size: Annotated[ + int, Query(description="Page size for each search page.", ge=1, le=1000) + ] = 200, + save_json: Annotated[ + bool, Query(description="Persist cache JSON to data folder.") + ] = True, +): + return logic.build_topic_cache(page_size=page_size, save_json=save_json) + + +@router.get( + "/topics/count", + operation_id="countTopicHierarchy", + response_model=dict, + summary="Counts topic hierarchy occurrences from cache.", + tags=["Topics"], +) +def count_topic_hierarchy( + topic_names: Annotated[ + List[str], + Query( + alias="topic", + description="Topic names (repeat parameter).", + example=[ + "Big Data and Business Intelligence", + "Big Data and Business Intelligence", + "Topic Modeling", + "Entrepreneurship Studies and Influences", + "Complex Network Analysis Techniques", + "Semantic Web and Ontologies", + ], + ), + ], +): + return logic.count_topic_hierarchy(topic_names) + + +@router.get( + "/topics/hierarchy", + operation_id="getTopicHierarchy", + response_model=dict, + summary="Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).", + tags=["Topics"], +) +def get_topic_hierarchy(): + return logic.get_topic_hierarchy() diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index 2b305269..5ae91a05 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -3,6 +3,7 @@ """ Business logic for OpenAlex topics. """ + import logging from copy import deepcopy from typing import Any @@ -156,7 +157,13 @@ def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]: meta = normalized.get("meta") if isinstance(meta, dict): - for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + for field in [ + "count", + "db_response_time_ms", + "page", + "per_page", + "groups_count", + ]: meta[field] = _int_or_none(meta.get(field)) meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) @@ -256,6 +263,7 @@ def _datetime_str_or_none(value: Any) -> str | None: return f"{text}T00:00:00Z" return text + # Configuration for vector search similarity thresholds and boosts SIMILARITY_THRESHOLD = 0.62 BOOST_LEXICAL = 1.0 @@ -264,6 +272,7 @@ BOOST_DISPLAY_NAME_VECTOR = 30.0 BOOST_DESCRIPTION_VECTOR = 15.0 BOOST_KEYWORD_VECTORS = 25.0 + async def vector_search_topics( *, query: str, @@ -281,7 +290,7 @@ async def vector_search_topics( logger.exception("Failed to load elasticsearch integration.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, - detail=f"Failed to load elasticsearch integration: {exc}" + detail=f"Failed to load elasticsearch integration: {exc}", ) # 1. Vectorize query @@ -292,7 +301,7 @@ async def vector_search_topics( logger.exception("Failed to encode query text.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, - detail=f"Failed to encode query text: {exc}" + detail=f"Failed to encode query text: {exc}", ) # 2. Query Elasticsearch using standard Bool Should hybrid search @@ -300,81 +309,80 @@ async def vector_search_topics( # Lexical multi_match search (only in hybrid mode) if search_type == "hybrid": - should_clauses.append({ - "multi_match": { - "query": query, - "fields": [ - "display_name^3", - "keywords^2", - "description^1" - ], - "boost": BOOST_LEXICAL + should_clauses.append( + { + "multi_match": { + "query": query, + "fields": ["display_name^3", "keywords^2", "description^1"], + "boost": BOOST_LEXICAL, + } } - }) + ) # Semantic KNN clauses - should_clauses.extend([ - { - "knn": { - "field": "display_name_vector", - "query_vector": query_vector, - "similarity": SIMILARITY_THRESHOLD, - "boost": BOOST_DISPLAY_NAME_VECTOR, - "k": 500, - "num_candidates": 500 - } - }, - { - "knn": { - "field": "description_vector", - "query_vector": query_vector, - "similarity": SIMILARITY_THRESHOLD, - "boost": BOOST_DESCRIPTION_VECTOR, - "k": 500, - "num_candidates": 500 - } - }, - { - "nested": { - "path": "keyword_vectors", - "query": { - "knn": { - "field": "keyword_vectors.vector", - "query_vector": query_vector, - "similarity": SIMILARITY_THRESHOLD, - "k": 500, - "num_candidates": 500 - } - }, - "score_mode": "max", - "boost": BOOST_KEYWORD_VECTORS - } - } - ]) + should_clauses.extend( + [ + { + "knn": { + "field": "display_name_vector", + "query_vector": query_vector, + "similarity": SIMILARITY_THRESHOLD, + "boost": BOOST_DISPLAY_NAME_VECTOR, + "k": 500, + "num_candidates": 500, + } + }, + { + "knn": { + "field": "description_vector", + "query_vector": query_vector, + "similarity": SIMILARITY_THRESHOLD, + "boost": BOOST_DESCRIPTION_VECTOR, + "k": 500, + "num_candidates": 500, + } + }, + { + "nested": { + "path": "keyword_vectors", + "query": { + "knn": { + "field": "keyword_vectors.vector", + "query_vector": query_vector, + "similarity": SIMILARITY_THRESHOLD, + "k": 500, + "num_candidates": 500, + } + }, + "score_mode": "max", + "boost": BOOST_KEYWORD_VECTORS, + } + }, + ] + ) body = { - "query": { - "bool": { - "should": should_clauses - } - }, + "query": {"bool": {"should": should_clauses}}, "_source": { - "excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"] # remove unrequired fields + "excludes": [ + "display_name_vector", + "description_vector", + "keyword_vectors", + "description", + ] # remove unrequired fields }, - "size": limit + "size": limit, } try: raw_results = elasticsearch.search( - index="topicvectors", - body=body, - cluster="nes" + index="topicvectors", body=body, cluster="nes" ) except Exception as exc: logger.exception("Elasticsearch vector search failed.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, - detail=f"Elasticsearch vector search failed: {exc}" + detail=f"Elasticsearch vector search failed: {exc}", ) # 3. Format result @@ -383,14 +391,7 @@ async def vector_search_topics( total = len(hits) results = [hit.get("_source", {}) for hit in hits] - data = { - "meta": { - "count": total, - "page": 1, - "per_page": limit - }, - "results": results - } + data = {"meta": {"count": total, "page": 1, "per_page": limit}, "results": results} try: normalized_data = _normalize_topics_response(data) @@ -401,4 +402,3 @@ async def vector_search_topics( status_code=HTTP_502_BAD_GATEWAY, detail="Vector search response could not be parsed.", ) from exc - diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 0a468ed3..49ac1868 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -4,12 +4,12 @@ README.md api.base.service.ts api.module.ts api/api.ts +api/auth.service.ts api/companyConnections.service.ts api/funding.service.ts api/iNSEAccountService.service.ts api/iNSEService.service.ts api/institutions.service.ts -api/items.service.ts api/news.service.ts api/patents.service.ts api/personNetwork.service.ts @@ -39,7 +39,11 @@ model/autocompleteResponse.ts model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts model/award.ts +model/bodyChangePassword.ts model/bodyCreateUser.ts +model/bodyGetAccessToken.ts +model/bodyLogin.ts +model/bodyRequestOtk.ts model/bundProject.ts model/bundProjectDetails.ts model/bundProjectPage.ts @@ -81,9 +85,6 @@ model/institutionInformation.ts model/institutionNetworkNode.ts model/institutionPage.ts model/institutionsListResponse.ts -model/item.ts -model/itemCreate.ts -model/itemPage.ts model/keywords.ts model/latitude.ts model/location.ts diff --git a/webapp/src/app/api/README.md b/webapp/src/app/api/README.md index 2df9da7b..dfa7b6e7 100644 --- a/webapp/src/app/api/README.md +++ b/webapp/src/app/api/README.md @@ -46,10 +46,10 @@ npm link In your project: ```console -npm link +npm link ``` -**Note for Windows users:** The Angular CLI has troubles to use linked npm packages. +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. Please refer to this issue for a solution / workaround. Published packages are not effected by this issue. @@ -58,22 +58,22 @@ Published packages are not effected by this issue. In your Angular project: ```typescript + import { ApplicationConfig } from '@angular/core'; import { provideHttpClient } from '@angular/common/http'; import { provideApi } from ''; export const appConfig: ApplicationConfig = { - providers: [ - // ... - provideHttpClient(), - provideApi(), - ], + providers: [ + // ... + provideHttpClient(), + provideApi() + ], }; ``` **NOTE** If you're still using `AppModule` and haven't [migrated](https://angular.dev/reference/migrations/standalone) yet, you can still import an Angular module: - ```typescript import { ApiModule } from ''; ``` @@ -86,11 +86,11 @@ import { provideHttpClient } from '@angular/common/http'; import { provideApi } from ''; export const appConfig: ApplicationConfig = { - providers: [ - // ... - provideHttpClient(), - provideApi('http://localhost:9999'), - ], + providers: [ + // ... + provideHttpClient(), + provideApi('http://localhost:9999') + ], }; ``` @@ -101,15 +101,15 @@ import { provideHttpClient } from '@angular/common/http'; import { provideApi } from ''; export const appConfig: ApplicationConfig = { - providers: [ - // ... - provideHttpClient(), - provideApi({ - withCredentials: true, - username: 'user', - password: 'password', - }), - ], + providers: [ + // ... + provideHttpClient(), + provideApi({ + withCredentials: true, + username: 'user', + password: 'password' + }) + ], }; ``` @@ -120,22 +120,21 @@ import { provideHttpClient } from '@angular/common/http'; import { provideApi, Configuration } from ''; export const appConfig: ApplicationConfig = { - providers: [ - // ... - provideHttpClient(), - { - provide: Configuration, - useFactory: (authService: AuthService) => - new Configuration({ - basePath: 'http://localhost:9999', - withCredentials: true, - username: authService.getUsername(), - password: authService.getPassword(), - }), - deps: [AuthService], - multi: false, - }, - ], + providers: [ + // ... + provideHttpClient(), + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration({ + basePath: 'http://localhost:9999', + withCredentials: true, + username: authService.getUsername(), + password: authService.getPassword(), + }), + deps: [AuthService], + multi: false + } + ], }; ``` @@ -152,12 +151,12 @@ import { HttpClientModule } from '@angular/common/http'; import { environment } from '../environments/environment'; export const appConfig: ApplicationConfig = { - providers: [ - // ... - provideHttpClient(), - provideUserApi(environment.basePath), - provideAdminApi(environment.basePath), - ], + providers: [ + // ... + provideHttpClient(), + provideUserApi(environment.basePath), + provideAdminApi(environment.basePath), + ], }; ``` @@ -177,8 +176,8 @@ Example value for use in your Configuration-Provider: ```typescript new Configuration({ - encodeParam: (param: Param) => myFancyParamEncoder(param), -}); + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) ``` [parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations diff --git a/webapp/src/app/api/api.base.service.ts b/webapp/src/app/api/api.base.service.ts index d9ec8f2e..dcf56358 100644 --- a/webapp/src/app/api/api.base.service.ts +++ b/webapp/src/app/api/api.base.service.ts @@ -1,109 +1,83 @@ /** * 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 { - HttpHeaders, - HttpParams, - HttpParameterCodec, -} from '@angular/common/http'; +import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; import { CustomHttpParameterCodec } from './encoder'; import { Configuration } from './configuration'; export class BaseService { - protected basePath = 'http://localhost:8000'; - public defaultHeaders = new HttpHeaders(); - public configuration: Configuration; - public encoder: HttpParameterCodec; + protected basePath = 'http://localhost:8000'; + public defaultHeaders = new HttpHeaders(); + public configuration: Configuration; + public encoder: HttpParameterCodec; - constructor(basePath?: string | string[], configuration?: Configuration) { - this.configuration = configuration || new Configuration(); - if (typeof this.configuration.basePath !== 'string') { - const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; - if (firstBasePath != undefined) { - basePath = firstBasePath; - } + constructor(basePath?: string|string[], configuration?: Configuration) { + this.configuration = configuration || new Configuration(); + if (typeof this.configuration.basePath !== 'string') { + const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; + if (firstBasePath != undefined) { + basePath = firstBasePath; + } - if (typeof basePath !== 'string') { - basePath = this.basePath; - } - this.configuration.basePath = basePath; - } - this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); - } - - protected canConsumeForm(consumes: string[]): boolean { - return consumes.indexOf('multipart/form-data') !== -1; - } - - protected addToHttpParams( - httpParams: HttpParams, - value: any, - key?: string, - isDeep: boolean = false, - ): HttpParams { - // If the value is an object (but not a Date), recursively add its keys. - if (typeof value === 'object' && !(value instanceof Date)) { - return this.addToHttpParamsRecursive( - httpParams, - value, - isDeep ? key : undefined, - isDeep, - ); - } - return this.addToHttpParamsRecursive(httpParams, value, key); - } - - protected addToHttpParamsRecursive( - httpParams: HttpParams, - value?: any, - key?: string, - isDeep: boolean = false, - ): HttpParams { - if (value === null || value === undefined) { - return httpParams; - } - if (typeof value === 'object') { - // If JSON format is preferred, key must be provided. - if (key != null) { - return isDeep - ? Object.keys(value as Record).reduce( - (hp, k) => hp.append(`${key}[${k}]`, value[k]), - httpParams, - ) - : httpParams.append(key, JSON.stringify(value)); - } - // Otherwise, if it's an array, add each element. - if (Array.isArray(value)) { - value.forEach( - (elem) => - (httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)), - ); - } else if (value instanceof Date) { - if (key != null) { - httpParams = httpParams.append(key, value.toISOString()); - } else { - throw Error('key may not be null if value is Date'); + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; } - } else { - Object.keys(value).forEach((k) => { - const paramKey = key ? `${key}.${k}` : k; - httpParams = this.addToHttpParamsRecursive( - httpParams, - value[k], - paramKey, - ); - }); - } - return httpParams; - } else if (key != null) { - return httpParams.append(key, value); + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + protected canConsumeForm(consumes: string[]): boolean { + return consumes.indexOf('multipart/form-data') !== -1; + } + + protected addToHttpParams(httpParams: HttpParams, value: any, key?: string, isDeep: boolean = false): HttpParams { + // If the value is an object (but not a Date), recursively add its keys. + if (typeof value === 'object' && !(value instanceof Date)) { + return this.addToHttpParamsRecursive(httpParams, value, isDeep ? key : undefined, isDeep); + } + return this.addToHttpParamsRecursive(httpParams, value, key); + } + + protected addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string, isDeep: boolean = false): HttpParams { + if (value === null || value === undefined) { + return httpParams; + } + if (typeof value === 'object') { + // If JSON format is preferred, key must be provided. + if (key != null) { + return isDeep + ? Object.keys(value as Record).reduce( + (hp, k) => hp.append(`${key}[${k}]`, value[k]), + httpParams, + ) + : httpParams.append(key, JSON.stringify(value)); + } + // Otherwise, if it's an array, add each element. + if (Array.isArray(value)) { + value.forEach(elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, value.toISOString()); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach(k => { + const paramKey = key ? `${key}.${k}` : k; + httpParams = this.addToHttpParamsRecursive(httpParams, value[k], paramKey); + }); + } + return httpParams; + } else if (key != null) { + return httpParams.append(key, value); + } + throw Error("key may not be null if value is not object or array"); } - throw Error('key may not be null if value is not object or array'); - } } diff --git a/webapp/src/app/api/api.module.ts b/webapp/src/app/api/api.module.ts index e29250f2..58d341fb 100644 --- a/webapp/src/app/api/api.module.ts +++ b/webapp/src/app/api/api.module.ts @@ -1,42 +1,30 @@ -import { - NgModule, - ModuleWithProviders, - SkipSelf, - Optional, -} from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { Configuration } from './configuration'; import { HttpClient } from '@angular/common/http'; + @NgModule({ - imports: [], + imports: [], declarations: [], - exports: [], - providers: [], + exports: [], + providers: [] }) export class ApiModule { - public static forRoot( - configurationFactory: () => Configuration, - ): ModuleWithProviders { - return { - ngModule: ApiModule, - providers: [{ provide: Configuration, useFactory: configurationFactory }], - }; - } + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } - constructor( - @Optional() @SkipSelf() parentModule: ApiModule, - @Optional() http: HttpClient, - ) { - if (parentModule) { - throw new Error( - 'ApiModule is already loaded. Import in your base AppModule only.', - ); + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } } - if (!http) { - throw new Error( - 'You need to import the HttpClientModule in your AppModule! \n' + - 'See also https://github.com/angular/angular/issues/20575', - ); - } - } } diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 7f47efcd..dda89ae3 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -1,3 +1,5 @@ +export * from './auth.service'; +import { AuthService } from './auth.service'; export * from './companyConnections.service'; import { CompanyConnectionsService } from './companyConnections.service'; export * from './funding.service'; @@ -8,8 +10,6 @@ export * from './iNSEService.service'; import { INSEServiceService } from './iNSEService.service'; export * from './institutions.service'; import { InstitutionsService } from './institutions.service'; -export * from './items.service'; -import { ItemsService } from './items.service'; export * from './news.service'; import { NewsService } from './news.service'; export * from './patents.service'; @@ -24,18 +24,4 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [ - CompanyConnectionsService, - FundingService, - INSEAccountServiceService, - INSEServiceService, - InstitutionsService, - ItemsService, - NewsService, - PatentsService, - PersonNetworkService, - PersonsService, - ProjectsService, - TopicsService, - WorksService, -]; +export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts new file mode 100644 index 00000000..24618227 --- /dev/null +++ b/webapp/src/app/api/api/auth.service.ts @@ -0,0 +1,484 @@ +/** + * 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 { 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 { HTTPValidationError } from '../model/hTTPValidationError'; + +// @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 + } + ); + } + + /** + * Get Access Token + * Retrieve an access token for the authenticated user. + * @endpoint post /api/auth/v2/access + * @param authorization + * @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(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<{ [key: string]: string | null; }>; + public getAccessToken(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorization === null || authorization === undefined) { + throw new Error('Required parameter authorization was null or undefined when calling getAccessToken.'); + } + if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) { + throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.'); + } + + let localVarHeaders = this.defaultHeaders; + if (authorization !== undefined && authorization !== null) { + localVarHeaders = localVarHeaders.set('Authorization', String(authorization)); + } + + // 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<{ [key: string]: string | null; }>('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyGetAccessToken, + 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 + } + ); + } + + /** + * 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 + } + ); + } + +} diff --git a/webapp/src/app/api/api/companyConnections.service.ts b/webapp/src/app/api/api/companyConnections.service.ts index 6ad850ea..cbc5f803 100644 --- a/webapp/src/app/api/api/companyConnections.service.ts +++ b/webapp/src/app/api/api/companyConnections.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'; @@ -28,121 +22,74 @@ import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse' import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class CompanyConnectionsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get possible company connections by OpenAlex author ID. - * @endpoint get /api/inse-service/authors/{author_id}/company-connections - * @param authorId - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getCompanyConnectionsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getCompanyConnectionsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getCompanyConnectionsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getCompanyConnectionsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Get possible company connections by OpenAlex author ID. + * @endpoint get /api/inse-service/authors/{author_id}/company-connections + * @param authorId + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getCompanyConnectionsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCompanyConnectionsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/funding.service.ts b/webapp/src/app/api/api/funding.service.ts index f1f0a1a7..46772768 100644 --- a/webapp/src/app/api/api/funding.service.ts +++ b/webapp/src/app/api/api/funding.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse'; @@ -30,246 +24,138 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class FundingService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get funding organizations by author. - * @endpoint get /api/inse-service/authors/{author_id}/funders - * @param authorId - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getFundersByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getFundersByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getFundersByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getFundersByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getFundersByAuthor.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Get funding organizations by author. + * @endpoint get /api/inse-service/authors/{author_id}/funders + * @param authorId + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get funded publications by author. + * @endpoint get /api/inse-service/authors/{author_id}/publications + * @param authorId + * @param page + * @param pageSize + * @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 getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`; + 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 + } + ); } - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/funders`; - 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, - }, - ); - } - - /** - * Get funded publications by author. - * @endpoint get /api/inse-service/authors/{author_id}/publications - * @param authorId - * @param page - * @param pageSize - * @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 getPublicationsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPublicationsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPublicationsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPublicationsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPublicationsByAuthor.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'page_size', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/publications`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/iNSEAccountService.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts index 4874a0a8..90181dbd 100644 --- a/webapp/src/app/api/api/iNSEAccountService.service.ts +++ b/webapp/src/app/api/api/iNSEAccountService.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AccessGrant } from '../model/accessGrant'; @@ -34,424 +28,255 @@ import { IdentityGrant } from '../model/identityGrant'; import { User } from '../model/user'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class INSEAccountServiceService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Create User - * @endpoint post /inse-account/create - * @param bodyCreateUser - * @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 createUser( - bodyCreateUser: BodyCreateUser, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public createUser( - bodyCreateUser: BodyCreateUser, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public createUser( - bodyCreateUser: BodyCreateUser, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public createUser( - bodyCreateUser: BodyCreateUser, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (bodyCreateUser === null || bodyCreateUser === undefined) { - throw new Error( - 'Required parameter bodyCreateUser was null or undefined when calling createUser.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Create User + * @endpoint post /inse-account/create + * @param bodyCreateUser + * @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 createUser(bodyCreateUser: BodyCreateUser, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createUser(bodyCreateUser: BodyCreateUser, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createUser(bodyCreateUser: BodyCreateUser, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createUser(bodyCreateUser: BodyCreateUser, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (bodyCreateUser === null || bodyCreateUser === undefined) { + throw new Error('Required parameter bodyCreateUser was null or undefined when calling createUser.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // 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 = `/inse-account/create`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyCreateUser, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get Access Grant + * @endpoint post /inse-account/auth/access + * @param secret + * @param account + * @param organization + * @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 getAccessGrant(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAccessGrant(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessGrant(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessGrant(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (secret === null || secret === undefined) { + throw new Error('Required parameter secret was null or undefined when calling getAccessGrant.'); + } + if (account === null || account === undefined) { + throw new Error('Required parameter account was null or undefined when calling getAccessGrant.'); + } + if (organization === null || organization === undefined) { + throw new Error('Required parameter organization was null or undefined when calling getAccessGrant.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - // 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, - ); + 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/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (secret !== undefined) { + localVarFormParams = localVarFormParams.append('secret', secret) as any || localVarFormParams; + } + if (account !== undefined) { + localVarFormParams = localVarFormParams.append('account', account) as any || localVarFormParams; + } + if (organization !== undefined) { + localVarFormParams = localVarFormParams.append('organization', organization) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/inse-account/auth/access`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - 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'; - } + /** + * Get Identity Grant + * @endpoint post /inse-account/auth/id + * @param username + * @param password + * @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 getIdentityGrant(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getIdentityGrant(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityGrant(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityGrant(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getIdentityGrant.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling getIdentityGrant.'); + } + + 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/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (username !== undefined) { + localVarFormParams = localVarFormParams.append('username', username) as any || localVarFormParams; + } + if (password !== undefined) { + localVarFormParams = localVarFormParams.append('password', password) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/inse-account/auth/id`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/inse-account/create`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - body: bodyCreateUser, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } - - /** - * Get Access Grant - * @endpoint post /inse-account/auth/access - * @param secret - * @param account - * @param organization - * @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 getAccessGrant( - secret: string, - account: number, - organization: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAccessGrant( - secret: string, - account: number, - organization: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAccessGrant( - secret: string, - account: number, - organization: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAccessGrant( - secret: string, - account: number, - organization: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (secret === null || secret === undefined) { - throw new Error( - 'Required parameter secret was null or undefined when calling getAccessGrant.', - ); - } - if (account === null || account === undefined) { - throw new Error( - 'Required parameter account was null or undefined when calling getAccessGrant.', - ); - } - if (organization === null || organization === undefined) { - throw new Error( - 'Required parameter organization was null or undefined when calling getAccessGrant.', - ); - } - - 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/x-www-form-urlencoded']; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({ encoder: this.encoder }); - } - - if (secret !== undefined) { - localVarFormParams = - (localVarFormParams.append('secret', secret) as any) || - localVarFormParams; - } - if (account !== undefined) { - localVarFormParams = - (localVarFormParams.append('account', account) as any) || - localVarFormParams; - } - if (organization !== undefined) { - localVarFormParams = - (localVarFormParams.append('organization', organization) as any) || - localVarFormParams; - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/inse-account/auth/access`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString - ? localVarFormParams.toString() - : localVarFormParams, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Get Identity Grant - * @endpoint post /inse-account/auth/id - * @param username - * @param password - * @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 getIdentityGrant( - username: string, - password: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getIdentityGrant( - username: string, - password: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getIdentityGrant( - username: string, - password: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getIdentityGrant( - username: string, - password: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (username === null || username === undefined) { - throw new Error( - 'Required parameter username was null or undefined when calling getIdentityGrant.', - ); - } - if (password === null || password === undefined) { - throw new Error( - 'Required parameter password was null or undefined when calling getIdentityGrant.', - ); - } - - 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/x-www-form-urlencoded']; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({ encoder: this.encoder }); - } - - if (username !== undefined) { - localVarFormParams = - (localVarFormParams.append('username', username) as any) || - localVarFormParams; - } - if (password !== undefined) { - localVarFormParams = - (localVarFormParams.append('password', password) as any) || - localVarFormParams; - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/inse-account/auth/id`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString - ? localVarFormParams.toString() - : localVarFormParams, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/iNSEService.service.ts b/webapp/src/app/api/api/iNSEService.service.ts index 8788adee..1149c309 100644 --- a/webapp/src/app/api/api/iNSEService.service.ts +++ b/webapp/src/app/api/api/iNSEService.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,945 +9,205 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; -// @ts-ignore -import { Item } from '../model/item'; -// @ts-ignore -import { ItemCreate } from '../model/itemCreate'; -// @ts-ignore -import { ItemPage } from '../model/itemPage'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class INSEServiceService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Adds a new item. - * @endpoint post /api/inse-service/items - * @param itemCreate - * @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 addItem( - itemCreate: ItemCreate, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public addItem( - itemCreate: ItemCreate, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public addItem( - itemCreate: ItemCreate, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public addItem( - itemCreate: ItemCreate, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (itemCreate === null || itemCreate === undefined) { - throw new Error( - 'Required parameter itemCreate was null or undefined when calling addItem.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - 'Authorization', - localVarHeaders, - 'Bearer ', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - // 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, - ); - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - let localVarPath = `/api/inse-service/items`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - body: itemCreate, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } + 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'; + } + } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - 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, - pageSize, - 'page_size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - saveJson, - 'save_json', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/cache`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public countTopicHierarchy( - topic: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public countTopicHierarchy( - topic: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling countTopicHierarchy.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + let localVarPath = `/api/inse-service/topics/cache`; + 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 + } ); - }); } - let localVarHeaders = this.defaultHeaders; + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/count`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * @endpoint get /api/inse-service/topics/hierarchy + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/hierarchy`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/count`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Deletes the item with the id. - * @endpoint delete /api/inse-service/items/{id} - * @param id The item id. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public deleteItem( - id: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public deleteItem( - id: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public deleteItem( - id: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public deleteItem( - id: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling deleteItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Returns the item with the id. - * @endpoint get /api/inse-service/items/{id} - * @param id The item id. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getItem( - id: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getItem( - id: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItem( - id: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItem( - id: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; - 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, - }); - } - - /** - * Returns a page of items. - * @endpoint get /api/inse-service/items - * @param pageOffset The page offset. - * @param pageSize The page size. - * @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 getItems( - pageOffset?: number, - pageSize?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getItems( - pageOffset?: number, - pageSize?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItems( - pageOffset?: number, - pageSize?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItems( - pageOffset?: number, - pageSize?: number, - 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, - pageOffset, - 'pageOffset', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items`; - 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, - }, - ); - } - - /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). - * @endpoint get /api/inse-service/topics/hierarchy - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getTopicHierarchy( - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicHierarchy( - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - 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/inse-service/topics/hierarchy`; - 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, - }, - ); - } - - /** - * Updates the item with the id. - * @endpoint put /api/inse-service/items/{id} - * @param id The item id. - * @param itemCreate - * @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 updateItem( - id: number, - itemCreate: ItemCreate, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public updateItem( - id: number, - itemCreate: ItemCreate, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public updateItem( - id: number, - itemCreate: ItemCreate, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public updateItem( - id: number, - itemCreate: ItemCreate, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling updateItem.', - ); - } - if (itemCreate === null || itemCreate === undefined) { - throw new Error( - 'Required parameter itemCreate was null or undefined when calling updateItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('put', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - body: itemCreate, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } } diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts index 8b27a539..a4ba3d62 100644 --- a/webapp/src/app/api/api/institutions.service.ts +++ b/webapp/src/app/api/api/institutions.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AutocompleteResponse } from '../model/autocompleteResponse'; @@ -36,727 +30,358 @@ import { InstitutionsListResponse } from '../model/institutionsListResponse'; import { RankingResponse } from '../model/rankingResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class InstitutionsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns institution options for autocomplete inputs. - * @endpoint get /api/inse-service/institutions/autocomplete - * @param query Institution search text, for example \'Duisburg Essen\'. - * @param countryCode Optional ISO country code filter. - * @param type Optional institution type filter. - * @param limit Maximum number of autocomplete options. - * @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 autocompleteInstitutions( - query: string, - countryCode?: string, - type?: string, - limit?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public autocompleteInstitutions( - query: string, - countryCode?: string, - type?: string, - limit?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteInstitutions( - query: string, - countryCode?: string, - type?: string, - limit?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteInstitutions( - query: string, - countryCode?: string, - type?: string, - limit?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling autocompleteInstitutions.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - countryCode, - 'countryCode', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - type, - 'type', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); + /** + * Returns institution options for autocomplete inputs. + * @endpoint get /api/inse-service/institutions/autocomplete + * @param query Institution search text, for example \'Duisburg Essen\'. + * @param countryCode Optional ISO country code filter. + * @param type Optional institution type filter. + * @param limit Maximum number of autocomplete options. + * @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 autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteInstitutions.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + countryCode, 'countryCode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + type, 'type'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/autocomplete`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns a single institution by ID. + * Returns a single institution by its OpenAlex ID. + * @endpoint get /api/inse-service/institutions/{id} + * @param id + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInstitutionById(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionById(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionById(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionById(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getInstitutionById.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); } - let localVarPath = `/api/inse-service/institutions/autocomplete`; - 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, - }, - ); - } + /** + * Returns data for the University Ranking Dashboard. + * @endpoint get /api/inse-service/university-rankings + * @param topic Research topic (e.g., \'Artificial Intelligence\') + * @param metric Metric to rank by + * @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 getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.'); + } - /** - * Returns a single institution by ID. - * Returns a single institution by its OpenAlex ID. - * @endpoint get /api/inse-service/institutions/{id} - * @param id - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getInstitutionById( - id: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getInstitutionById( - id: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getInstitutionById( - id: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getInstitutionById( - id: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getInstitutionById.', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + topic, 'topic'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + metric, 'metric'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/university-rankings`; + 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 + } + ); } - let localVarHeaders = this.defaultHeaders; + /** + * Returns a list of OpenAlex institutions. + * @endpoint get /api/inse-service/institutions + * @param search Full-text search, for example \'Duisburg Essen\'. + * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'country_code\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @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 listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Searches for institutions by name. + * Searches for institutions by name with pagination. + * @endpoint get /api/inse-service/institutions/search + * @param name Institution name to search for, for example \'University of Duisburg Essen\'. + * @param page Page number (0-indexed). + * @param size Number of institutions per page. + * @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'. + * @param sortingDirection Sorting direction, either \'asc\' or \'desc\'. + * @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 searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + name, 'name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortingDirection, 'sorting_direction'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/search`; + 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 + } + ); } - let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Returns data for the University Ranking Dashboard. - * @endpoint get /api/inse-service/university-rankings - * @param topic Research topic (e.g., \'Artificial Intelligence\') - * @param metric Metric to rank by - * @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 getRankingsApiInseServiceUniversityRankingsGet( - topic: - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology', - metric?: 'publications' | 'citations', - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getRankingsApiInseServiceUniversityRankingsGet( - topic: - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology', - metric?: 'publications' | 'citations', - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getRankingsApiInseServiceUniversityRankingsGet( - topic: - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology', - metric?: 'publications' | 'citations', - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getRankingsApiInseServiceUniversityRankingsGet( - topic: - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology', - metric?: 'publications' | 'citations', - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - topic, - 'topic', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - metric, - 'metric', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/university-rankings`; - 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, - }, - ); - } - - /** - * Returns a list of OpenAlex institutions. - * @endpoint get /api/inse-service/institutions - * @param search Full-text search, for example \'Duisburg Essen\'. - * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. - * @param sort Sort field, for example \'works_count:desc\'. - * @param groupBy OpenAlex group_by field, for example \'country_code\'. - * @param perPage Results per page. - * @param page Page number. Use cursor for deep pagination. - * @param cursor Cursor pagination token. Use \'*\' to start. - * @param sample Random sample size. Cannot be combined with sort or page. - * @param select Comma-separated fields to return. - * @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 listInstitutions( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public listInstitutions( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listInstitutions( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listInstitutions( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: 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, - search, - 'search', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filter, - 'filter', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sort, - 'sort', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - groupBy, - 'group_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - perPage, - 'per_page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - cursor, - 'cursor', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sample, - 'sample', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - select, - 'select', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions`; - 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, - }, - ); - } - - /** - * Searches for institutions by name. - * Searches for institutions by name with pagination. - * @endpoint get /api/inse-service/institutions/search - * @param name Institution name to search for, for example \'University of Duisburg Essen\'. - * @param page Page number (0-indexed). - * @param size Number of institutions per page. - * @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'. - * @param sortingDirection Sorting direction, either \'asc\' or \'desc\'. - * @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 searchInstitutionsByName( - name?: string, - page?: number, - size?: number, - sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', - sortingDirection?: 'asc' | 'desc', - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchInstitutionsByName( - name?: string, - page?: number, - size?: number, - sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', - sortingDirection?: 'asc' | 'desc', - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchInstitutionsByName( - name?: string, - page?: number, - size?: number, - sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', - sortingDirection?: 'asc' | 'desc', - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchInstitutionsByName( - name?: string, - page?: number, - size?: number, - sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', - sortingDirection?: 'asc' | 'desc', - 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, - name, - 'name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sort_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortingDirection, - 'sorting_direction', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions/search`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/items.service.ts b/webapp/src/app/api/api/items.service.ts deleted file mode 100644 index bc3c2293..00000000 --- a/webapp/src/app/api/api/items.service.ts +++ /dev/null @@ -1,634 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -/* tslint:disable:no-unused-variable member-ordering */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; - -// @ts-ignore -import { HTTPValidationError } from '../model/hTTPValidationError'; -// @ts-ignore -import { Item } from '../model/item'; -// @ts-ignore -import { ItemCreate } from '../model/itemCreate'; -// @ts-ignore -import { ItemPage } from '../model/itemPage'; - -// @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; -import { BaseService } from '../api.base.service'; - -@Injectable({ - providedIn: 'root', -}) -export class ItemsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - - /** - * Adds a new item. - * @endpoint post /api/inse-service/items - * @param itemCreate - * @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 addItem( - itemCreate: ItemCreate, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public addItem( - itemCreate: ItemCreate, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public addItem( - itemCreate: ItemCreate, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public addItem( - itemCreate: ItemCreate, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (itemCreate === null || itemCreate === undefined) { - throw new Error( - 'Required parameter itemCreate was null or undefined when calling addItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - body: itemCreate, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } - - /** - * Deletes the item with the id. - * @endpoint delete /api/inse-service/items/{id} - * @param id The item id. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public deleteItem( - id: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public deleteItem( - id: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public deleteItem( - id: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public deleteItem( - id: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling deleteItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Returns the item with the id. - * @endpoint get /api/inse-service/items/{id} - * @param id The item id. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getItem( - id: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getItem( - id: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItem( - id: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItem( - id: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; - 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, - }); - } - - /** - * Returns a page of items. - * @endpoint get /api/inse-service/items - * @param pageOffset The page offset. - * @param pageSize The page size. - * @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 getItems( - pageOffset?: number, - pageSize?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getItems( - pageOffset?: number, - pageSize?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItems( - pageOffset?: number, - pageSize?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getItems( - pageOffset?: number, - pageSize?: number, - 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, - pageOffset, - 'pageOffset', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items`; - 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, - }, - ); - } - - /** - * Updates the item with the id. - * @endpoint put /api/inse-service/items/{id} - * @param id The item id. - * @param itemCreate - * @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 updateItem( - id: number, - itemCreate: ItemCreate, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public updateItem( - id: number, - itemCreate: ItemCreate, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public updateItem( - id: number, - itemCreate: ItemCreate, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public updateItem( - id: number, - itemCreate: ItemCreate, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling updateItem.', - ); - } - if (itemCreate === null || itemCreate === undefined) { - throw new Error( - 'Required parameter itemCreate was null or undefined when calling updateItem.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('put', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - body: itemCreate, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } -} diff --git a/webapp/src/app/api/api/news.service.ts b/webapp/src/app/api/api/news.service.ts index de08c0d1..ad6a9f4b 100644 --- a/webapp/src/app/api/api/news.service.ts +++ b/webapp/src/app/api/api/news.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -30,1031 +24,531 @@ import { NewsArticleDetail } from '../model/newsArticleDetail'; import { NewsPage } from '../model/newsPage'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class NewsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns news articles in which the given person is mentioned. - * @endpoint get /api/news/by-author - * @param authorId OpenAlex author id, e.g. A5034365278. - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param query Optional search term, matched against title/author. - * @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 getNewsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getNewsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsByAuthor( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getNewsByAuthor.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorId, - 'authorId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortOrder, - 'sortOrder', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); + /** + * Returns news articles in which the given person is mentioned. + * @endpoint get /api/news/by-author + * @param authorId OpenAlex author id, e.g. A5034365278. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param query Optional search term, matched against title/author. + * @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 getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorId, 'authorId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sortOrder'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/by-author`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns news articles in which the given person is mentioned. + * @endpoint get /api/news/by-author + * @param authorId OpenAlex author id, e.g. A5034365278. + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @param query Optional search term, matched against title/author. + * @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 getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor_1.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorId, 'authorId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sortOrder'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/by-author`; + 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 + } + ); } - let localVarPath = `/api/news/by-author`; - 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, - }, - ); - } + /** + * Returns a single news article including its full content. + * @endpoint get /api/news/{news_id} + * @param newsId The unique id of the news article (Elasticsearch _id). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getNewsById(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getNewsById(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsById(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsById(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (newsId === null || newsId === undefined) { + throw new Error('Required parameter newsId was null or undefined when calling getNewsById.'); + } - /** - * Returns news articles in which the given person is mentioned. - * @endpoint get /api/news/by-author - * @param authorId OpenAlex author id, e.g. A5034365278. - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @param query Optional search term, matched against title/author. - * @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 getNewsByAuthor_1( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getNewsByAuthor_1( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsByAuthor_1( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsByAuthor_1( - authorId: string, - page?: number, - pageSize?: number, - sortOrder?: string, - query?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getNewsByAuthor_1.', - ); + 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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorId, - 'authorId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortOrder, - 'sortOrder', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); + /** + * Returns a single news article including its full content. + * @endpoint get /api/news/{news_id} + * @param newsId The unique id of the news article (Elasticsearch _id). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getNewsById_2(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getNewsById_2(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsById_2(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getNewsById_2(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (newsId === null || newsId === undefined) { + throw new Error('Required parameter newsId was null or undefined when calling getNewsById_2.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + 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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns a page of news articles, newest first. + * @endpoint get /api/news + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @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 listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listNews(page?: number, pageSize?: number, sortOrder?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sortOrder'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news`; + 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 + } + ); } - let localVarPath = `/api/news/by-author`; - 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, - }, - ); - } + /** + * Returns a page of news articles, newest first. + * @endpoint get /api/news + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). + * @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 listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - /** - * Returns a single news article including its full content. - * @endpoint get /api/news/{news_id} - * @param newsId The unique id of the news article (Elasticsearch _id). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getNewsById( - newsId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getNewsById( - newsId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsById( - newsId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsById( - newsId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (newsId === null || newsId === undefined) { - throw new Error( - 'Required parameter newsId was null or undefined when calling getNewsById.', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sortOrder'); + + 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/news`; + 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 + } + ); } - let localVarHeaders = this.defaultHeaders; + /** + * Searches news articles by full text (full_content). + * @endpoint get /api/news/search + * @param query Search term, matched against the full text (full_content). + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @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 searchNews(query: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchNews(query: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchNews(query: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchNews(query: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling searchNews.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + + 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/news/search`; + 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 + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Searches news articles by full text (full_content). + * @endpoint get /api/news/search + * @param query Search term, matched against the full text (full_content). + * @param page Page number (1-based). + * @param pageSize Articles per page. + * @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 searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchNews_4(query: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling searchNews_4.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/news/search`; + 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 + } + ); } - let localVarPath = `/api/news/${this.configuration.encodeParam({ name: 'newsId', value: newsId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Returns a single news article including its full content. - * @endpoint get /api/news/{news_id} - * @param newsId The unique id of the news article (Elasticsearch _id). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getNewsById_2( - newsId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getNewsById_2( - newsId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsById_2( - newsId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getNewsById_2( - newsId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (newsId === null || newsId === undefined) { - throw new Error( - 'Required parameter newsId was null or undefined when calling getNewsById_2.', - ); - } - - 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/news/${this.configuration.encodeParam({ name: 'newsId', value: newsId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Returns a page of news articles, newest first. - * @endpoint get /api/news - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @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 listNews( - page?: number, - pageSize?: number, - sortOrder?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public listNews( - page?: number, - pageSize?: number, - sortOrder?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listNews( - page?: number, - pageSize?: number, - sortOrder?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listNews( - page?: number, - pageSize?: number, - sortOrder?: 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, - 'pageSize', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortOrder, - 'sortOrder', - ); - - 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/news`; - 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, - }, - ); - } - - /** - * Returns a page of news articles, newest first. - * @endpoint get /api/news - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first). - * @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 listNews_3( - page?: number, - pageSize?: number, - sortOrder?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public listNews_3( - page?: number, - pageSize?: number, - sortOrder?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listNews_3( - page?: number, - pageSize?: number, - sortOrder?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listNews_3( - page?: number, - pageSize?: number, - sortOrder?: 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, - 'pageSize', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortOrder, - 'sortOrder', - ); - - 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/news`; - 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, - }, - ); - } - - /** - * Searches news articles by full text (full_content). - * @endpoint get /api/news/search - * @param query Search term, matched against the full text (full_content). - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @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 searchNews( - query: string, - page?: number, - pageSize?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchNews( - query: string, - page?: number, - pageSize?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchNews( - query: string, - page?: number, - pageSize?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchNews( - query: string, - page?: number, - pageSize?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling searchNews.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - - 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/news/search`; - 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, - }, - ); - } - - /** - * Searches news articles by full text (full_content). - * @endpoint get /api/news/search - * @param query Search term, matched against the full text (full_content). - * @param page Page number (1-based). - * @param pageSize Articles per page. - * @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 searchNews_4( - query: string, - page?: number, - pageSize?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchNews_4( - query: string, - page?: number, - pageSize?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchNews_4( - query: string, - page?: number, - pageSize?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchNews_4( - query: string, - page?: number, - pageSize?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling searchNews_4.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - - 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/news/search`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index d8715dc1..de6ea981 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -28,121 +22,74 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class PatentsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get patents matched to an author by name. - * @endpoint get /api/inse-service/authors/{author_id}/patents - * @param authorId - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getPatentsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPatentsByAuthor.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Get patents matched to an author by name. + * @endpoint get /api/inse-service/authors/{author_id}/patents + * @param authorId + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/personNetwork.service.ts b/webapp/src/app/api/api/personNetwork.service.ts index 5b468938..b1183ff6 100644 --- a/webapp/src/app/api/api/personNetwork.service.ts +++ b/webapp/src/app/api/api/personNetwork.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { CollaborationNetwork } from '../model/collaborationNetwork'; @@ -30,139 +24,86 @@ import { FilterProperties } from '../model/filterProperties'; import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class PersonNetworkService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get a person\'s collaboration network. - * Returns a person\'s collaboration network based on their works and co-authors. - * @endpoint post /api/person/network/{raw_user_id} - * @param rawUserId The raw user ID of the person. - * @param filterProperties - * @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 getCollaborationNetwork( - rawUserId: string, - filterProperties?: FilterProperties, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getCollaborationNetwork( - rawUserId: string, - filterProperties?: FilterProperties, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getCollaborationNetwork( - rawUserId: string, - filterProperties?: FilterProperties, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getCollaborationNetwork( - rawUserId: string, - filterProperties?: FilterProperties, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (rawUserId === null || rawUserId === undefined) { - throw new Error( - 'Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Get a person\'s collaboration network. + * Returns a person\'s collaboration network based on their works and co-authors. + * @endpoint post /api/person/network/{raw_user_id} + * @param rawUserId The raw user ID of the person. + * @param filterProperties + * @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 getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawUserId === null || rawUserId === undefined) { + throw new Error('Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // 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/person/network/${this.configuration.encodeParam({name: "rawUserId", value: rawUserId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: filterProperties, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - 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/person/network/${this.configuration.encodeParam({ name: 'rawUserId', value: rawUserId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: filterProperties, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index cef36fc4..03222a4c 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AuthorsListResponse } from '../model/authorsListResponse'; @@ -32,1739 +26,869 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { PersonBio } from '../model/personBio'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class PersonsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Generates a bio for a person by author ID. - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - * @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 generatePersonBio( - authorId: string, - include?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public generatePersonBio( - authorId: string, - include?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public generatePersonBio( - authorId: string, - include?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public generatePersonBio( - authorId: string, - include?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling generatePersonBio.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorId, - 'author_id', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/bio`; - 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, - }, - ); - } - - /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 getPersonByID( - id: string, - include?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPersonByID( - id: string, - include?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPersonByID( - id: string, - include?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPersonByID( - id: string, - include?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getPersonByID.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 getPersonByID_1( - id: string, - include?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPersonByID_1( - id: string, - include?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPersonByID_1( - id: string, - include?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPersonByID_1( - id: string, - include?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getPersonByID_1.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Searches for persons by ID or name. - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - * @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 searchPersons( - authorId?: string, - query?: string, - include?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersons( - authorId?: string, - query?: string, - include?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersons( - authorId?: string, - query?: string, - include?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersons( - authorId?: string, - query?: string, - include?: 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, - authorId, - 'author_id', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/search`; - 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, - }, - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsAutocomplete( - authorName: string, - include: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsAutocomplete( - authorName: string, - include: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsAutocomplete( - authorName: string, - include: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsAutocomplete( - authorName: string, - include: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorName === null || authorName === undefined) { - throw new Error( - 'Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.', - ); - } - if (include === null || include === undefined) { - throw new Error( - 'Required parameter include was null or undefined when calling searchPersonsAutocomplete.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorName, - 'author_name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/autocomplete`; - 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, - }, - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsAutocomplete_2( - authorName: string, - include: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsAutocomplete_2( - authorName: string, - include: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsAutocomplete_2( - authorName: string, - include: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsAutocomplete_2( - authorName: string, - include: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorName === null || authorName === undefined) { - throw new Error( - 'Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.', - ); - } - if (include === null || include === undefined) { - throw new Error( - 'Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorName, - 'author_name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/autocomplete`; - 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, - }, - ); - } - - /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByInstitution( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsByInstitution( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByInstitution( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByInstitution( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error( - 'Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.', - ); - } - if (include === null || include === undefined) { - throw new Error( - 'Required parameter include was null or undefined when calling searchPersonsByInstitution.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - institutionName, - 'institution_name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageOffset, - 'page_offset', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByInstitution`; - 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, - }, - ); - } - - /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByInstitution_3( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsByInstitution_3( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByInstitution_3( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByInstitution_3( - institutionName: string, - include: string, - limit?: number, - pageOffset?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error( - 'Required parameter institutionName was null or undefined when calling searchPersonsByInstitution_3.', - ); - } - if (include === null || include === undefined) { - throw new Error( - 'Required parameter include was null or undefined when calling searchPersonsByInstitution_3.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - institutionName, - 'institution_name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageOffset, - 'page_offset', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByInstitution`; - 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, - }, - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByName( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsByName( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByName( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByName( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorName === null || authorName === undefined) { - throw new Error( - 'Required parameter authorName was null or undefined when calling searchPersonsByName.', - ); - } - if (include === null || include === undefined) { - throw new Error( - 'Required parameter include was null or undefined when calling searchPersonsByName.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorName, - 'author_name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageOffset, - 'page_offset', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByName`; - 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, - }, - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByName_4( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsByName_4( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByName_4( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsByName_4( - authorName: string, - include: string, - limit?: number, - pageOffset?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorName === null || authorName === undefined) { - throw new Error( - 'Required parameter authorName was null or undefined when calling searchPersonsByName_4.', - ); - } - if (include === null || include === undefined) { - throw new Error( - 'Required parameter include was null or undefined when calling searchPersonsByName_4.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorName, - 'author_name', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageOffset, - 'page_offset', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/searchByName`; - 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, - }, - ); - } - - /** - * Searches for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param sortBy Value to sort by - * @param sortOrder asc or desc? - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @param filterMode Filter mode: \'in\' or \'from\' - * @param filterYear Filter year - * @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 searchPersonsList( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsList( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsList( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsList( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - 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, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - institutionName, - 'institutionName', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sortBy', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortOrder, - 'sortOrder', - ); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + /** + * Generates a bio for a person by author ID. + * @endpoint get /api/inse-service/persons/bio + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Comma-separated list to include tags + * @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 generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public generatePersonBio(authorId: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling generatePersonBio.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorId, 'author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/bio`; + 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 + } ); - }); - } - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - strict, - 'strict', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filterMode, - 'filterMode', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filterYear, - 'filterYear', - ); - - 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(); + /** + * Searches for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPersonByID(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getPersonByID.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + let localVarHeaders = this.defaultHeaders; - let localVarPath = `/api/inse-service/persons/search-list`; - 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, - }, - ); - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - /** - * Searches for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param sortBy Value to sort by - * @param sortOrder asc or desc? - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @param filterMode Filter mode: \'in\' or \'from\' - * @param filterYear Filter year - * @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 searchPersonsList_5( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchPersonsList_5( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsList_5( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchPersonsList_5( - query?: string, - institutionName?: string, - sortBy?: string, - sortOrder?: string, - topic?: Array, - page?: number, - pageSize?: number, - include?: string, - strict?: boolean, - filterMode?: string, - filterYear?: number, - 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, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - institutionName, - 'institutionName', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sortBy', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortOrder, - 'sortOrder', - ); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } ); - }); - } - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'pageSize', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - strict, - 'strict', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filterMode, - 'filterMode', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filterYear, - 'filterYear', - ); - - 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(); + /** + * Searches for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID_1(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPersonByID_1(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID_1(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID_1(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getPersonByID_1.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); + } + + /** + * Searches for persons by ID or name. + * @endpoint get /api/inse-service/persons/search + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param query Search query (e.g., Arman AND Arzani) + * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost + * @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 searchPersons(authorId?: string, query?: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersons(authorId?: string, query?: string, include?: 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, + authorId, 'author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/search`; + 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 + } + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/autocomplete`; + 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 + } + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/autocomplete`; + 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 + } + ); + } + + /** + * Searches for persons by institution name. + * @endpoint get /api/inse-service/persons/searchByInstitution + * @param institutionName Institution name (e.g., MIT, Oxford University) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (institutionName === null || institutionName === undefined) { + throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institution_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/searchByInstitution`; + 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 + } + ); + } + + /** + * Searches for persons by institution name. + * @endpoint get /api/inse-service/persons/searchByInstitution + * @param institutionName Institution name (e.g., MIT, Oxford University) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (institutionName === null || institutionName === undefined) { + throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution_3.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution_3.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institution_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/searchByInstitution`; + 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 + } + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByName.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/searchByName`; + 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 + } + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName_4.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByName_4.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/searchByName`; + 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 + } + ); + } + + /** + * Searches for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionName Filter by institution name + * @param sortBy Value to sort by + * @param sortOrder asc or desc? + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param strict Strict institution search by target year + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, 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, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institutionName'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sortBy'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sortOrder'); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + strict, 'strict'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterMode, 'filterMode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterYear, 'filterYear'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/search-list`; + 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 + } + ); + } + + /** + * Searches for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionName Filter by institution name + * @param sortBy Value to sort by + * @param sortOrder asc or desc? + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param strict Strict institution search by target year + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, 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, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institutionName'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sortBy'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sortOrder'); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + strict, 'strict'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterMode, 'filterMode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterYear, 'filterYear'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/persons/search-list`; + 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 + } + ); } - let localVarPath = `/api/inse-service/persons/search-list`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 35cdba8a..9edfb7fe 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { BundProjectDetails } from '../model/bundProjectDetails'; @@ -50,1106 +44,594 @@ import { ProjectsSortBy } from '../model/projectsSortBy'; import { SortDirection } from '../model/sortDirection'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class ProjectsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get DFG projects. - * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/person/dfg/search - * @param authorId The author ID to filter by. - * @param topic The topic to filter by. - * @param page The page number. - * @param size The page size. - * @param sortBy The field to sort by. - * @param sortDirection The sort direction (asc or desc). - * @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 getDfgProjects( - authorId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getDfgProjects( - authorId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getDfgProjects( - authorId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getDfgProjects( - authorId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getDfgProjects.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - authorId, - 'author_id', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - topic, - 'topic', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sort_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortDirection, - 'sort_direction', - ); + /** + * Get DFG projects. + * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. + * @endpoint get /api/projects/person/dfg/search + * @param authorId The author ID to filter by. + * @param topic The topic to filter by. + * @param page The page number. + * @param size The page size. + * @param sortBy The field to sort by. + * @param sortDirection The sort direction (asc or desc). + * @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 getDfgProjects(authorId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getDfgProjects(authorId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(authorId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(authorId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getDfgProjects.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorId, 'author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + topic, 'topic'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortDirection, 'sort_direction'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarPath = `/api/projects/person/dfg/search`; - 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, - }, - ); - } - /** - * Get EU projects for an author. - * Returns a list of EU projects associated with the specified author ID. - * @endpoint get /api/projects/author/{raw_oa_author_id}/eu - * @param rawOaAuthorId The author ID to filter by. - * @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 getEuProjectsForAuthor( - rawOaAuthorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getEuProjectsForAuthor( - rawOaAuthorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getEuProjectsForAuthor( - rawOaAuthorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getEuProjectsForAuthor( - rawOaAuthorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (rawOaAuthorId === null || rawOaAuthorId === undefined) { - throw new Error( - 'Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.', - ); - } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/projects/author/${this.configuration.encodeParam({ name: 'rawOaAuthorId', value: rawOaAuthorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/eu`; - 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, - }, - ); - } - - /** - * Get funding over time for bund projects. - * Returns the funding over time for bund projects associated with the specified institution. - * @endpoint get /api/projects/institution/bund/funding-over-time - * @param rawOaInstitutionId The institution ID to filter by. - * @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 getInstitutionBundProjectsFundingOverTime( - rawOaInstitutionId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getInstitutionBundProjectsFundingOverTime( - rawOaInstitutionId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getInstitutionBundProjectsFundingOverTime( - rawOaInstitutionId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getInstitutionBundProjectsFundingOverTime( - rawOaInstitutionId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { - throw new Error( - 'Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - rawOaInstitutionId, - 'raw_oa_institution_id', - ); - - 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/projects/institution/bund/funding-over-time`; - 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, - }, - ); - } - - /** - * Get funding over time for EU projects. - * Returns the funding over time for EU projects associated with the specified institution. - * @endpoint get /api/projects/institution/eu/funding-over-time - * @param rawOaInstitutionId The institution ID to filter by. - * @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 getInstitutionCordisEuProjectsFundingOverTime( - rawOaInstitutionId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getInstitutionCordisEuProjectsFundingOverTime( - rawOaInstitutionId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getInstitutionCordisEuProjectsFundingOverTime( - rawOaInstitutionId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getInstitutionCordisEuProjectsFundingOverTime( - rawOaInstitutionId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { - throw new Error( - 'Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionCordisEuProjectsFundingOverTime.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - rawOaInstitutionId, - 'raw_oa_institution_id', - ); - - 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/projects/institution/eu/funding-over-time`; - 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, - }, - ); - } - - /** - * Get a single BUND project. - * Returns a single BUND project based on its ID. - * @endpoint get /api/projects/bund/{id} - * @param id The ID of the BUND project to retrieve. - * @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 getSingleBundProject( - id: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getSingleBundProject( - id: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getSingleBundProject( - id: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getSingleBundProject( - id: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getSingleBundProject.', - ); - } - - 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/projects/bund/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Get a single DFG project. - * Returns a single DFG project based on its ID. - * @endpoint get /api/projects/dfg/{id} - * @param id The ID of the DFG project to retrieve. - * @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 getSingleDfgProject( - id: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getSingleDfgProject( - id: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getSingleDfgProject( - id: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getSingleDfgProject( - id: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getSingleDfgProject.', - ); - } - - 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/projects/dfg/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Get bund projects. - * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. - * @endpoint post /api/projects/institution/bund/search - * @param projectsFilteringProperties - * @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 searchBundProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchBundProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchBundProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchBundProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if ( - projectsFilteringProperties === null || - projectsFilteringProperties === undefined - ) { - throw new Error( - 'Required parameter projectsFilteringProperties was null or undefined when calling searchBundProjects.', - ); - } - - 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/projects/institution/bund/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: projectsFilteringProperties, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Get EU projects. - * Returns a page of EU projects based on the provided pagination parameters and optional institution filter. - * @endpoint post /api/projects/institution/eu/search - * @param projectsFilteringProperties - * @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 searchCordisEuProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchCordisEuProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchCordisEuProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchCordisEuProjects( - projectsFilteringProperties: ProjectsFilteringProperties, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if ( - projectsFilteringProperties === null || - projectsFilteringProperties === undefined - ) { - throw new Error( - 'Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.', - ); - } - - 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/projects/institution/eu/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: projectsFilteringProperties, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Search projects across all funders. - * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/search - * @param page The page number. - * @param size The page size. - * @param selectedProjectTypes The set of project types to filter by (e.g., \'bund\', \'eu\', \'dfg\'). If not provided, projects of all types will be included. - * @param title The title to filter by. - * @param sortBy The field to sort by. - * @param sortDirection The sort direction (asc or desc). - * @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 searchProjects( - page?: number, - size?: number, - selectedProjectTypes?: Set, - title?: string, - sortBy?: ProjectsSortBy, - sortDirection?: SortDirection, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public searchProjects( - page?: number, - size?: number, - selectedProjectTypes?: Set, - title?: string, - sortBy?: ProjectsSortBy, - sortDirection?: SortDirection, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchProjects( - page?: number, - size?: number, - selectedProjectTypes?: Set, - title?: string, - sortBy?: ProjectsSortBy, - sortDirection?: SortDirection, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public searchProjects( - page?: number, - size?: number, - selectedProjectTypes?: Set, - title?: string, - sortBy?: ProjectsSortBy, - sortDirection?: SortDirection, - 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, - size, - 'size', - ); - if (selectedProjectTypes) { - selectedProjectTypes.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'selected_project_types', + let localVarPath = `/api/projects/person/dfg/search`; + 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 + } ); - }); - } - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - title, - 'title', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sort_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortDirection, - 'sort_direction', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get EU projects for an author. + * Returns a list of EU projects associated with the specified author ID. + * @endpoint get /api/projects/author/{raw_oa_author_id}/eu + * @param rawOaAuthorId The author ID to filter by. + * @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 getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaAuthorId === null || rawOaAuthorId === undefined) { + throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/eu`; + 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 + } + ); + } + + /** + * Get funding over time for bund projects. + * Returns the funding over time for bund projects associated with the specified institution. + * @endpoint get /api/projects/institution/bund/funding-over-time + * @param rawOaInstitutionId The institution ID to filter by. + * @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 getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { + throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); + + 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/projects/institution/bund/funding-over-time`; + 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 + } + ); + } + + /** + * Get funding over time for EU projects. + * Returns the funding over time for EU projects associated with the specified institution. + * @endpoint get /api/projects/institution/eu/funding-over-time + * @param rawOaInstitutionId The institution ID to filter by. + * @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 getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { + throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionCordisEuProjectsFundingOverTime.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); + + 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/projects/institution/eu/funding-over-time`; + 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 + } + ); + } + + /** + * Get a single BUND project. + * Returns a single BUND project based on its ID. + * @endpoint get /api/projects/bund/{id} + * @param id The ID of the BUND project to retrieve. + * @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 getSingleBundProject(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getSingleBundProject(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getSingleBundProject(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getSingleBundProject(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getSingleBundProject.'); + } + + 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/projects/bund/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); + } + + /** + * Get a single DFG project. + * Returns a single DFG project based on its ID. + * @endpoint get /api/projects/dfg/{id} + * @param id The ID of the DFG project to retrieve. + * @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 getSingleDfgProject(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getSingleDfgProject(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getSingleDfgProject(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getSingleDfgProject(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getSingleDfgProject.'); + } + + 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/projects/dfg/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); + } + + /** + * Get bund projects. + * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. + * @endpoint post /api/projects/institution/bund/search + * @param projectsFilteringProperties + * @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 searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) { + throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchBundProjects.'); + } + + 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/projects/institution/bund/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: projectsFilteringProperties, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Get EU projects. + * Returns a page of EU projects based on the provided pagination parameters and optional institution filter. + * @endpoint post /api/projects/institution/eu/search + * @param projectsFilteringProperties + * @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 searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) { + throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.'); + } + + 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/projects/institution/eu/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: projectsFilteringProperties, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Search projects across all funders. + * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. + * @endpoint get /api/projects/search + * @param page The page number. + * @param size The page size. + * @param selectedProjectTypes The set of project types to filter by (e.g., \'bund\', \'eu\', \'dfg\'). If not provided, projects of all types will be included. + * @param title The title to filter by. + * @param sortBy The field to sort by. + * @param sortDirection The sort direction (asc or desc). + * @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 searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, 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, + size, 'size'); + if (selectedProjectTypes) { + selectedProjectTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'selected_project_types'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortDirection, 'sort_direction'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + 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/projects/search`; + 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 + } + ); } - let localVarPath = `/api/projects/search`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 2b90f737..6f17a01e 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AutocompleteResponse } from '../model/autocompleteResponse'; @@ -30,803 +24,413 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class TopicsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns topic options for autocomplete inputs. - * @endpoint get /api/topics/autocomplete - * @param query Topic search text, for example \'machine learning\'. - * @param domainId Optional OpenAlex domain id filter. - * @param fieldId Optional OpenAlex field id filter. - * @param subfieldId Optional OpenAlex subfield id filter. - * @param limit Maximum number of autocomplete options. - * @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 autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling autocompleteTopics.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - domainId, - 'domainId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - fieldId, - 'fieldId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - subfieldId, - 'subfieldId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); + /** + * Returns topic options for autocomplete inputs. + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + * @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 autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteTopics.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + domainId, 'domainId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fieldId, 'fieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + subfieldId, 'subfieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarPath = `/api/topics/autocomplete`; - 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, - }, - ); - } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - 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, - pageSize, - 'page_size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - saveJson, - 'save_json', - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/cache`; - 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, - }, - ); - } - - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public countTopicHierarchy( - topic: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public countTopicHierarchy( - topic: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling countTopicHierarchy.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + let localVarPath = `/api/topics/autocomplete`; + 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 + } ); - }); } - let localVarHeaders = this.defaultHeaders; + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/cache`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/count`; + 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 + } + ); } - let localVarPath = `/api/inse-service/topics/count`; - 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, - }, - ); - } + /** + * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * @endpoint get /api/inse-service/topics/hierarchy + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). - * @endpoint get /api/inse-service/topics/hierarchy - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getTopicHierarchy( - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicHierarchy( - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/hierarchy`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns a list of OpenAlex topics. + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @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 listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics`; + 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 + } + ); } - let localVarPath = `/api/inse-service/topics/hierarchy`; - 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, - }, - ); - } + /** + * Semantic / vector search for topics using a keyword/sentence. + * @endpoint get /api/topics/vector-search + * @param query Word or sentence to search by similarity. + * @param limit Maximum number of topics to return. + * @param searchType Search approach: \'hybrid\' or \'semantic\'. + * @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 vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling vectorSearchTopics.'); + } - /** - * Returns a list of OpenAlex topics. - * @endpoint get /api/topics - * @param search Full-text search, for example \'machine learning\'. - * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. - * @param sort Sort field, for example \'works_count:desc\'. - * @param groupBy OpenAlex group_by field, for example \'domain.id\'. - * @param perPage Results per page. - * @param page Page number. Use cursor for deep pagination. - * @param cursor Cursor pagination token. Use \'*\' to start. - * @param sample Random sample size. Cannot be combined with sort or page. - * @param select Comma-separated fields to return. - * @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 listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: 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, - search, - 'search', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filter, - 'filter', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sort, - 'sort', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - groupBy, - 'group_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - perPage, - 'per_page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - cursor, - 'cursor', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sample, - 'sample', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - select, - 'select', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + searchType, 'searchType'); - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + 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/topics/vector-search`; + 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 + } + ); } - 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/topics`; - 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, - }, - ); - } - - /** - * Semantic / vector search for topics using a keyword/sentence. - * @endpoint get /api/topics/vector-search - * @param query Word or sentence to search by similarity. - * @param limit Maximum number of topics to return. - * @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 vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling vectorSearchTopics.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - if (searchType !== undefined && searchType !== null) { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'searchType', - ); - } - - 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/topics/vector-search`; - 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, - }, - ); - } } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 20d855a3..5fcf6311 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -36,691 +30,350 @@ import { WorkPage } from '../model/workPage'; import { WorksListResponse } from '../model/worksListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class WorksService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns all works for an author. - * @endpoint get /api/works/{author_id}/all - * @param authorId The author id, for example A5023888391. - * @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 getAllAuthorWorks( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAllAuthorWorks( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllAuthorWorks( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllAuthorWorks( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getAllAuthorWorks.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Returns all works for an author. + * @endpoint get /api/works/{author_id}/all + * @param authorId The author id, for example A5023888391. + * @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 getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getAllAuthorWorks.'); + } - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - 'Authorization', - localVarHeaders, - 'Bearer ', - ); + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + 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 localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - const localVarTransferCache: boolean = options?.transferCache ?? true; + 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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/all`; - 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, - }, - ); - } + 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'; + } + } - /** - * Returns a page of works for an author. - * @endpoint get /api/works/{author_id} - * @param authorId The author id, for example A5023888391. - * @param page The page number. - * @param size The page size. - * @param publicationYear Filter by publication year. Can be repeated. - * @param type Filter by publication type. Can be repeated. - * @param language Filter by language code. Can be repeated. - * @param institutionId Filter by OpenAlex institution id. Can be repeated. - * @param topicId Filter by OpenAlex topic id. Can be repeated. - * @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 getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getAuthorWorks.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - if (publicationYear) { - publicationYear.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'publication_year', + let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/all`; + 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 + } ); - }); } - if (type) { - type.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'type', + + /** + * Returns a page of works for an author. + * @endpoint get /api/works/{author_id} + * @param authorId The author id, for example A5023888391. + * @param page The page number. + * @param size The page size. + * @param publicationYear Filter by publication year. Can be repeated. + * @param type Filter by publication type. Can be repeated. + * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. + * @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + if (publicationYear) { + publicationYear.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_year'); + }) + } + if (type) { + type.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'type'); + }) + } + if (language) { + language.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'language'); + }) + } + if (institutionId) { + institutionId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_id'); + }) + } + if (topicId) { + topicId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_id'); + }) + } + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } ); - }); } - if (language) { - language.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'language', + + /** + * Returns work counts per primary topic for an author. + * @endpoint get /api/works/{author_id}/primary-topic-counts + * @param authorId The author id, for example A5023888391. + * @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 getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.'); + } + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-topic-counts`; + 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 + } ); - }); } - if (institutionId) { - institutionId.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'institution_id', + + /** + * Returns topics grouped by publication year for an author. + * @endpoint get /api/works/{author_id}/topics-by-time + * @param authorId The author id, for example A5023888391. + * @param maxTopicsPerYear The maximum number of topics per year. + * @param targetPublications Target number of publications used for the timeline. Complete years are always included. + * @param includeAll If true, all publications are used for the timeline. + * @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 getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + maxTopicsPerYear, 'max_topics_per_year'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + targetPublications, 'target_publications'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + includeAll, 'include_all'); + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/topics-by-time`; + 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 + } ); - }); } - if (topicId) { - topicId.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic_id', + + /** + * Returns one publication. + * @endpoint get /api/works/detail/{work_id} + * @param workId The OpenAlex work id, for example W2741809807. + * @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 getWork(workId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getWork(workId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(workId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(workId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (workId === null || workId === undefined) { + throw new Error('Required parameter workId was null or undefined when calling getWork.'); + } + + 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/works/detail/${this.configuration.encodeParam({name: "workId", value: workId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } ); - }); } - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }, - ); - } - - /** - * Returns work counts per primary topic for an author. - * @endpoint get /api/works/{author_id}/primary-topic-counts - * @param authorId The author id, for example A5023888391. - * @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 getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/primary-topic-counts`; - 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, - }, - ); - } - - /** - * Returns topics grouped by publication year for an author. - * @endpoint get /api/works/{author_id}/topics-by-time - * @param authorId The author id, for example A5023888391. - * @param maxTopicsPerYear The maximum number of topics per year. - * @param targetPublications Target number of publications used for the timeline. Complete years are always included. - * @param includeAll If true, all publications are used for the timeline. - * @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 getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - maxTopicsPerYear, - 'max_topics_per_year', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - targetPublications, - 'target_publications', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - includeAll, - 'include_all', - ); - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/topics-by-time`; - 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, - }, - ); - } - - /** - * Returns one publication. - * @endpoint get /api/works/detail/{work_id} - * @param workId The OpenAlex work id, for example W2741809807. - * @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 getWork( - workId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getWork( - workId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getWork( - workId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getWork( - workId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (workId === null || workId === undefined) { - throw new Error( - 'Required parameter workId was null or undefined when calling getWork.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (bearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'bearer', - '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/works/detail/${this.configuration.encodeParam({ name: 'workId', value: workId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - 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, - }); - } } diff --git a/webapp/src/app/api/configuration.ts b/webapp/src/app/api/configuration.ts index 664630b3..2b8c80f7 100644 --- a/webapp/src/app/api/configuration.ts +++ b/webapp/src/app/api/configuration.ts @@ -1,219 +1,193 @@ -import { - HttpHeaders, - HttpParams, - HttpParameterCodec, -} from '@angular/common/http'; +import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; import { Param } from './param'; export interface ConfigurationParameters { - /** - * @deprecated Since 5.0. Use credentials instead - */ - apiKeys?: { [key: string]: string }; - username?: string; - password?: string; - /** - * @deprecated Since 5.0. Use credentials instead - */ - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; - /** - * Takes care of encoding query- and form-parameters. - */ - encoder?: HttpParameterCodec; - /** - * Override the default method for encoding path parameters in various - * styles. - *

- * See {@link README.md} for more details - *

- */ - encodeParam?: (param: Param) => string; - /** - * The keys are the names in the securitySchemes section of the OpenAPI - * document. They should map to the value used for authentication - * minus any standard prefixes such as 'Basic' or 'Bearer'. - */ - credentials?: { [key: string]: string | (() => string | undefined) }; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; } export class Configuration { - /** - * @deprecated Since 5.0. Use credentials instead - */ - apiKeys?: { [key: string]: string }; - username?: string; - password?: string; - /** - * @deprecated Since 5.0. Use credentials instead - */ - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; - /** - * Takes care of encoding query- and form-parameters. - */ - encoder?: HttpParameterCodec; - /** - * Encoding of various path parameter - * styles. - *

- * See {@link README.md} for more details - *

- */ - encodeParam: (param: Param) => string; - /** - * The keys are the names in the securitySchemes section of the OpenAPI - * document. They should map to the value used for authentication - * minus any standard prefixes such as 'Basic' or 'Bearer'. - */ - credentials: { [key: string]: string | (() => string | undefined) }; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; - constructor({ - accessToken, - apiKeys, - basePath, - credentials, - encodeParam, - encoder, - password, - username, - withCredentials, - }: ConfigurationParameters = {}) { - if (apiKeys) { - this.apiKeys = apiKeys; - } - if (username !== undefined) { - this.username = username; - } - if (password !== undefined) { - this.password = password; - } - if (accessToken !== undefined) { - this.accessToken = accessToken; - } - if (basePath !== undefined) { - this.basePath = basePath; - } - if (withCredentials !== undefined) { - this.withCredentials = withCredentials; - } - if (encoder) { - this.encoder = encoder; - } - this.encodeParam = - encodeParam ?? ((param) => this.defaultEncodeParam(param)); - this.credentials = credentials ?? {}; +constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) { + if (apiKeys) { + this.apiKeys = apiKeys; + } + if (username !== undefined) { + this.username = username; + } + if (password !== undefined) { + this.password = password; + } + if (accessToken !== undefined) { + this.accessToken = accessToken; + } + if (basePath !== undefined) { + this.basePath = basePath; + } + if (withCredentials !== undefined) { + this.withCredentials = withCredentials; + } + if (encoder) { + this.encoder = encoder; + } + this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param)); + this.credentials = credentials ?? {}; - // init default bearer credential - if (!this.credentials['bearer']) { - this.credentials['bearer'] = () => { - return typeof this.accessToken === 'function' - ? this.accessToken() - : this.accessToken; - }; - } - } - - /** - * Select the correct content-type to use for a request. - * Uses {@link Configuration#isJsonMime} to determine the correct content-type. - * If no content type is found return the first found type if the contentTypes is not empty - * @param contentTypes - the array of content types that are available for selection - * @returns the selected content-type or undefined if no selection could be made. - */ - public selectHeaderContentType(contentTypes: string[]): string | undefined { - if (contentTypes.length === 0) { - return undefined; + // init default HTTPBearer credential + if (!this.credentials['HTTPBearer']) { + this.credentials['HTTPBearer'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } } - const type = contentTypes.find((x: string) => this.isJsonMime(x)); - if (type === undefined) { - return contentTypes[0]; - } - return type; - } + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } - /** - * Select the correct accept content-type to use for a request. - * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. - * If no content type is found return the first found type if the contentTypes is not empty - * @param accepts - the array of content types that are available for selection. - * @returns the selected content-type or undefined if no selection could be made. - */ - public selectHeaderAccept(accepts: string[]): string | undefined { - if (accepts.length === 0) { - return undefined; + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; } - const type = accepts.find((x: string) => this.isJsonMime(x)); - if (type === undefined) { - return accepts[0]; + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; } - return type; - } - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * @param mime - MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public isJsonMime(mime: string): boolean { - const jsonMime: RegExp = new RegExp( - '^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', - 'i', - ); - return ( - mime !== null && - (jsonMime.test(mime) || - mime.toLowerCase() === 'application/json-patch+json') - ); - } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } - public lookupCredential(key: string): string | undefined { - const value = this.credentials[key]; - return typeof value === 'function' ? value() : value; - } + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } - public addCredentialToHeaders( - credentialKey: string, - headerName: string, - headers: HttpHeaders, - prefix?: string, - ): HttpHeaders { - const value = this.lookupCredential(credentialKey); - return value ? headers.set(headerName, (prefix ?? '') + value) : headers; - } + public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders { + const value = this.lookupCredential(credentialKey); + return value + ? headers.set(headerName, (prefix ?? '') + value) + : headers; + } - public addCredentialToQuery( - credentialKey: string, - paramName: string, - query: HttpParams, - ): HttpParams { - const value = this.lookupCredential(credentialKey); - return value ? query.set(paramName, value) : query; - } + public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams { + const value = this.lookupCredential(credentialKey); + return value + ? query.set(paramName, value) + : query; + } - private defaultEncodeParam(param: Param): string { - // This implementation exists as fallback for missing configuration - // and for backwards compatibility to older typescript-angular generator versions. - // It only works for the 'simple' parameter style. - // Date-handling only works for the 'date-time' format. - // All other styles and Date-formats are probably handled incorrectly. - // - // But: if that's all you need (i.e.: the most common use-case): no need for customization! + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! - const value = - param.dataFormat === 'date-time' && param.value instanceof Date - ? (param.value as Date).toISOString() - : param.value; + const value = param.dataFormat === 'date-time' && param.value instanceof Date + ? (param.value as Date).toISOString() + : param.value; - return encodeURIComponent(String(value)); - } + return encodeURIComponent(String(value)); + } } diff --git a/webapp/src/app/api/encoder.ts b/webapp/src/app/api/encoder.ts index 889ef00d..138c4d5c 100644 --- a/webapp/src/app/api/encoder.ts +++ b/webapp/src/app/api/encoder.ts @@ -5,16 +5,16 @@ import { HttpParameterCodec } from '@angular/common/http'; * Workaround for https://github.com/angular/angular/issues/18261 */ export class CustomHttpParameterCodec implements HttpParameterCodec { - encodeKey(k: string): string { - return encodeURIComponent(k); - } - encodeValue(v: string): string { - return encodeURIComponent(v); - } - decodeKey(k: string): string { - return decodeURIComponent(k); - } - decodeValue(v: string): string { - return decodeURIComponent(v); - } + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } } diff --git a/webapp/src/app/api/model/accessGrant.ts b/webapp/src/app/api/model/accessGrant.ts index 0aa29f6f..ad1f537a 100644 --- a/webapp/src/app/api/model/accessGrant.ts +++ b/webapp/src/app/api/model/accessGrant.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,10 +9,12 @@ */ import { AuthScope } from './authScope'; -export interface AccessGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; - refresh_token: string; + +export interface AccessGrant { + token_type: string; + access_token: string; + expires_in: number; + scope: AuthScope; + refresh_token: string; } + diff --git a/webapp/src/app/api/model/authAccount.ts b/webapp/src/app/api/model/authAccount.ts index 7a672b04..770a61f5 100644 --- a/webapp/src/app/api/model/authAccount.ts +++ b/webapp/src/app/api/model/authAccount.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface AuthAccount { - i: number; - l: string; - o: number; - e: string; - on: string; + +export interface AuthAccount { + i: number; + l: string; + o: number; + e: string; + on: string; } + diff --git a/webapp/src/app/api/model/authScope.ts b/webapp/src/app/api/model/authScope.ts index 3ccd752e..65ffa9b5 100644 --- a/webapp/src/app/api/model/authScope.ts +++ b/webapp/src/app/api/model/authScope.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { AuthAccount } from './authAccount'; -export interface AuthScope { - t: string; - a: AuthAccount; - d?: number | null; - r?: Array; + +export interface AuthScope { + t: string; + a: AuthAccount; + d?: number | null; + r?: Array; } + diff --git a/webapp/src/app/api/model/author.ts b/webapp/src/app/api/model/author.ts index 0a050590..9ba12273 100644 --- a/webapp/src/app/api/model/author.ts +++ b/webapp/src/app/api/model/author.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -15,25 +15,27 @@ import { AuthorIds } from './authorIds'; import { AuthorSummaryStats } from './authorSummaryStats'; import { WorkTopic } from './workTopic'; + /** * A person who creates scholarly works */ -export interface Author { - id?: string | null; - orcid?: string | null; - display_name?: string | null; - display_name_alternatives?: Array | null; - longest_name?: string | null; - parsed_longest_name?: AuthorParsedLongestName | null; - works_count?: number | null; - cited_by_count?: number | null; - summary_stats?: AuthorSummaryStats | null; - affiliations?: Array | null; - last_known_institutions?: Array | null; - topics?: Array | null; - counts_by_year?: Array | null; - ids?: AuthorIds | null; - works_api_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Author { + id?: string | null; + orcid?: string | null; + display_name?: string | null; + display_name_alternatives?: Array | null; + longest_name?: string | null; + parsed_longest_name?: AuthorParsedLongestName | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + affiliations?: Array | null; + last_known_institutions?: Array | null; + topics?: Array | null; + counts_by_year?: Array | null; + ids?: AuthorIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; } + diff --git a/webapp/src/app/api/model/authorAffiliationsInner.ts b/webapp/src/app/api/model/authorAffiliationsInner.ts index d1e8f764..270443ff 100644 --- a/webapp/src/app/api/model/authorAffiliationsInner.ts +++ b/webapp/src/app/api/model/authorAffiliationsInner.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,10 +9,12 @@ */ import { DehydratedInstitution } from './dehydratedInstitution'; + /** * AuthorAffiliationsInner */ -export interface AuthorAffiliationsInner { - institution?: DehydratedInstitution | null; - years?: Array | null; +export interface AuthorAffiliationsInner { + institution?: DehydratedInstitution | null; + years?: Array | null; } + diff --git a/webapp/src/app/api/model/authorCountsByYearInner.ts b/webapp/src/app/api/model/authorCountsByYearInner.ts index 1fac5b45..d16c7c21 100644 --- a/webapp/src/app/api/model/authorCountsByYearInner.ts +++ b/webapp/src/app/api/model/authorCountsByYearInner.ts @@ -1,18 +1,20 @@ /** * 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. */ + /** * AuthorCountsByYearInner */ -export interface AuthorCountsByYearInner { - year?: number | null; - works_count?: number | null; - cited_by_count?: number | null; +export interface AuthorCountsByYearInner { + year?: number | null; + works_count?: number | null; + cited_by_count?: number | null; } + diff --git a/webapp/src/app/api/model/authorIds.ts b/webapp/src/app/api/model/authorIds.ts index 0b079d33..9235a207 100644 --- a/webapp/src/app/api/model/authorIds.ts +++ b/webapp/src/app/api/model/authorIds.ts @@ -1,18 +1,20 @@ /** * 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. */ + /** * External identifiers: */ -export interface AuthorIds { - openalex?: string | null; - orcid?: string | null; - scopus?: string | null; +export interface AuthorIds { + openalex?: string | null; + orcid?: string | null; + scopus?: string | null; } + diff --git a/webapp/src/app/api/model/authorNetworkNode.ts b/webapp/src/app/api/model/authorNetworkNode.ts index f67c7148..aee98d47 100644 --- a/webapp/src/app/api/model/authorNetworkNode.ts +++ b/webapp/src/app/api/model/authorNetworkNode.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,22 @@ */ import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; -export interface AuthorNetworkNode { - /** - * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. - */ - raw_id: string; - /** - * The display name of the node. - */ - display_name: string; - /** - * The category of the node, either \'author\', \'institution\', or \'work\'. - */ - category: CollaborationNetworkNodeType; + +export interface AuthorNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; } -export namespace AuthorNetworkNode {} +export namespace AuthorNetworkNode { +} + + diff --git a/webapp/src/app/api/model/authorParsedLongestName.ts b/webapp/src/app/api/model/authorParsedLongestName.ts index f08df27d..f49e04be 100644 --- a/webapp/src/app/api/model/authorParsedLongestName.ts +++ b/webapp/src/app/api/model/authorParsedLongestName.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The longest name parsed into its component parts. */ -export interface AuthorParsedLongestName { - first?: string | null; - middle?: string | null; - last?: string | null; - suffix?: string | null; - nickname?: string | null; +export interface AuthorParsedLongestName { + first?: string | null; + middle?: string | null; + last?: string | null; + suffix?: string | null; + nickname?: string | null; } + diff --git a/webapp/src/app/api/model/authorPositionCount.ts b/webapp/src/app/api/model/authorPositionCount.ts index 989d2c18..a02e3749 100644 --- a/webapp/src/app/api/model/authorPositionCount.ts +++ b/webapp/src/app/api/model/authorPositionCount.ts @@ -1,16 +1,18 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface AuthorPositionCount { - first?: number; - middle?: number; - last?: number; - unknown?: number; + +export interface AuthorPositionCount { + first?: number; + middle?: number; + last?: number; + unknown?: number; } + diff --git a/webapp/src/app/api/model/authorSummaryStats.ts b/webapp/src/app/api/model/authorSummaryStats.ts index 63c35c31..1cfc0bdb 100644 --- a/webapp/src/app/api/model/authorSummaryStats.ts +++ b/webapp/src/app/api/model/authorSummaryStats.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,11 +9,13 @@ */ import { Model2YrMeanCitedness } from './model2YrMeanCitedness'; + /** * Citation metrics: */ -export interface AuthorSummaryStats { - '2yr_mean_citedness'?: Model2YrMeanCitedness | null; - h_index?: number | null; - i10_index?: number | null; +export interface AuthorSummaryStats { + '2yr_mean_citedness'?: Model2YrMeanCitedness | null; + h_index?: number | null; + i10_index?: number | null; } + diff --git a/webapp/src/app/api/model/authorsFilterProperties.ts b/webapp/src/app/api/model/authorsFilterProperties.ts index 50795f2a..7312558f 100644 --- a/webapp/src/app/api/model/authorsFilterProperties.ts +++ b/webapp/src/app/api/model/authorsFilterProperties.ts @@ -1,24 +1,26 @@ /** * 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 AuthorsFilterProperties { - /** - * The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included. - */ - allowed_institutions?: Array; - /** - * The minimum number of collaborations required for an author to be included in the collaboration network. - */ - min_collaborations?: number; - /** - * The maximum number of collaborations allowed for an author to be included in the collaboration network. - */ - max_collaborations?: number; + +export interface AuthorsFilterProperties { + /** + * The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included. + */ + allowed_institutions?: Array; + /** + * The minimum number of collaborations required for an author to be included in the collaboration network. + */ + min_collaborations?: number; + /** + * The maximum number of collaborations allowed for an author to be included in the collaboration network. + */ + max_collaborations?: number; } + diff --git a/webapp/src/app/api/model/authorsListResponse.ts b/webapp/src/app/api/model/authorsListResponse.ts index bb1a602c..d309ae43 100644 --- a/webapp/src/app/api/model/authorsListResponse.ts +++ b/webapp/src/app/api/model/authorsListResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,11 +11,13 @@ import { Meta } from './meta'; import { Author } from './author'; import { GroupByResult } from './groupByResult'; + /** * AuthorsListResponse */ -export interface AuthorsListResponse { - meta?: Meta | null; - results?: Array | null; - group_by?: Array | null; +export interface AuthorsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; } + diff --git a/webapp/src/app/api/model/authorship.ts b/webapp/src/app/api/model/authorship.ts index f1b9d48e..db3a0bf0 100644 --- a/webapp/src/app/api/model/authorship.ts +++ b/webapp/src/app/api/model/authorship.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,15 +10,17 @@ import { DehydratedInstitution } from './dehydratedInstitution'; import { DehydratedAuthor } from './dehydratedAuthor'; + /** * Author and their affiliation for a work */ -export interface Authorship { - author_position?: string | null; - author?: DehydratedAuthor | null; - institutions?: Array | null; - countries?: Array | null; - is_corresponding?: boolean | null; - raw_author_name?: string | null; - raw_affiliation_strings?: Array | null; +export interface Authorship { + author_position?: string | null; + author?: DehydratedAuthor | null; + institutions?: Array | null; + countries?: Array | null; + is_corresponding?: boolean | null; + raw_author_name?: string | null; + raw_affiliation_strings?: Array | null; } + diff --git a/webapp/src/app/api/model/autocompleteResponse.ts b/webapp/src/app/api/model/autocompleteResponse.ts index 8b52b300..e220f57b 100644 --- a/webapp/src/app/api/model/autocompleteResponse.ts +++ b/webapp/src/app/api/model/autocompleteResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,10 +10,12 @@ import { AutocompleteResponseMeta } from './autocompleteResponseMeta'; import { AutocompleteResponseResultsInner } from './autocompleteResponseResultsInner'; + /** * AutocompleteResponse */ -export interface AutocompleteResponse { - meta?: AutocompleteResponseMeta | null; - results?: Array | null; +export interface AutocompleteResponse { + meta?: AutocompleteResponseMeta | null; + results?: Array | null; } + diff --git a/webapp/src/app/api/model/autocompleteResponseMeta.ts b/webapp/src/app/api/model/autocompleteResponseMeta.ts index 5bf94a57..2e080d39 100644 --- a/webapp/src/app/api/model/autocompleteResponseMeta.ts +++ b/webapp/src/app/api/model/autocompleteResponseMeta.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * AutocompleteResponseMeta */ -export interface AutocompleteResponseMeta { - count?: number | null; - db_response_time_ms?: number | null; +export interface AutocompleteResponseMeta { + count?: number | null; + db_response_time_ms?: number | null; } + diff --git a/webapp/src/app/api/model/autocompleteResponseResultsInner.ts b/webapp/src/app/api/model/autocompleteResponseResultsInner.ts index 0fa956b7..99ba71fe 100644 --- a/webapp/src/app/api/model/autocompleteResponseResultsInner.ts +++ b/webapp/src/app/api/model/autocompleteResponseResultsInner.ts @@ -1,22 +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. */ + /** * AutocompleteResponseResultsInner */ -export interface AutocompleteResponseResultsInner { - id?: string | null; - display_name?: string | null; - hint?: string | null; - cited_by_count?: number | null; - works_count?: number | null; - entity_type?: string | null; - external_id?: string | null; +export interface AutocompleteResponseResultsInner { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; } + diff --git a/webapp/src/app/api/model/award.ts b/webapp/src/app/api/model/award.ts index a461c971..4e3b5cc9 100644 --- a/webapp/src/app/api/model/award.ts +++ b/webapp/src/app/api/model/award.ts @@ -1,21 +1,23 @@ /** * 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. */ + /** * Award */ -export interface Award { - id?: string | null; - display_name?: string | null; - funder_award_id?: string | null; - funder_id?: string | null; - funder_display_name?: string | null; - doi?: string | null; +export interface Award { + id?: string | null; + display_name?: string | null; + funder_award_id?: string | null; + funder_id?: string | null; + funder_display_name?: string | null; + doi?: string | null; } + diff --git a/webapp/src/app/api/model/item.ts b/webapp/src/app/api/model/bodyChangePassword.ts similarity index 50% rename from webapp/src/app/api/model/item.ts rename to webapp/src/app/api/model/bodyChangePassword.ts index 377f3a81..b6454f0e 100644 --- a/webapp/src/app/api/model/item.ts +++ b/webapp/src/app/api/model/bodyChangePassword.ts @@ -1,24 +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 Item { - /** - * The id of the entity. - */ - id: number; - /** - * The name of the item. - */ - name: string; - /** - * The description of the item. - */ - description: string; + +export interface BodyChangePassword { + /** + * Current password + */ + current_password: string; + /** + * New password + */ + new_password: string; } + diff --git a/webapp/src/app/api/model/bodyCreateUser.ts b/webapp/src/app/api/model/bodyCreateUser.ts index 6a0778be..76caab3b 100644 --- a/webapp/src/app/api/model/bodyCreateUser.ts +++ b/webapp/src/app/api/model/bodyCreateUser.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface BodyCreateUser { - username: string; - password: string; - email: string; - institution: string; - superadmin?: boolean; + +export interface BodyCreateUser { + username: string; + password: string; + email: string; + institution: string; + superadmin?: boolean; } + diff --git a/webapp/src/app/api/model/bodyGetAccessToken.ts b/webapp/src/app/api/model/bodyGetAccessToken.ts new file mode 100644 index 00000000..8e5df2ed --- /dev/null +++ b/webapp/src/app/api/model/bodyGetAccessToken.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.ts b/webapp/src/app/api/model/bodyLogin.ts new file mode 100644 index 00000000..f4022b0b --- /dev/null +++ b/webapp/src/app/api/model/bodyLogin.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/itemCreate.ts b/webapp/src/app/api/model/bodyRequestOtk.ts similarity index 55% rename from webapp/src/app/api/model/itemCreate.ts rename to webapp/src/app/api/model/bodyRequestOtk.ts index 36920a12..ba1a396d 100644 --- a/webapp/src/app/api/model/itemCreate.ts +++ b/webapp/src/app/api/model/bodyRequestOtk.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface ItemCreate { - /** - * The name of the item. - */ - name: string; - /** - * The description of the item. - */ - description: string; + +export interface BodyRequestOtk { + /** + * User\'s email address + */ + email: string; + /** + * User\'s password + */ + password: string; } + diff --git a/webapp/src/app/api/model/bundProject.ts b/webapp/src/app/api/model/bundProject.ts index 9f291399..3463aa78 100644 --- a/webapp/src/app/api/model/bundProject.ts +++ b/webapp/src/app/api/model/bundProject.ts @@ -1,40 +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. */ -export interface BundProject { - funding_code?: string | null; - department?: string | null; - department_fullname?: string | null; - referat?: string | null; - project_sponsor?: string | null; - project_sponsor_fullname?: string | null; - work_unit?: string | null; - recipient?: string | null; - municipal_code?: string | null; - municipality?: string | null; - place?: string | null; - state?: string | null; - country?: string | null; - implementing_agency?: string | null; - topic?: string | null; - performance_plan_system?: string | null; - performance_plan_system_text?: string | null; - funding_start?: string | null; - funding_end?: string | null; - grant_amount?: number | null; - funding_profile?: string | null; - joint_project?: string | null; - funding_type?: string | null; - publication_date?: string | null; - unix_timestamp?: number | null; - date?: string | null; - new?: boolean | null; - duration?: string | null; + +export interface BundProject { + funding_code?: string | null; + department?: string | null; + department_fullname?: string | null; + referat?: string | null; + project_sponsor?: string | null; + project_sponsor_fullname?: string | null; + work_unit?: string | null; + recipient?: string | null; + municipal_code?: string | null; + municipality?: string | null; + place?: string | null; + state?: string | null; + country?: string | null; + implementing_agency?: string | null; + topic?: string | null; + performance_plan_system?: string | null; + performance_plan_system_text?: string | null; + funding_start?: string | null; + funding_end?: string | null; + grant_amount?: number | null; + funding_profile?: string | null; + joint_project?: string | null; + funding_type?: string | null; + publication_date?: string | null; + unix_timestamp?: number | null; + date?: string | null; + 'new'?: boolean | null; + duration?: string | null; } + diff --git a/webapp/src/app/api/model/bundProjectDetails.ts b/webapp/src/app/api/model/bundProjectDetails.ts index b61df06b..2193563c 100644 --- a/webapp/src/app/api/model/bundProjectDetails.ts +++ b/webapp/src/app/api/model/bundProjectDetails.ts @@ -1,55 +1,57 @@ /** * 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. */ + /** * Clean summary model for a Bund (federal) project, consolidating all fields into semantic English names with proper native types. */ -export interface BundProjectDetails { - /** - * The ID of the Bund project - */ - id: string; - funding_reference?: string | null; - title?: string | null; - description?: string | null; - joint_project?: string | null; - funding_type?: string | null; - funding_profile?: string | null; - funding_amount?: number | null; - funding_start_date?: string | null; - funding_end_date?: string | null; - duration?: string | null; - performance_plan_code?: string | null; - performance_plan_fullname?: string | null; - executing_agency?: string | null; - funding_recipient?: string | null; - project_agency?: string | null; - project_agency_fullname?: string | null; - department?: string | null; - department_fullname?: string | null; - division?: string | null; - location?: string | null; - municipality?: string | null; - state?: string | null; - country?: string | null; - municipality_code?: string | null; - publication_date?: string | null; - is_new?: boolean | null; - record_date?: string | null; - unix_timestamp?: number | null; - /** - * All persons associated with the Bund project (from nested Arb object) - */ - associated_persons?: Array; - /** - * All institutions associated with the Bund project - */ - institutions?: Array; +export interface BundProjectDetails { + /** + * The ID of the Bund project + */ + id: string; + funding_reference?: string | null; + title?: string | null; + description?: string | null; + joint_project?: string | null; + funding_type?: string | null; + funding_profile?: string | null; + funding_amount?: number | null; + funding_start_date?: string | null; + funding_end_date?: string | null; + duration?: string | null; + performance_plan_code?: string | null; + performance_plan_fullname?: string | null; + executing_agency?: string | null; + funding_recipient?: string | null; + project_agency?: string | null; + project_agency_fullname?: string | null; + department?: string | null; + department_fullname?: string | null; + division?: string | null; + location?: string | null; + municipality?: string | null; + state?: string | null; + country?: string | null; + municipality_code?: string | null; + publication_date?: string | null; + is_new?: boolean | null; + record_date?: string | null; + unix_timestamp?: number | null; + /** + * All persons associated with the Bund project (from nested Arb object) + */ + associated_persons?: Array; + /** + * All institutions associated with the Bund project + */ + institutions?: Array; } + diff --git a/webapp/src/app/api/model/bundProjectPage.ts b/webapp/src/app/api/model/bundProjectPage.ts index 6c38e7a6..10514bce 100644 --- a/webapp/src/app/api/model/bundProjectPage.ts +++ b/webapp/src/app/api/model/bundProjectPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { BundProject } from './bundProject'; -export interface BundProjectPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The bund projects on this page. - */ - elements?: Array; + +export interface BundProjectPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The bund projects on this page. + */ + elements?: Array; } + diff --git a/webapp/src/app/api/model/careerMetrics.ts b/webapp/src/app/api/model/careerMetrics.ts index eb84c19f..abb58689 100644 --- a/webapp/src/app/api/model/careerMetrics.ts +++ b/webapp/src/app/api/model/careerMetrics.ts @@ -1,32 +1,34 @@ /** * 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 CareerMetrics { - first_publication_year?: number | null; - last_publication_year?: number | null; - career_age?: number | null; - career_span?: number | null; - career_stage?: string | null; - /** - * Number of distinct years with at least one publication. - */ - active_years?: number; - /** - * Number of publications used for career metrics. - */ - publication_count?: number; - publications_per_active_year?: number | null; - publications_per_career_year?: number | null; - years_since_last_publication?: number | null; - /** - * True if publication years look suspicious. - */ - has_suspicious_publication_years?: boolean; + +export interface CareerMetrics { + first_publication_year?: number | null; + last_publication_year?: number | null; + career_age?: number | null; + career_span?: number | null; + career_stage?: string | null; + /** + * Number of distinct years with at least one publication. + */ + active_years?: number; + /** + * Number of publications used for career metrics. + */ + publication_count?: number; + publications_per_active_year?: number | null; + publications_per_career_year?: number | null; + years_since_last_publication?: number | null; + /** + * True if publication years look suspicious. + */ + has_suspicious_publication_years?: boolean; } + diff --git a/webapp/src/app/api/model/collaborationNetwork.ts b/webapp/src/app/api/model/collaborationNetwork.ts index a2fbdc5b..e439c061 100644 --- a/webapp/src/app/api/model/collaborationNetwork.ts +++ b/webapp/src/app/api/model/collaborationNetwork.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -13,29 +13,31 @@ import { CollaborationNetworkEdge } from './collaborationNetworkEdge'; import { InstitutionNetworkNode } from './institutionNetworkNode'; import { AuthorNetworkNode } from './authorNetworkNode'; -export interface CollaborationNetwork { - /** - * The raw person ID of the person whose collaboration network this is. - */ - raw_person_id: string; - /** - * The work nodes in the collaboration network. - */ - work_nodes: Array; - /** - * The author nodes in the collaboration network. - */ - author_nodes: Array; - /** - * The institution nodes in the collaboration network. - */ - institution_nodes: Array; - /** - * The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I - */ - collaboration_edges: Array; - /** - * The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network. - */ - filter_information: FilterInformation; + +export interface CollaborationNetwork { + /** + * The raw person ID of the person whose collaboration network this is. + */ + raw_person_id: string; + /** + * The work nodes in the collaboration network. + */ + work_nodes: Array; + /** + * The author nodes in the collaboration network. + */ + author_nodes: Array; + /** + * The institution nodes in the collaboration network. + */ + institution_nodes: Array; + /** + * The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I + */ + collaboration_edges: Array; + /** + * The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network. + */ + filter_information: FilterInformation; } + diff --git a/webapp/src/app/api/model/collaborationNetworkEdge.ts b/webapp/src/app/api/model/collaborationNetworkEdge.ts index baffb178..16fb5fc6 100644 --- a/webapp/src/app/api/model/collaborationNetworkEdge.ts +++ b/webapp/src/app/api/model/collaborationNetworkEdge.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface CollaborationNetworkEdge { - /** - * The raw ID of the source node. - */ - raw_source_id: string; - /** - * The raw ID of the target node. - */ - raw_target_id: string; + +export interface CollaborationNetworkEdge { + /** + * The raw ID of the source node. + */ + raw_source_id: string; + /** + * The raw ID of the target node. + */ + raw_target_id: string; } + diff --git a/webapp/src/app/api/model/collaborationNetworkNodeType.ts b/webapp/src/app/api/model/collaborationNetworkNodeType.ts index 3e673f35..752e35b0 100644 --- a/webapp/src/app/api/model/collaborationNetworkNodeType.ts +++ b/webapp/src/app/api/model/collaborationNetworkNodeType.ts @@ -1,17 +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 CollaborationNetworkNodeType = { - Author: 'author', - Institution: 'institution', - Work: 'work', + Author: 'author', + Institution: 'institution', + Work: 'work' } as const; -export type CollaborationNetworkNodeType = - (typeof CollaborationNetworkNodeType)[keyof typeof CollaborationNetworkNodeType]; +export type CollaborationNetworkNodeType = typeof CollaborationNetworkNodeType[keyof typeof CollaborationNetworkNodeType]; + diff --git a/webapp/src/app/api/model/companyConnection.ts b/webapp/src/app/api/model/companyConnection.ts index 2824c543..4ce31814 100644 --- a/webapp/src/app/api/model/companyConnection.ts +++ b/webapp/src/app/api/model/companyConnection.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,17 +9,19 @@ */ import { MatchedOfficer } from './matchedOfficer'; -export interface CompanyConnection { - company_number?: string | null; - company_name?: string | null; - company_status?: string | null; - register_art?: string | null; - register_nummer?: string | null; - native_company_number?: string | null; - registrar?: string | null; - registered_office?: string | null; - registered_address?: string | null; - retrieved_at?: string | null; - matched_officers?: Array; - officers?: Array; + +export interface CompanyConnection { + company_number?: string | null; + company_name?: string | null; + company_status?: string | null; + register_art?: string | null; + register_nummer?: string | null; + native_company_number?: string | null; + registrar?: string | null; + registered_office?: string | null; + registered_address?: string | null; + retrieved_at?: string | null; + matched_officers?: Array; + officers?: Array; } + diff --git a/webapp/src/app/api/model/companyConnectionsResponse.ts b/webapp/src/app/api/model/companyConnectionsResponse.ts index f4f5f42f..9beabd1e 100644 --- a/webapp/src/app/api/model/companyConnectionsResponse.ts +++ b/webapp/src/app/api/model/companyConnectionsResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,15 +9,17 @@ */ import { CompanyConnection } from './companyConnection'; -export interface CompanyConnectionsResponse { - author_id: string; - display_name?: string | null; - is_ude_author: boolean; - institution_scope?: string | null; - matching_institutions?: Array; - matching_method?: string | null; - company_count: number; - has_more_results: boolean; - common_name_warning: boolean; - connections?: Array; + +export interface CompanyConnectionsResponse { + author_id: string; + display_name?: string | null; + is_ude_author: boolean; + institution_scope?: string | null; + matching_institutions?: Array; + matching_method?: string | null; + company_count: number; + has_more_results: boolean; + common_name_warning: boolean; + connections?: Array; } + diff --git a/webapp/src/app/api/model/cordisEuProject.ts b/webapp/src/app/api/model/cordisEuProject.ts index 8d408ad6..f18dd3d4 100644 --- a/webapp/src/app/api/model/cordisEuProject.ts +++ b/webapp/src/app/api/model/cordisEuProject.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,30 +10,32 @@ import { Keywords } from './keywords'; import { Topics } from './topics'; -export interface CordisEuProject { - /** - * Unique identifier for the project, typically the CORDIS ID - */ - id: string; - rcn?: string | null; - acronym?: string | null; - title?: string | null; - objective?: string | null; - frameworkProgramme?: string | null; - fundingScheme?: string | null; - legalBasis?: string | null; - masterCall?: string | null; - subCall?: string | null; - topics?: Topics | null; - nature?: string | null; - status?: string | null; - ecMaxContribution?: number | null; - totalCost?: number | null; - startDate?: string | null; - endDate?: string | null; - ecSignatureDate?: string | null; - contentUpdateDate?: string | null; - grantDoi?: string | null; - humanValidated?: boolean | null; - keywords?: Keywords | null; + +export interface CordisEuProject { + /** + * Unique identifier for the project, typically the CORDIS ID + */ + id: string; + rcn?: string | null; + acronym?: string | null; + title?: string | null; + objective?: string | null; + frameworkProgramme?: string | null; + fundingScheme?: string | null; + legalBasis?: string | null; + masterCall?: string | null; + subCall?: string | null; + topics?: Topics | null; + nature?: string | null; + status?: string | null; + ecMaxContribution?: number | null; + totalCost?: number | null; + startDate?: string | null; + endDate?: string | null; + ecSignatureDate?: string | null; + contentUpdateDate?: string | null; + grantDoi?: string | null; + humanValidated?: boolean | null; + keywords?: Keywords | null; } + diff --git a/webapp/src/app/api/model/cordisEuProjectPage.ts b/webapp/src/app/api/model/cordisEuProjectPage.ts index 8dc900f7..393f6db8 100644 --- a/webapp/src/app/api/model/cordisEuProjectPage.ts +++ b/webapp/src/app/api/model/cordisEuProjectPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { CordisEuProject } from './cordisEuProject'; -export interface CordisEuProjectPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The CORDIS EU projects on this page. - */ - elements?: Array; + +export interface CordisEuProjectPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The CORDIS EU projects on this page. + */ + elements?: Array; } + diff --git a/webapp/src/app/api/model/costUsd.ts b/webapp/src/app/api/model/costUsd.ts index 494cb094..c7bcbee8 100644 --- a/webapp/src/app/api/model/costUsd.ts +++ b/webapp/src/app/api/model/costUsd.ts @@ -1,14 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * Cost of this request in USD */ -export interface CostUsd {} +export interface CostUsd { +} + diff --git a/webapp/src/app/api/model/customAuthor.ts b/webapp/src/app/api/model/customAuthor.ts index 6fd54c51..0cf7eb21 100644 --- a/webapp/src/app/api/model/customAuthor.ts +++ b/webapp/src/app/api/model/customAuthor.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -16,24 +16,26 @@ import { AuthorIds } from './authorIds'; import { AuthorSummaryStats } from './authorSummaryStats'; import { WorkTopic } from './workTopic'; -export interface CustomAuthor { - id?: string | null; - orcid?: string | null; - display_name?: string | null; - display_name_alternatives?: Array | null; - longest_name?: string | null; - parsed_longest_name?: AuthorParsedLongestName | null; - works_count?: number | null; - cited_by_count?: number | null; - summary_stats?: AuthorSummaryStats | null; - affiliations?: Array | null; - last_known_institutions?: Array | null; - topics?: Array | null; - counts_by_year?: Array | null; - ids?: AuthorIds | null; - works_api_url?: string | null; - created_date?: string | null; - updated_date?: string | null; - relevance_rating?: string | null; - career_metrics?: CareerMetrics | null; + +export interface CustomAuthor { + id?: string | null; + orcid?: string | null; + display_name?: string | null; + display_name_alternatives?: Array | null; + longest_name?: string | null; + parsed_longest_name?: AuthorParsedLongestName | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + affiliations?: Array | null; + last_known_institutions?: Array | null; + topics?: Array | null; + counts_by_year?: Array | null; + ids?: AuthorIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; + relevance_rating?: string | null; + career_metrics?: CareerMetrics | null; } + diff --git a/webapp/src/app/api/model/customAuthorsListResponse.ts b/webapp/src/app/api/model/customAuthorsListResponse.ts index 71f691a2..3c80ddf5 100644 --- a/webapp/src/app/api/model/customAuthorsListResponse.ts +++ b/webapp/src/app/api/model/customAuthorsListResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,9 +11,11 @@ import { Meta } from './meta'; import { CustomAuthor } from './customAuthor'; import { GroupByResult } from './groupByResult'; -export interface CustomAuthorsListResponse { - meta?: Meta | null; - results?: Array | null; - group_by?: Array | null; - placeholder?: CustomAuthor | null; + +export interface CustomAuthorsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; + placeholder?: CustomAuthor | null; } + diff --git a/webapp/src/app/api/model/dehydratedAuthor.ts b/webapp/src/app/api/model/dehydratedAuthor.ts index 350718ef..4d3817f1 100644 --- a/webapp/src/app/api/model/dehydratedAuthor.ts +++ b/webapp/src/app/api/model/dehydratedAuthor.ts @@ -1,18 +1,20 @@ /** * 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. */ + /** * [Dehydrated Author](/api-reference/authors#the-dehydratedauthor-object) — reduced-field version used in nested contexts */ -export interface DehydratedAuthor { - id?: string | null; - display_name?: string | null; - orcid?: string | null; +export interface DehydratedAuthor { + id?: string | null; + display_name?: string | null; + orcid?: string | null; } + diff --git a/webapp/src/app/api/model/dehydratedFunder.ts b/webapp/src/app/api/model/dehydratedFunder.ts index c4231c13..b134bbb1 100644 --- a/webapp/src/app/api/model/dehydratedFunder.ts +++ b/webapp/src/app/api/model/dehydratedFunder.ts @@ -1,18 +1,20 @@ /** * 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. */ + /** * [Dehydrated Funder](/api-reference/funders) — reduced-field version used in nested contexts */ -export interface DehydratedFunder { - id?: string | null; - display_name?: string | null; - ror?: string | null; +export interface DehydratedFunder { + id?: string | null; + display_name?: string | null; + ror?: string | null; } + diff --git a/webapp/src/app/api/model/dehydratedInstitution.ts b/webapp/src/app/api/model/dehydratedInstitution.ts index 956fc03e..7b6c9824 100644 --- a/webapp/src/app/api/model/dehydratedInstitution.ts +++ b/webapp/src/app/api/model/dehydratedInstitution.ts @@ -1,21 +1,23 @@ /** * 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. */ + /** * [Dehydrated Institution](/api-reference/institutions#the-dehydratedinstitution-object) — reduced-field version used in nested contexts */ -export interface DehydratedInstitution { - id?: string | null; - display_name?: string | null; - ror?: string | null; - country_code?: string | null; - type?: string | null; - lineage?: Array | null; +export interface DehydratedInstitution { + id?: string | null; + display_name?: string | null; + ror?: string | null; + country_code?: string | null; + type?: string | null; + lineage?: Array | null; } + diff --git a/webapp/src/app/api/model/dehydratedSource.ts b/webapp/src/app/api/model/dehydratedSource.ts index b672b5dd..ae714846 100644 --- a/webapp/src/app/api/model/dehydratedSource.ts +++ b/webapp/src/app/api/model/dehydratedSource.ts @@ -1,26 +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. */ + /** * [Dehydrated Source](/api-reference/sources#the-dehydratedsource-object) — reduced-field version used in nested contexts */ -export interface DehydratedSource { - id?: string | null; - display_name?: string | null; - issn_l?: string | null; - issn?: Array | null; - is_oa?: boolean | null; - is_in_doaj?: boolean | null; - is_core?: boolean | null; - host_organization?: string | null; - host_organization_name?: string | null; - host_organization_lineage?: Array | null; - type?: string | null; +export interface DehydratedSource { + id?: string | null; + display_name?: string | null; + issn_l?: string | null; + issn?: Array | null; + is_oa?: boolean | null; + is_in_doaj?: boolean | null; + is_core?: boolean | null; + host_organization?: string | null; + host_organization_name?: string | null; + host_organization_lineage?: Array | null; + type?: string | null; } + diff --git a/webapp/src/app/api/model/dfgProjectDetails.ts b/webapp/src/app/api/model/dfgProjectDetails.ts index 58ece5f7..5fe29ff9 100644 --- a/webapp/src/app/api/model/dfgProjectDetails.ts +++ b/webapp/src/app/api/model/dfgProjectDetails.ts @@ -1,39 +1,41 @@ /** * 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. */ + /** * Clean summary model for a DFG project, consolidating all person roles and institution references into unified lists. */ -export interface DfgProjectDetails { - /** - * The ID of the DFG project - */ - id: string; - link?: string | null; - title?: string | null; - description?: string | null; - project_identifier?: string | null; - funding_start_date?: string | null; - funding_end_date?: string | null; - dfg_procedure?: string | null; - subject_area?: string | null; - funding_type?: string | null; - international_reference?: string | null; - website?: string | null; - /** - * All persons associated with the DFG project (any role) - */ - associated_persons?: Array; - /** - * All institutions associated with the DFG project - */ - institutions?: Array; - subproject_of?: string | null; +export interface DfgProjectDetails { + /** + * The ID of the DFG project + */ + id: string; + link?: string | null; + title?: string | null; + description?: string | null; + project_identifier?: string | null; + funding_start_date?: string | null; + funding_end_date?: string | null; + dfg_procedure?: string | null; + subject_area?: string | null; + funding_type?: string | null; + international_reference?: string | null; + website?: string | null; + /** + * All persons associated with the DFG project (any role) + */ + associated_persons?: Array; + /** + * All institutions associated with the DFG project + */ + institutions?: Array; + subproject_of?: string | null; } + diff --git a/webapp/src/app/api/model/dfgProjectPage.ts b/webapp/src/app/api/model/dfgProjectPage.ts index a05d81d2..8f67e170 100644 --- a/webapp/src/app/api/model/dfgProjectPage.ts +++ b/webapp/src/app/api/model/dfgProjectPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { DfgProjectSummary } from './dfgProjectSummary'; -export interface DfgProjectPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The DFG projects on this page. - */ - elements?: Array; + +export interface DfgProjectPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The DFG projects on this page. + */ + elements?: Array; } + diff --git a/webapp/src/app/api/model/dfgProjectSummary.ts b/webapp/src/app/api/model/dfgProjectSummary.ts index 10c05a08..145dba4a 100644 --- a/webapp/src/app/api/model/dfgProjectSummary.ts +++ b/webapp/src/app/api/model/dfgProjectSummary.ts @@ -1,25 +1,27 @@ /** * 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 DfgProjectSummary { - /** - * The unique identifier of the DFG project. - */ - id: string; - link?: string | null; - title?: string | null; - professional_classification?: string | null; - funding_start?: string | null; - funding_end?: string | null; - /** - * The names of the researchers involved in the DFG project. - */ - names?: Array; + +export interface DfgProjectSummary { + /** + * The unique identifier of the DFG project. + */ + id: string; + link?: string | null; + title?: string | null; + professional_classification?: string | null; + funding_start?: string | null; + funding_end?: string | null; + /** + * The names of the researchers involved in the DFG project. + */ + names?: Array; } + diff --git a/webapp/src/app/api/model/euOrganizationProjectSummary.ts b/webapp/src/app/api/model/euOrganizationProjectSummary.ts index af085ff3..3cc10f0a 100644 --- a/webapp/src/app/api/model/euOrganizationProjectSummary.ts +++ b/webapp/src/app/api/model/euOrganizationProjectSummary.ts @@ -1,25 +1,27 @@ /** * 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 EuOrganizationProjectSummary { - /** - * The unique identifier of the organization. - */ - organization_id: string; - /** - * The unique identifier of the project. - */ - project_id: string; - title?: string | null; - start_date?: string | null; - end_date?: string | null; - acronym?: string | null; - ec_contribution?: number | null; + +export interface EuOrganizationProjectSummary { + /** + * The unique identifier of the organization. + */ + organization_id: string; + /** + * The unique identifier of the project. + */ + project_id: string; + title?: string | null; + start_date?: string | null; + end_date?: string | null; + acronym?: string | null; + ec_contribution?: number | null; } + diff --git a/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts b/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts index 90166a7e..9d57d5b4 100644 --- a/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts +++ b/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary'; -export interface EuOrganizationProjectSummaryPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The organization project summaries on this page. - */ - elements?: Array; + +export interface EuOrganizationProjectSummaryPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The organization project summaries on this page. + */ + elements?: Array; } + diff --git a/webapp/src/app/api/model/filterInformation.ts b/webapp/src/app/api/model/filterInformation.ts index 1c4af66d..b2078376 100644 --- a/webapp/src/app/api/model/filterInformation.ts +++ b/webapp/src/app/api/model/filterInformation.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,21 +10,23 @@ import { InstitutionInformation } from './institutionInformation'; import { WorkTopicInformation } from './workTopicInformation'; -export interface FilterInformation { - /** - * The minimum publication year of the works in the collaboration network. - */ - min_possible_year: number; - /** - * The maximum publication year of the works in the collaboration network. - */ - max_possible_year: number; - /** - * The list of institutions associated with the works in the collaboration network. - */ - institutions: Array; - /** - * The list of topics associated with the works in the collaboration network. - */ - topics: Array; + +export interface FilterInformation { + /** + * The minimum publication year of the works in the collaboration network. + */ + min_possible_year: number; + /** + * The maximum publication year of the works in the collaboration network. + */ + max_possible_year: number; + /** + * The list of institutions associated with the works in the collaboration network. + */ + institutions: Array; + /** + * The list of topics associated with the works in the collaboration network. + */ + topics: Array; } + diff --git a/webapp/src/app/api/model/filterProperties.ts b/webapp/src/app/api/model/filterProperties.ts index 7caac0b6..608acab4 100644 --- a/webapp/src/app/api/model/filterProperties.ts +++ b/webapp/src/app/api/model/filterProperties.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,11 +10,13 @@ import { WorksFilterProperties } from './worksFilterProperties'; import { AuthorsFilterProperties } from './authorsFilterProperties'; -export interface FilterProperties { - /** - * The type of filter to apply when generating the collaboration network. Can be either \'works\' or \'authors\'. If \'works\', the filter properties in the \'works_filter_properties\' field will be used. If \'authors\', the filter properties in the \'authors_filter_properties\' field will be used. - */ - filter_by?: string; - works_filter_properties: WorksFilterProperties | null; - authors_filter_properties: AuthorsFilterProperties | null; + +export interface FilterProperties { + /** + * The type of filter to apply when generating the collaboration network. Can be either \'works\' or \'authors\'. If \'works\', the filter properties in the \'works_filter_properties\' field will be used. If \'authors\', the filter properties in the \'authors_filter_properties\' field will be used. + */ + filter_by?: string; + works_filter_properties: WorksFilterProperties | null; + authors_filter_properties: AuthorsFilterProperties | null; } + diff --git a/webapp/src/app/api/model/funderByAuthor.ts b/webapp/src/app/api/model/funderByAuthor.ts index c62110e7..247e5629 100644 --- a/webapp/src/app/api/model/funderByAuthor.ts +++ b/webapp/src/app/api/model/funderByAuthor.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,13 +11,15 @@ import { PublicationIdsByAuthorPosition } from './publicationIdsByAuthorPosition import { AuthorPositionCount } from './authorPositionCount'; import { PublicationDetailByFunder } from './publicationDetailByFunder'; -export interface FunderByAuthor { - funder_id?: string | null; - funder_name?: string | null; - publication_count: number; - author_position_count: AuthorPositionCount; - publication_ids: PublicationIdsByAuthorPosition; - publication_urls?: { [key: string]: string }; - publication_titles?: { [key: string]: string }; - publication_details?: { [key: string]: PublicationDetailByFunder }; + +export interface FunderByAuthor { + funder_id?: string | null; + funder_name?: string | null; + publication_count: number; + author_position_count: AuthorPositionCount; + publication_ids: PublicationIdsByAuthorPosition; + publication_urls?: { [key: string]: string; }; + publication_titles?: { [key: string]: string; }; + publication_details?: { [key: string]: PublicationDetailByFunder; }; } + diff --git a/webapp/src/app/api/model/fundersByAuthorResponse.ts b/webapp/src/app/api/model/fundersByAuthorResponse.ts index d6e0e02f..1286429e 100644 --- a/webapp/src/app/api/model/fundersByAuthorResponse.ts +++ b/webapp/src/app/api/model/fundersByAuthorResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { FunderByAuthor } from './funderByAuthor'; -export interface FundersByAuthorResponse { - author_id: string; - author_name?: string | null; - funder_count: number; - funders: Array; + +export interface FundersByAuthorResponse { + author_id: string; + author_name?: string | null; + funder_count: number; + funders: Array; } + diff --git a/webapp/src/app/api/model/fundingProject.ts b/webapp/src/app/api/model/fundingProject.ts index fb8204e3..a53c64f1 100644 --- a/webapp/src/app/api/model/fundingProject.ts +++ b/webapp/src/app/api/model/fundingProject.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,19 +9,23 @@ */ import { ProjectType } from './projectType'; -export interface FundingProject { - /** - * The type of the project. - */ - type: ProjectType; - /** - * The unique identifier of the project. - */ - id: string; - title?: string | null; - acronym?: string | null; - start_date?: string | null; - end_date?: string | null; - funding_amount?: number | null; + +export interface FundingProject { + /** + * The type of the project. + */ + type: ProjectType; + /** + * The unique identifier of the project. + */ + id: string; + title?: string | null; + acronym?: string | null; + start_date?: string | null; + end_date?: string | null; + funding_amount?: number | null; } -export namespace FundingProject {} +export namespace FundingProject { +} + + diff --git a/webapp/src/app/api/model/fundingProjectPage.ts b/webapp/src/app/api/model/fundingProjectPage.ts index e0996525..db43c9c4 100644 --- a/webapp/src/app/api/model/fundingProjectPage.ts +++ b/webapp/src/app/api/model/fundingProjectPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { FundingProject } from './fundingProject'; -export interface FundingProjectPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The funding projects on this page. - */ - elements?: Array; + +export interface FundingProjectPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The funding projects on this page. + */ + elements?: Array; } + diff --git a/webapp/src/app/api/model/fwci.ts b/webapp/src/app/api/model/fwci.ts index bd7eea69..0c0cf8de 100644 --- a/webapp/src/app/api/model/fwci.ts +++ b/webapp/src/app/api/model/fwci.ts @@ -1,14 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * Field-weighted Citation Impact, calculated as citations received / citations expected. */ -export interface Fwci {} +export interface Fwci { +} + diff --git a/webapp/src/app/api/model/groupByResult.ts b/webapp/src/app/api/model/groupByResult.ts index 98580663..68c51855 100644 --- a/webapp/src/app/api/model/groupByResult.ts +++ b/webapp/src/app/api/model/groupByResult.ts @@ -1,18 +1,20 @@ /** * 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. */ + /** * GroupByResult */ -export interface GroupByResult { - key?: string | null; - key_display_name?: string | null; - count?: number | null; +export interface GroupByResult { + key?: string | null; + key_display_name?: string | null; + count?: number | null; } + diff --git a/webapp/src/app/api/model/hTTPValidationError.ts b/webapp/src/app/api/model/hTTPValidationError.ts index c8e65c3e..f624be37 100644 --- a/webapp/src/app/api/model/hTTPValidationError.ts +++ b/webapp/src/app/api/model/hTTPValidationError.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,6 +9,8 @@ */ import { ValidationError } from './validationError'; -export interface HTTPValidationError { - detail?: Array; + +export interface HTTPValidationError { + detail?: Array; } + diff --git a/webapp/src/app/api/model/identityGrant.ts b/webapp/src/app/api/model/identityGrant.ts index 4bf172b8..9ec3fe50 100644 --- a/webapp/src/app/api/model/identityGrant.ts +++ b/webapp/src/app/api/model/identityGrant.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { AuthScope } from './authScope'; -export interface IdentityGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; + +export interface IdentityGrant { + token_type: string; + access_token: string; + expires_in: number; + scope: AuthScope; } + diff --git a/webapp/src/app/api/model/institution.ts b/webapp/src/app/api/model/institution.ts index c099fc57..6b1a5778 100644 --- a/webapp/src/app/api/model/institution.ts +++ b/webapp/src/app/api/model/institution.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -12,28 +12,30 @@ import { AuthorCountsByYearInner } from './authorCountsByYearInner'; import { AuthorSummaryStats } from './authorSummaryStats'; import { InstitutionGeo } from './institutionGeo'; + /** * A university, research organization, or other affiliation */ -export interface Institution { - id?: string | null; - ror?: string | null; - display_name?: string | null; - country_code?: string | null; - type?: string | null; - homepage_url?: string | null; - image_url?: string | null; - image_thumbnail_url?: string | null; - display_name_acronyms?: Array | null; - display_name_alternatives?: Array | null; - works_count?: number | null; - cited_by_count?: number | null; - summary_stats?: AuthorSummaryStats | null; - geo?: InstitutionGeo | null; - lineage?: Array | null; - ids?: InstitutionIds | null; - counts_by_year?: Array | null; - works_api_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Institution { + id?: string | null; + ror?: string | null; + display_name?: string | null; + country_code?: string | null; + type?: string | null; + homepage_url?: string | null; + image_url?: string | null; + image_thumbnail_url?: string | null; + display_name_acronyms?: Array | null; + display_name_alternatives?: Array | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + geo?: InstitutionGeo | null; + lineage?: Array | null; + ids?: InstitutionIds | null; + counts_by_year?: Array | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; } + diff --git a/webapp/src/app/api/model/institutionFunderSummary.ts b/webapp/src/app/api/model/institutionFunderSummary.ts index cf15754a..48d147b2 100644 --- a/webapp/src/app/api/model/institutionFunderSummary.ts +++ b/webapp/src/app/api/model/institutionFunderSummary.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,22 @@ */ import { ProjectType } from './projectType'; -export interface InstitutionFunderSummary { - /** - * The type of funding data (e.g., \'bund\', \'eu\', \'dfg\'). - */ - type: ProjectType; - /** - * A dictionary mapping years to total funding amounts for that year. - */ - funding_per_year?: object; - /** - * The average annual funding over the continuous period covered by the data. - */ - annual_average_over_period?: number; + +export interface InstitutionFunderSummary { + /** + * The type of funding data (e.g., \'bund\', \'eu\', \'dfg\'). + */ + type: ProjectType; + /** + * A dictionary mapping years to total funding amounts for that year. + */ + funding_per_year?: object; + /** + * The average annual funding over the continuous period covered by the data. + */ + annual_average_over_period?: number; } -export namespace InstitutionFunderSummary {} +export namespace InstitutionFunderSummary { +} + + diff --git a/webapp/src/app/api/model/institutionGeo.ts b/webapp/src/app/api/model/institutionGeo.ts index b438d37c..949b73f4 100644 --- a/webapp/src/app/api/model/institutionGeo.ts +++ b/webapp/src/app/api/model/institutionGeo.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,15 +10,17 @@ import { Latitude } from './latitude'; import { Longitude } from './longitude'; + /** * Location information: */ -export interface InstitutionGeo { - city?: string | null; - geonames_city_id?: string | null; - region?: string | null; - country_code?: string | null; - country?: string | null; - latitude?: Latitude | null; - longitude?: Longitude | null; +export interface InstitutionGeo { + city?: string | null; + geonames_city_id?: string | null; + region?: string | null; + country_code?: string | null; + country?: string | null; + latitude?: Latitude | null; + longitude?: Longitude | null; } + diff --git a/webapp/src/app/api/model/institutionIds.ts b/webapp/src/app/api/model/institutionIds.ts index fd952098..93d801e1 100644 --- a/webapp/src/app/api/model/institutionIds.ts +++ b/webapp/src/app/api/model/institutionIds.ts @@ -1,21 +1,23 @@ /** * 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. */ + /** * External identifiers: */ -export interface InstitutionIds { - openalex?: string | null; - ror?: string | null; - mag?: number | null; - grid?: string | null; - wikipedia?: string | null; - wikidata?: string | null; +export interface InstitutionIds { + openalex?: string | null; + ror?: string | null; + mag?: number | null; + grid?: string | null; + wikipedia?: string | null; + wikidata?: string | null; } + diff --git a/webapp/src/app/api/model/institutionInformation.ts b/webapp/src/app/api/model/institutionInformation.ts index 9e12986d..e287b0fa 100644 --- a/webapp/src/app/api/model/institutionInformation.ts +++ b/webapp/src/app/api/model/institutionInformation.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface InstitutionInformation { - /** - * The raw institution ID of the institution. - */ - raw_id: string; - /** - * The display name of the institution. - */ - display_name: string; + +export interface InstitutionInformation { + /** + * The raw institution ID of the institution. + */ + raw_id: string; + /** + * The display name of the institution. + */ + display_name: string; } + diff --git a/webapp/src/app/api/model/institutionNetworkNode.ts b/webapp/src/app/api/model/institutionNetworkNode.ts index 791645b7..a558a8cf 100644 --- a/webapp/src/app/api/model/institutionNetworkNode.ts +++ b/webapp/src/app/api/model/institutionNetworkNode.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,22 @@ */ import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; -export interface InstitutionNetworkNode { - /** - * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. - */ - raw_id: string; - /** - * The display name of the node. - */ - display_name: string; - /** - * The category of the node, either \'author\', \'institution\', or \'work\'. - */ - category: CollaborationNetworkNodeType; + +export interface InstitutionNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; } -export namespace InstitutionNetworkNode {} +export namespace InstitutionNetworkNode { +} + + diff --git a/webapp/src/app/api/model/institutionPage.ts b/webapp/src/app/api/model/institutionPage.ts index b7640651..01267ee3 100644 --- a/webapp/src/app/api/model/institutionPage.ts +++ b/webapp/src/app/api/model/institutionPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { Institution } from './institution'; -export interface InstitutionPage { - /** - * List of institutions in the current page. - */ - elements?: Array; - /** - * Current page number. (0-indexed) - */ - page?: number; - /** - * Number of institutions per page. - */ - size?: number; - /** - * Total number of institutions matching the search criteria. - */ - total?: number; + +export interface InstitutionPage { + /** + * List of institutions in the current page. + */ + elements?: Array; + /** + * Current page number. (0-indexed) + */ + page?: number; + /** + * Number of institutions per page. + */ + size?: number; + /** + * Total number of institutions matching the search criteria. + */ + total?: number; } + diff --git a/webapp/src/app/api/model/institutionsListResponse.ts b/webapp/src/app/api/model/institutionsListResponse.ts index 0ac2c185..908d72fe 100644 --- a/webapp/src/app/api/model/institutionsListResponse.ts +++ b/webapp/src/app/api/model/institutionsListResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,11 +11,13 @@ import { Meta } from './meta'; import { Institution } from './institution'; import { GroupByResult } from './groupByResult'; + /** * InstitutionsListResponse */ -export interface InstitutionsListResponse { - meta?: Meta | null; - results?: Array | null; - group_by?: Array | null; +export interface InstitutionsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; } + diff --git a/webapp/src/app/api/model/itemPage.ts b/webapp/src/app/api/model/itemPage.ts deleted file mode 100644 index 53a7140a..00000000 --- a/webapp/src/app/api/model/itemPage.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { Item } from './item'; - -export interface ItemPage { - /** - * The elements of the page. - */ - elements?: Array; - /** - * The page offset in elements. - */ - offset?: number; - /** - * The total number of elements. - */ - total?: number; - /** - * The page size in elements. - */ - size?: number; -} diff --git a/webapp/src/app/api/model/keywords.ts b/webapp/src/app/api/model/keywords.ts index d93b5fe0..c65c7600 100644 --- a/webapp/src/app/api/model/keywords.ts +++ b/webapp/src/app/api/model/keywords.ts @@ -1,14 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * Keywords associated with the project */ -export interface Keywords {} +export interface Keywords { +} + diff --git a/webapp/src/app/api/model/latitude.ts b/webapp/src/app/api/model/latitude.ts index 8fb58a9b..fe6b49aa 100644 --- a/webapp/src/app/api/model/latitude.ts +++ b/webapp/src/app/api/model/latitude.ts @@ -1,11 +1,14 @@ /** * 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 Latitude {} + +export interface Latitude { +} + diff --git a/webapp/src/app/api/model/location.ts b/webapp/src/app/api/model/location.ts index f92e2ffb..f207d751 100644 --- a/webapp/src/app/api/model/location.ts +++ b/webapp/src/app/api/model/location.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,17 +9,19 @@ */ import { DehydratedSource } from './dehydratedSource'; + /** * Where a work is hosted */ -export interface Location { - is_oa?: boolean | null; - landing_page_url?: string | null; - pdf_url?: string | null; - source?: DehydratedSource | null; - license?: string | null; - license_id?: string | null; - version?: string | null; - is_accepted?: boolean | null; - is_published?: boolean | null; +export interface Location { + is_oa?: boolean | null; + landing_page_url?: string | null; + pdf_url?: string | null; + source?: DehydratedSource | null; + license?: string | null; + license_id?: string | null; + version?: string | null; + is_accepted?: boolean | null; + is_published?: boolean | null; } + diff --git a/webapp/src/app/api/model/longitude.ts b/webapp/src/app/api/model/longitude.ts index d222a6ff..b0d39fce 100644 --- a/webapp/src/app/api/model/longitude.ts +++ b/webapp/src/app/api/model/longitude.ts @@ -1,11 +1,14 @@ /** * 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 Longitude {} + +export interface Longitude { +} + diff --git a/webapp/src/app/api/model/matchedOfficer.ts b/webapp/src/app/api/model/matchedOfficer.ts index a9f00939..4ad5c354 100644 --- a/webapp/src/app/api/model/matchedOfficer.ts +++ b/webapp/src/app/api/model/matchedOfficer.ts @@ -1,21 +1,23 @@ /** * 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 MatchedOfficer { - name?: string | null; - firstname?: string | null; - lastname?: string | null; - city?: string | null; - position?: string | null; - start_date?: string | null; - type?: string | null; - flag?: string | null; - is_matched_person?: boolean; + +export interface MatchedOfficer { + name?: string | null; + firstname?: string | null; + lastname?: string | null; + city?: string | null; + position?: string | null; + start_date?: string | null; + type?: string | null; + flag?: string | null; + is_matched_person?: boolean; } + diff --git a/webapp/src/app/api/model/mentionedPerson.ts b/webapp/src/app/api/model/mentionedPerson.ts index dad21357..6141b12a 100644 --- a/webapp/src/app/api/model/mentionedPerson.ts +++ b/webapp/src/app/api/model/mentionedPerson.ts @@ -1,15 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface MentionedPerson { - name: string; - is_ude?: boolean; - person_id?: string | null; + +export interface MentionedPerson { + name: string; + is_ude?: boolean; + person_id?: string | null; } + diff --git a/webapp/src/app/api/model/meta.ts b/webapp/src/app/api/model/meta.ts index f9f56443..8481062a 100644 --- a/webapp/src/app/api/model/meta.ts +++ b/webapp/src/app/api/model/meta.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,15 +9,17 @@ */ import { CostUsd } from './costUsd'; + /** * Metadata about the query results */ -export interface Meta { - count?: number | null; - db_response_time_ms?: number | null; - page?: number | null; - per_page?: number | null; - next_cursor?: string | null; - groups_count?: number | null; - cost_usd?: CostUsd | null; +export interface Meta { + count?: number | null; + db_response_time_ms?: number | null; + page?: number | null; + per_page?: number | null; + next_cursor?: string | null; + groups_count?: number | null; + cost_usd?: CostUsd | null; } + diff --git a/webapp/src/app/api/model/model2YrMeanCitedness.ts b/webapp/src/app/api/model/model2YrMeanCitedness.ts index d9c3d9df..67ec623c 100644 --- a/webapp/src/app/api/model/model2YrMeanCitedness.ts +++ b/webapp/src/app/api/model/model2YrMeanCitedness.ts @@ -1,11 +1,14 @@ /** * 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 Model2YrMeanCitedness {} + +export interface Model2YrMeanCitedness { +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 89f601cc..3690cd69 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -16,7 +16,11 @@ export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; +export * from './bodyChangePassword'; export * from './bodyCreateUser'; +export * from './bodyGetAccessToken'; +export * from './bodyLogin'; +export * from './bodyRequestOtk'; export * from './bundProject'; export * from './bundProjectDetails'; export * from './bundProjectPage'; @@ -58,9 +62,6 @@ export * from './institutionInformation'; export * from './institutionNetworkNode'; export * from './institutionPage'; export * from './institutionsListResponse'; -export * from './item'; -export * from './itemCreate'; -export * from './itemPage'; export * from './keywords'; export * from './latitude'; export * from './location'; diff --git a/webapp/src/app/api/model/newsArticle.ts b/webapp/src/app/api/model/newsArticle.ts index 3701eb25..4412dd66 100644 --- a/webapp/src/app/api/model/newsArticle.ts +++ b/webapp/src/app/api/model/newsArticle.ts @@ -1,19 +1,21 @@ /** * 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 NewsArticle { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; - relevant?: boolean | null; - snippet?: string | null; + +export interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + relevant?: boolean | null; + snippet?: string | null; } + diff --git a/webapp/src/app/api/model/newsArticleDetail.ts b/webapp/src/app/api/model/newsArticleDetail.ts index ed8903d0..c38406e2 100644 --- a/webapp/src/app/api/model/newsArticleDetail.ts +++ b/webapp/src/app/api/model/newsArticleDetail.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,14 +9,16 @@ */ import { MentionedPerson } from './mentionedPerson'; -export interface NewsArticleDetail { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; - relevant?: boolean | null; - snippet?: string | null; - full_content?: string | null; - authors?: Array; + +export interface NewsArticleDetail { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + relevant?: boolean | null; + snippet?: string | null; + full_content?: string | null; + authors?: Array; } + diff --git a/webapp/src/app/api/model/newsPage.ts b/webapp/src/app/api/model/newsPage.ts index bbb74122..da7f26ab 100644 --- a/webapp/src/app/api/model/newsPage.ts +++ b/webapp/src/app/api/model/newsPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { NewsArticle } from './newsArticle'; -export interface NewsPage { - total: number; - page: number; - page_size: number; - results: Array; + +export interface NewsPage { + total: number; + page: number; + page_size: number; + results: Array; } + diff --git a/webapp/src/app/api/model/openAccess.ts b/webapp/src/app/api/model/openAccess.ts index 40d7b1d0..32a4ddd9 100644 --- a/webapp/src/app/api/model/openAccess.ts +++ b/webapp/src/app/api/model/openAccess.ts @@ -1,19 +1,21 @@ /** * 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. */ + /** * Open access information */ -export interface OpenAccess { - is_oa?: boolean | null; - oa_status?: string | null; - oa_url?: string | null; - any_repository_has_fulltext?: boolean | null; +export interface OpenAccess { + is_oa?: boolean | null; + oa_status?: string | null; + oa_url?: string | null; + any_repository_has_fulltext?: boolean | null; } + diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index a6a3619c..a375ec6f 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -1,22 +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. */ -export interface PatentEntry { - patent_id: string; - source: string; - title?: string | null; - abstract?: string | null; - publication_date?: string | null; - publication_year?: string | null; - inventors?: Array; - assignees?: Array; - ipc?: Array; - country?: string | null; + +export interface PatentEntry { + patent_id: string; + source: string; + title?: string | null; + 'abstract'?: string | null; + publication_date?: string | null; + publication_year?: string | null; + inventors?: Array; + assignees?: Array; + ipc?: Array; + country?: string | null; } + diff --git a/webapp/src/app/api/model/patentsByAuthorResponse.ts b/webapp/src/app/api/model/patentsByAuthorResponse.ts index ed970c7a..eca819ed 100644 --- a/webapp/src/app/api/model/patentsByAuthorResponse.ts +++ b/webapp/src/app/api/model/patentsByAuthorResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { PatentEntry } from './patentEntry'; -export interface PatentsByAuthorResponse { - author_id: string; - author_name?: string | null; - patent_count: number; - patents: Array; + +export interface PatentsByAuthorResponse { + author_id: string; + author_name?: string | null; + patent_count: number; + patents: Array; } + diff --git a/webapp/src/app/api/model/personBio.ts b/webapp/src/app/api/model/personBio.ts index b060c9a9..f7291e6f 100644 --- a/webapp/src/app/api/model/personBio.ts +++ b/webapp/src/app/api/model/personBio.ts @@ -1,16 +1,18 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface PersonBio { - /** - * The generated biography. - */ - bio: string; + +export interface PersonBio { + /** + * The generated biography. + */ + bio: string; } + diff --git a/webapp/src/app/api/model/projectType.ts b/webapp/src/app/api/model/projectType.ts index 08df30c4..a01a743c 100644 --- a/webapp/src/app/api/model/projectType.ts +++ b/webapp/src/app/api/model/projectType.ts @@ -1,16 +1,18 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + export const ProjectType = { - Bund: 'bund', - Eu: 'eu', - Dfg: 'dfg', + Bund: 'bund', + Eu: 'eu', + Dfg: 'dfg' } as const; -export type ProjectType = (typeof ProjectType)[keyof typeof ProjectType]; +export type ProjectType = typeof ProjectType[keyof typeof ProjectType]; + diff --git a/webapp/src/app/api/model/projectsFilteringProperties.ts b/webapp/src/app/api/model/projectsFilteringProperties.ts index c0cebe63..7ce7cfc2 100644 --- a/webapp/src/app/api/model/projectsFilteringProperties.ts +++ b/webapp/src/app/api/model/projectsFilteringProperties.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,28 +11,32 @@ import { SortDirection } from './sortDirection'; import { ProjectsSortBy } from './projectsSortBy'; import { ProjectType } from './projectType'; -export interface ProjectsFilteringProperties { - /** - * The type of projects to filter by. - */ - project_type: ProjectType; - /** - * The page number for pagination. - */ - page: number; - /** - * The page size for pagination. - */ - size: number; - raw_oa_institution_id?: string | null; - query?: string | null; - /** - * The field to sort by. - */ - sort_by?: ProjectsSortBy; - /** - * The sort direction (asc or desc). - */ - sort_direction?: SortDirection; + +export interface ProjectsFilteringProperties { + /** + * The type of projects to filter by. + */ + project_type: ProjectType; + /** + * The page number for pagination. + */ + page: number; + /** + * The page size for pagination. + */ + size: number; + raw_oa_institution_id?: string | null; + query?: string | null; + /** + * The field to sort by. + */ + sort_by?: ProjectsSortBy; + /** + * The sort direction (asc or desc). + */ + sort_direction?: SortDirection; } -export namespace ProjectsFilteringProperties {} +export namespace ProjectsFilteringProperties { +} + + diff --git a/webapp/src/app/api/model/projectsSortBy.ts b/webapp/src/app/api/model/projectsSortBy.ts index 26400b22..79824096 100644 --- a/webapp/src/app/api/model/projectsSortBy.ts +++ b/webapp/src/app/api/model/projectsSortBy.ts @@ -1,18 +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 ProjectsSortBy = { - Title: 'title', - FundingStart: 'funding_start', - FundingEnd: 'funding_end', - FundingAmount: 'funding_amount', + Title: 'title', + FundingStart: 'funding_start', + FundingEnd: 'funding_end', + FundingAmount: 'funding_amount' } as const; -export type ProjectsSortBy = - (typeof ProjectsSortBy)[keyof typeof ProjectsSortBy]; +export type ProjectsSortBy = typeof ProjectsSortBy[keyof typeof ProjectsSortBy]; + diff --git a/webapp/src/app/api/model/publicationDetailByFunder.ts b/webapp/src/app/api/model/publicationDetailByFunder.ts index 0fd6b7c5..123ded7e 100644 --- a/webapp/src/app/api/model/publicationDetailByFunder.ts +++ b/webapp/src/app/api/model/publicationDetailByFunder.ts @@ -1,43 +1,45 @@ /** * 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 PublicationDetailByFunder { - id: string; - title: string; - abstract?: string | null; - doi?: string | null; - publication_year?: number | null; - publication_date?: string | null; - publication_type?: string | null; - language?: string | null; - publication_url?: string | null; - pdf_url?: string | null; - source_name?: string | null; - source_type?: string | null; - is_open_access?: boolean | null; - open_access_status?: string | null; - has_fulltext?: boolean | null; - license?: string | null; - cited_by_count?: number | null; - is_retracted?: boolean | null; - primary_topic?: string | null; - topic_field?: string | null; - topic_subfield?: string | null; - topic_domain?: string | null; - author_position?: string | null; - authors?: Array; - funder_names?: Array; - institutions?: Array; - countries?: Array; - topics?: Array; - keywords?: Array; - grant_labels?: Array; - counts_by_year?: Array; + +export interface PublicationDetailByFunder { + id: string; + title: string; + 'abstract'?: string | null; + doi?: string | null; + publication_year?: number | null; + publication_date?: string | null; + publication_type?: string | null; + language?: string | null; + publication_url?: string | null; + pdf_url?: string | null; + source_name?: string | null; + source_type?: string | null; + is_open_access?: boolean | null; + open_access_status?: string | null; + has_fulltext?: boolean | null; + license?: string | null; + cited_by_count?: number | null; + is_retracted?: boolean | null; + primary_topic?: string | null; + topic_field?: string | null; + topic_subfield?: string | null; + topic_domain?: string | null; + author_position?: string | null; + authors?: Array; + funder_names?: Array; + institutions?: Array; + countries?: Array; + topics?: Array; + keywords?: Array; + grant_labels?: Array; + counts_by_year?: Array; } + diff --git a/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts index d549f8ed..c35050ef 100644 --- a/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts +++ b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts @@ -1,16 +1,18 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface PublicationIdsByAuthorPosition { - first?: Array; - middle?: Array; - last?: Array; - unknown?: Array; + +export interface PublicationIdsByAuthorPosition { + first?: Array; + middle?: Array; + last?: Array; + unknown?: Array; } + diff --git a/webapp/src/app/api/model/publicationsByAuthorResponse.ts b/webapp/src/app/api/model/publicationsByAuthorResponse.ts index 35333880..5176fe39 100644 --- a/webapp/src/app/api/model/publicationsByAuthorResponse.ts +++ b/webapp/src/app/api/model/publicationsByAuthorResponse.ts @@ -1,19 +1,21 @@ /** * 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 PublicationsByAuthorResponse { - author_id: string; - page: number; - page_size: number; - total_works: number; - total: number; - results_count: number; - results: Array; + +export interface PublicationsByAuthorResponse { + author_id: string; + page: number; + page_size: number; + total_works: number; + total: number; + results_count: number; + results: Array; } + diff --git a/webapp/src/app/api/model/rankingResponse.ts b/webapp/src/app/api/model/rankingResponse.ts index 5be090a2..099ec660 100644 --- a/webapp/src/app/api/model/rankingResponse.ts +++ b/webapp/src/app/api/model/rankingResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,7 +10,9 @@ import { UniversityRanking } from './universityRanking'; import { UniversityTopicData } from './universityTopicData'; -export interface RankingResponse { - timeseries: Array; - rankings: Array; + +export interface RankingResponse { + timeseries: Array; + rankings: Array; } + diff --git a/webapp/src/app/api/model/score.ts b/webapp/src/app/api/model/score.ts index 5b0b5935..fac39735 100644 --- a/webapp/src/app/api/model/score.ts +++ b/webapp/src/app/api/model/score.ts @@ -1,11 +1,14 @@ /** * 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 Score {} + +export interface Score { +} + diff --git a/webapp/src/app/api/model/sortDirection.ts b/webapp/src/app/api/model/sortDirection.ts index 49933995..4f9362f2 100644 --- a/webapp/src/app/api/model/sortDirection.ts +++ b/webapp/src/app/api/model/sortDirection.ts @@ -1,15 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + export const SortDirection = { - Asc: 'asc', - Desc: 'desc', + Asc: 'asc', + Desc: 'desc' } as const; -export type SortDirection = (typeof SortDirection)[keyof typeof SortDirection]; +export type SortDirection = typeof SortDirection[keyof typeof SortDirection]; + diff --git a/webapp/src/app/api/model/topic.ts b/webapp/src/app/api/model/topic.ts index eaac16f6..9fc0ee63 100644 --- a/webapp/src/app/api/model/topic.ts +++ b/webapp/src/app/api/model/topic.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -12,21 +12,23 @@ import { TopicIds } from './topicIds'; import { TopicSubfield } from './topicSubfield'; import { TopicField } from './topicField'; + /** * A research topic automatically assigned to works */ -export interface Topic { - id?: string | null; - display_name?: string | null; - description?: string | null; - keywords?: Array | null; - subfield?: TopicSubfield | null; - field?: TopicField | null; - domain?: TopicDomain | null; - works_count?: number | null; - cited_by_count?: number | null; - ids?: TopicIds | null; - works_api_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Topic { + id?: string | null; + display_name?: string | null; + description?: string | null; + keywords?: Array | null; + subfield?: TopicSubfield | null; + field?: TopicField | null; + domain?: TopicDomain | null; + works_count?: number | null; + cited_by_count?: number | null; + ids?: TopicIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; } + diff --git a/webapp/src/app/api/model/topicCount.ts b/webapp/src/app/api/model/topicCount.ts index 1d2abe90..b929a51d 100644 --- a/webapp/src/app/api/model/topicCount.ts +++ b/webapp/src/app/api/model/topicCount.ts @@ -1,31 +1,33 @@ /** * 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 TopicCount { - id?: string | null; - /** - * The topic display name. - */ - name: string; - /** - * The number of occurrences. - */ - count?: number; - description?: string | null; - subfield_id?: string | null; - subfield_name?: string | null; - subfield_description?: string | null; - field_id?: string | null; - field_name?: string | null; - field_description?: string | null; - domain_id?: string | null; - domain_name?: string | null; - domain_description?: string | null; + +export interface TopicCount { + id?: string | null; + /** + * The topic display name. + */ + name: string; + /** + * The number of occurrences. + */ + count?: number; + description?: string | null; + subfield_id?: string | null; + subfield_name?: string | null; + subfield_description?: string | null; + field_id?: string | null; + field_name?: string | null; + field_description?: string | null; + domain_id?: string | null; + domain_name?: string | null; + domain_description?: string | null; } + diff --git a/webapp/src/app/api/model/topicDomain.ts b/webapp/src/app/api/model/topicDomain.ts index 573bef0d..652b1bca 100644 --- a/webapp/src/app/api/model/topicDomain.ts +++ b/webapp/src/app/api/model/topicDomain.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The domain (highest level) containing this topic: */ -export interface TopicDomain { - id?: string | null; - display_name?: string | null; +export interface TopicDomain { + id?: string | null; + display_name?: string | null; } + diff --git a/webapp/src/app/api/model/topicField.ts b/webapp/src/app/api/model/topicField.ts index cd7d08c8..c7351675 100644 --- a/webapp/src/app/api/model/topicField.ts +++ b/webapp/src/app/api/model/topicField.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The field (second level) containing this topic: */ -export interface TopicField { - id?: string | null; - display_name?: string | null; +export interface TopicField { + id?: string | null; + display_name?: string | null; } + diff --git a/webapp/src/app/api/model/topicIds.ts b/webapp/src/app/api/model/topicIds.ts index 22ca3343..4aa6738f 100644 --- a/webapp/src/app/api/model/topicIds.ts +++ b/webapp/src/app/api/model/topicIds.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * External identifiers: */ -export interface TopicIds { - openalex?: string | null; - wikipedia?: string | null; +export interface TopicIds { + openalex?: string | null; + wikipedia?: string | null; } + diff --git a/webapp/src/app/api/model/topicSubfield.ts b/webapp/src/app/api/model/topicSubfield.ts index 79f3c9c7..53d37842 100644 --- a/webapp/src/app/api/model/topicSubfield.ts +++ b/webapp/src/app/api/model/topicSubfield.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The subfield (third level) containing this topic: */ -export interface TopicSubfield { - id?: string | null; - display_name?: string | null; +export interface TopicSubfield { + id?: string | null; + display_name?: string | null; } + diff --git a/webapp/src/app/api/model/topics.ts b/webapp/src/app/api/model/topics.ts index cf40ff1d..44f0eb98 100644 --- a/webapp/src/app/api/model/topics.ts +++ b/webapp/src/app/api/model/topics.ts @@ -1,11 +1,14 @@ /** * 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 Topics {} + +export interface Topics { +} + diff --git a/webapp/src/app/api/model/topicsByTime.ts b/webapp/src/app/api/model/topicsByTime.ts index 007dc43d..8af7c9bb 100644 --- a/webapp/src/app/api/model/topicsByTime.ts +++ b/webapp/src/app/api/model/topicsByTime.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,25 +9,27 @@ */ import { TopicsByYear } from './topicsByYear'; -export interface TopicsByTime { - /** - * Topics grouped by year. - */ - elements?: Array; - /** - * The number of years. - */ - total?: number; - /** - * True if the timeline contains only a limited subset of the author\'s publications. - */ - is_limited?: boolean; - /** - * The number of publications used to build the timeline. - */ - used_publications?: number; - /** - * The total number of publications found for this author. - */ - total_publications?: number; + +export interface TopicsByTime { + /** + * Topics grouped by year. + */ + elements?: Array; + /** + * The number of years. + */ + total?: number; + /** + * True if the timeline contains only a limited subset of the author\'s publications. + */ + is_limited?: boolean; + /** + * The number of publications used to build the timeline. + */ + used_publications?: number; + /** + * The total number of publications found for this author. + */ + total_publications?: number; } + diff --git a/webapp/src/app/api/model/topicsByYear.ts b/webapp/src/app/api/model/topicsByYear.ts index bb2f1820..fded8da0 100644 --- a/webapp/src/app/api/model/topicsByYear.ts +++ b/webapp/src/app/api/model/topicsByYear.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,21 +9,23 @@ */ import { TopicCount } from './topicCount'; -export interface TopicsByYear { - /** - * The publication year. - */ - year: number; - /** - * The number of works in this year. - */ - publication_count?: number; - /** - * The topics in this year. - */ - topics?: Array; - /** - * The primary topics in this year. - */ - primary_topics?: Array; + +export interface TopicsByYear { + /** + * The publication year. + */ + year: number; + /** + * The number of works in this year. + */ + publication_count?: number; + /** + * The topics in this year. + */ + topics?: Array; + /** + * The primary topics in this year. + */ + primary_topics?: Array; } + diff --git a/webapp/src/app/api/model/topicsListResponse.ts b/webapp/src/app/api/model/topicsListResponse.ts index 058b45fd..43f21226 100644 --- a/webapp/src/app/api/model/topicsListResponse.ts +++ b/webapp/src/app/api/model/topicsListResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,11 +11,13 @@ import { Meta } from './meta'; import { GroupByResult } from './groupByResult'; import { Topic } from './topic'; + /** * TopicsListResponse */ -export interface TopicsListResponse { - meta?: Meta | null; - results?: Array | null; - group_by?: Array | null; +export interface TopicsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; } + diff --git a/webapp/src/app/api/model/universityRanking.ts b/webapp/src/app/api/model/universityRanking.ts index 5c9d0d05..3099e73e 100644 --- a/webapp/src/app/api/model/universityRanking.ts +++ b/webapp/src/app/api/model/universityRanking.ts @@ -1,27 +1,30 @@ /** * 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 UniversityRanking { - rank: number; - university: string; - publications: number; - citations: number; - growth_rate: number; - trend: UniversityRanking.TrendEnum; - is_top_mover: boolean; + +export interface UniversityRanking { + rank: number; + university: string; + publications: number; + citations: number; + growth_rate: number; + trend: UniversityRanking.TrendEnum; + is_top_mover: boolean; } export namespace UniversityRanking { - export const TrendEnum = { - Up: 'up', - Down: 'down', - Stable: 'stable', - } as const; - export type TrendEnum = (typeof TrendEnum)[keyof typeof TrendEnum]; + export const TrendEnum = { + Up: 'up', + Down: 'down', + Stable: 'stable' + } as const; + export type TrendEnum = typeof TrendEnum[keyof typeof TrendEnum]; } + + diff --git a/webapp/src/app/api/model/universityTopicData.ts b/webapp/src/app/api/model/universityTopicData.ts index f5436445..fc517b7c 100644 --- a/webapp/src/app/api/model/universityTopicData.ts +++ b/webapp/src/app/api/model/universityTopicData.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,17 +9,20 @@ */ import { YearlyData } from './yearlyData'; -export interface UniversityTopicData { - university: string; - topic: UniversityTopicData.TopicEnum; - yearly_data: Array; + +export interface UniversityTopicData { + university: string; + topic: UniversityTopicData.TopicEnum; + yearly_data: Array; } export namespace UniversityTopicData { - export const TopicEnum = { - ArtificialIntelligence: 'Artificial Intelligence', - QuantumComputing: 'Quantum Computing', - RenewableEnergy: 'Renewable Energy', - Biotechnology: 'Biotechnology', - } as const; - export type TopicEnum = (typeof TopicEnum)[keyof typeof TopicEnum]; + export const TopicEnum = { + ArtificialIntelligence: 'Artificial Intelligence', + QuantumComputing: 'Quantum Computing', + RenewableEnergy: 'Renewable Energy', + Biotechnology: 'Biotechnology' + } as const; + export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum]; } + + diff --git a/webapp/src/app/api/model/user.ts b/webapp/src/app/api/model/user.ts index 7e82821c..def604e1 100644 --- a/webapp/src/app/api/model/user.ts +++ b/webapp/src/app/api/model/user.ts @@ -1,43 +1,45 @@ /** * 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. */ + /** - * An entry in the user configuration file. + * An entry in the user configuration file. */ -export interface User { - /** - * The username of the user. - */ - username: string; - /** - * The password of the user. - */ - password: string; - /** - * The email of the user. - */ - email: string; - /** - * The account id of the user. - */ - account: number; - /** - * The organization id of the user. - */ - organization: number; - /** - * The organization name of the user. - */ - organization_name: string; - /** - * Indicates whether the user is a superadmin. - */ - superadmin?: boolean; +export interface User { + /** + * The username of the user. + */ + username: string; + /** + * The password of the user. + */ + password: string; + /** + * The email of the user. + */ + email: string; + /** + * The account id of the user. + */ + account: number; + /** + * The organization id of the user. + */ + organization: number; + /** + * The organization name of the user. + */ + organization_name: string; + /** + * Indicates whether the user is a superadmin. + */ + superadmin?: boolean; } + diff --git a/webapp/src/app/api/model/validationError.ts b/webapp/src/app/api/model/validationError.ts index 18cd1b61..bdbd57ad 100644 --- a/webapp/src/app/api/model/validationError.ts +++ b/webapp/src/app/api/model/validationError.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,8 +9,10 @@ */ import { ValidationErrorLocInner } from './validationErrorLocInner'; -export interface ValidationError { - loc: Array; - msg: string; - type: string; + +export interface ValidationError { + loc: Array; + msg: string; + type: string; } + diff --git a/webapp/src/app/api/model/validationErrorLocInner.ts b/webapp/src/app/api/model/validationErrorLocInner.ts index 3c1ffa29..d248a9b7 100644 --- a/webapp/src/app/api/model/validationErrorLocInner.ts +++ b/webapp/src/app/api/model/validationErrorLocInner.ts @@ -1,11 +1,14 @@ /** * 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 ValidationErrorLocInner {} + +export interface ValidationErrorLocInner { +} + diff --git a/webapp/src/app/api/model/value.ts b/webapp/src/app/api/model/value.ts index 016b21cb..a9fc79ba 100644 --- a/webapp/src/app/api/model/value.ts +++ b/webapp/src/app/api/model/value.ts @@ -1,11 +1,14 @@ /** * 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 Value {} + +export interface Value { +} + diff --git a/webapp/src/app/api/model/work.ts b/webapp/src/app/api/model/work.ts index 6c6ae99b..07d94a1c 100644 --- a/webapp/src/app/api/model/work.ts +++ b/webapp/src/app/api/model/work.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -24,46 +24,48 @@ import { WorkHasContent } from './workHasContent'; import { Location } from './location'; import { WorkBiblio } from './workBiblio'; + /** * A scholarly document (article, book, dataset, thesis, etc.) */ -export interface Work { - id?: string | null; - doi?: string | null; - title?: string | null; - display_name?: string | null; - publication_year?: number | null; - publication_date?: string | null; - type?: string | null; - language?: string | null; - cited_by_count?: number | null; - is_retracted?: boolean | null; - is_paratext?: boolean | null; - primary_location?: Location | null; - locations?: Array | null; - best_oa_location?: Location | null; - open_access?: OpenAccess | null; - authorships?: Array | null; - ids?: WorkIds | null; - biblio?: WorkBiblio | null; - abstract_inverted_index?: object | null; - referenced_works?: Array | null; - referenced_works_count?: number | null; - related_works?: Array | null; - topics?: Array | null; - primary_topic?: WorkTopic | null; - keywords?: Array | null; - funders?: Array | null; - awards?: Array | null; - fwci?: Fwci | null; - citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; - cited_by_percentile_year?: WorkCitedByPercentileYear | null; - counts_by_year?: Array | null; - sustainable_development_goals?: Array | null; - mesh?: Array | null; - indexed_in?: Array | null; - has_content?: WorkHasContent | null; - content_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Work { + id?: string | null; + doi?: string | null; + title?: string | null; + display_name?: string | null; + publication_year?: number | null; + publication_date?: string | null; + type?: string | null; + language?: string | null; + cited_by_count?: number | null; + is_retracted?: boolean | null; + is_paratext?: boolean | null; + primary_location?: Location | null; + locations?: Array | null; + best_oa_location?: Location | null; + open_access?: OpenAccess | null; + authorships?: Array | null; + ids?: WorkIds | null; + biblio?: WorkBiblio | null; + abstract_inverted_index?: object | null; + referenced_works?: Array | null; + referenced_works_count?: number | null; + related_works?: Array | null; + topics?: Array | null; + primary_topic?: WorkTopic | null; + keywords?: Array | null; + funders?: Array | null; + awards?: Array | null; + fwci?: Fwci | null; + citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; + cited_by_percentile_year?: WorkCitedByPercentileYear | null; + counts_by_year?: Array | null; + sustainable_development_goals?: Array | null; + mesh?: Array | null; + indexed_in?: Array | null; + has_content?: WorkHasContent | null; + content_url?: string | null; + created_date?: string | null; + updated_date?: string | null; } + diff --git a/webapp/src/app/api/model/workBiblio.ts b/webapp/src/app/api/model/workBiblio.ts index 65c0a34b..f6d7079b 100644 --- a/webapp/src/app/api/model/workBiblio.ts +++ b/webapp/src/app/api/model/workBiblio.ts @@ -1,19 +1,21 @@ /** * 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. */ + /** * Bibliographic info: `volume`, `issue`, `first_page`, `last_page`. */ -export interface WorkBiblio { - volume?: string | null; - issue?: string | null; - first_page?: string | null; - last_page?: string | null; +export interface WorkBiblio { + volume?: string | null; + issue?: string | null; + first_page?: string | null; + last_page?: string | null; } + diff --git a/webapp/src/app/api/model/workCitationNormalizedPercentile.ts b/webapp/src/app/api/model/workCitationNormalizedPercentile.ts index 4a2bc6d4..a587ddf6 100644 --- a/webapp/src/app/api/model/workCitationNormalizedPercentile.ts +++ b/webapp/src/app/api/model/workCitationNormalizedPercentile.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,11 +9,13 @@ */ import { Value } from './value'; + /** * Percentile of citation count normalized by work type, year, and subfield. Includes `value`, `is_in_top_1_percent`, `is_in_top_10_percent`. */ -export interface WorkCitationNormalizedPercentile { - value?: Value | null; - is_in_top_1_percent?: boolean | null; - is_in_top_10_percent?: boolean | null; +export interface WorkCitationNormalizedPercentile { + value?: Value | null; + is_in_top_1_percent?: boolean | null; + is_in_top_10_percent?: boolean | null; } + diff --git a/webapp/src/app/api/model/workCitedByPercentileYear.ts b/webapp/src/app/api/model/workCitedByPercentileYear.ts index 7bcd3c85..5257eb3b 100644 --- a/webapp/src/app/api/model/workCitedByPercentileYear.ts +++ b/webapp/src/app/api/model/workCitedByPercentileYear.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * Percentile rank compared to other works published in the same year. Contains `min` and `max`. */ -export interface WorkCitedByPercentileYear { - min?: number | null; - max?: number | null; +export interface WorkCitedByPercentileYear { + min?: number | null; + max?: number | null; } + diff --git a/webapp/src/app/api/model/workCountsByYearInner.ts b/webapp/src/app/api/model/workCountsByYearInner.ts index 496a11db..76d97d77 100644 --- a/webapp/src/app/api/model/workCountsByYearInner.ts +++ b/webapp/src/app/api/model/workCountsByYearInner.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * WorkCountsByYearInner */ -export interface WorkCountsByYearInner { - year?: number | null; - cited_by_count?: number | null; +export interface WorkCountsByYearInner { + year?: number | null; + cited_by_count?: number | null; } + diff --git a/webapp/src/app/api/model/workHasContent.ts b/webapp/src/app/api/model/workHasContent.ts index 76871238..44fbe446 100644 --- a/webapp/src/app/api/model/workHasContent.ts +++ b/webapp/src/app/api/model/workHasContent.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * Information about downloadable full-text content: */ -export interface WorkHasContent { - pdf?: boolean | null; - grobid_xml?: boolean | null; +export interface WorkHasContent { + pdf?: boolean | null; + grobid_xml?: boolean | null; } + diff --git a/webapp/src/app/api/model/workIds.ts b/webapp/src/app/api/model/workIds.ts index fe562e40..e8315250 100644 --- a/webapp/src/app/api/model/workIds.ts +++ b/webapp/src/app/api/model/workIds.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * External identifiers: `openalex`, `doi`, `mag`, `pmid`, `pmcid`. */ -export interface WorkIds { - openalex?: string | null; - doi?: string | null; - mag?: number | null; - pmid?: string | null; - pmcid?: string | null; +export interface WorkIds { + openalex?: string | null; + doi?: string | null; + mag?: number | null; + pmid?: string | null; + pmcid?: string | null; } + diff --git a/webapp/src/app/api/model/workKeyword.ts b/webapp/src/app/api/model/workKeyword.ts index 7270db25..c9c99afb 100644 --- a/webapp/src/app/api/model/workKeyword.ts +++ b/webapp/src/app/api/model/workKeyword.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,11 +9,13 @@ */ import { Score } from './score'; + /** * WorkKeyword */ -export interface WorkKeyword { - id?: string | null; - display_name?: string | null; - score?: Score | null; +export interface WorkKeyword { + id?: string | null; + display_name?: string | null; + score?: Score | null; } + diff --git a/webapp/src/app/api/model/workMeshInner.ts b/webapp/src/app/api/model/workMeshInner.ts index 36a0c569..40633524 100644 --- a/webapp/src/app/api/model/workMeshInner.ts +++ b/webapp/src/app/api/model/workMeshInner.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * WorkMeshInner */ -export interface WorkMeshInner { - descriptor_ui?: string | null; - descriptor_name?: string | null; - qualifier_ui?: string | null; - qualifier_name?: string | null; - is_major_topic?: boolean | null; +export interface WorkMeshInner { + descriptor_ui?: string | null; + descriptor_name?: string | null; + qualifier_ui?: string | null; + qualifier_name?: string | null; + is_major_topic?: boolean | null; } + diff --git a/webapp/src/app/api/model/workNetworkNode.ts b/webapp/src/app/api/model/workNetworkNode.ts index 445cd8ad..abc04a69 100644 --- a/webapp/src/app/api/model/workNetworkNode.ts +++ b/webapp/src/app/api/model/workNetworkNode.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,20 +10,24 @@ import { WorkTopicInformation } from './workTopicInformation'; import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; -export interface WorkNetworkNode { - /** - * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. - */ - raw_id: string; - /** - * The display name of the node. - */ - display_name: string; - /** - * The category of the node, either \'author\', \'institution\', or \'work\'. - */ - category: CollaborationNetworkNodeType; - publication_year: number | null; - work_topics_information: Set | null; + +export interface WorkNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; + publication_year: number | null; + work_topics_information: Set | null; } -export namespace WorkNetworkNode {} +export namespace WorkNetworkNode { +} + + diff --git a/webapp/src/app/api/model/workPage.ts b/webapp/src/app/api/model/workPage.ts index 285d2065..8490c3ab 100644 --- a/webapp/src/app/api/model/workPage.ts +++ b/webapp/src/app/api/model/workPage.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,25 +9,27 @@ */ import { Work } from './work'; -export interface WorkPage { - /** - * Total number of works matching the query - */ - total: number; - /** - * List of works on the current page - */ - elements: Array; - /** - * Offset of the current page - */ - offset: number; - /** - * Size of the current page - */ - size: number; - /** - * Indicates if the current page is the last page - */ - last_page: boolean; + +export interface WorkPage { + /** + * Total number of works matching the query + */ + total: number; + /** + * List of works on the current page + */ + elements: Array; + /** + * Offset of the current page + */ + offset: number; + /** + * Size of the current page + */ + size: number; + /** + * Indicates if the current page is the last page + */ + last_page: boolean; } + diff --git a/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts b/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts index 8bc67292..c9ecd00f 100644 --- a/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts +++ b/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,11 +9,13 @@ */ import { Score } from './score'; + /** * WorkSustainableDevelopmentGoalsInner */ -export interface WorkSustainableDevelopmentGoalsInner { - id?: string | null; - display_name?: string | null; - score?: Score | null; +export interface WorkSustainableDevelopmentGoalsInner { + id?: string | null; + display_name?: string | null; + score?: Score | null; } + diff --git a/webapp/src/app/api/model/workTopic.ts b/webapp/src/app/api/model/workTopic.ts index 4b326824..925ead4f 100644 --- a/webapp/src/app/api/model/workTopic.ts +++ b/webapp/src/app/api/model/workTopic.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -12,14 +12,16 @@ import { WorkTopicDomain } from './workTopicDomain'; import { WorkTopicSubfield } from './workTopicSubfield'; import { WorkTopicField } from './workTopicField'; + /** * WorkTopic */ -export interface WorkTopic { - id?: string | null; - display_name?: string | null; - score?: Score | null; - subfield?: WorkTopicSubfield | null; - field?: WorkTopicField | null; - domain?: WorkTopicDomain | null; +export interface WorkTopic { + id?: string | null; + display_name?: string | null; + score?: Score | null; + subfield?: WorkTopicSubfield | null; + field?: WorkTopicField | null; + domain?: WorkTopicDomain | null; } + diff --git a/webapp/src/app/api/model/workTopicDomain.ts b/webapp/src/app/api/model/workTopicDomain.ts index 13b227df..1a9879d4 100644 --- a/webapp/src/app/api/model/workTopicDomain.ts +++ b/webapp/src/app/api/model/workTopicDomain.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The parent [domain](/api-reference/domains) */ -export interface WorkTopicDomain { - id?: string | null; - display_name?: string | null; +export interface WorkTopicDomain { + id?: string | null; + display_name?: string | null; } + diff --git a/webapp/src/app/api/model/workTopicField.ts b/webapp/src/app/api/model/workTopicField.ts index 432b993e..1807cfc1 100644 --- a/webapp/src/app/api/model/workTopicField.ts +++ b/webapp/src/app/api/model/workTopicField.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The parent [field](/api-reference/fields) */ -export interface WorkTopicField { - id?: string | null; - display_name?: string | null; +export interface WorkTopicField { + id?: string | null; + display_name?: string | null; } + diff --git a/webapp/src/app/api/model/workTopicInformation.ts b/webapp/src/app/api/model/workTopicInformation.ts index 5dbbfc78..ca3b9454 100644 --- a/webapp/src/app/api/model/workTopicInformation.ts +++ b/webapp/src/app/api/model/workTopicInformation.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface WorkTopicInformation { - /** - * The ID of the topic. - */ - raw_topic_id: string; - /** - * The name of the topic. - */ - display_name: string; + +export interface WorkTopicInformation { + /** + * The ID of the topic. + */ + raw_topic_id: string; + /** + * The name of the topic. + */ + display_name: string; } + diff --git a/webapp/src/app/api/model/workTopicSubfield.ts b/webapp/src/app/api/model/workTopicSubfield.ts index 49c1155b..b6e7278a 100644 --- a/webapp/src/app/api/model/workTopicSubfield.ts +++ b/webapp/src/app/api/model/workTopicSubfield.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * The parent [subfield](/api-reference/subfields) */ -export interface WorkTopicSubfield { - id?: string | null; - display_name?: string | null; +export interface WorkTopicSubfield { + id?: string | null; + display_name?: string | null; } + diff --git a/webapp/src/app/api/model/worksFilterProperties.ts b/webapp/src/app/api/model/worksFilterProperties.ts index fd25fd26..bd6cc9a4 100644 --- a/webapp/src/app/api/model/worksFilterProperties.ts +++ b/webapp/src/app/api/model/worksFilterProperties.ts @@ -1,32 +1,34 @@ /** * 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 WorksFilterProperties { - /** - * The start publication year for the works to include in the collaboration network. - */ - start_year?: number; - /** - * The end publication year for the works to include in the collaboration network. - */ - end_year?: number; - /** - * The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included. - */ - allowed_topics?: Array; - /** - * The minimum number of contributors required for a work to be included in the collaboration network. - */ - min_contributors?: number; - /** - * The maximum number of contributors allowed for a work to be included in the collaboration network. - */ - max_contributors?: number; + +export interface WorksFilterProperties { + /** + * The start publication year for the works to include in the collaboration network. + */ + start_year?: number; + /** + * The end publication year for the works to include in the collaboration network. + */ + end_year?: number; + /** + * The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included. + */ + allowed_topics?: Array; + /** + * The minimum number of contributors required for a work to be included in the collaboration network. + */ + min_contributors?: number; + /** + * The maximum number of contributors allowed for a work to be included in the collaboration network. + */ + max_contributors?: number; } + diff --git a/webapp/src/app/api/model/worksListResponse.ts b/webapp/src/app/api/model/worksListResponse.ts index bc21a41b..a65d3849 100644 --- a/webapp/src/app/api/model/worksListResponse.ts +++ b/webapp/src/app/api/model/worksListResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,11 +11,13 @@ import { Meta } from './meta'; import { Work } from './work'; import { GroupByResult } from './groupByResult'; + /** * WorksListResponse */ -export interface WorksListResponse { - meta?: Meta | null; - results?: Array | null; - group_by?: Array | null; +export interface WorksListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; } + diff --git a/webapp/src/app/api/model/yearlyData.ts b/webapp/src/app/api/model/yearlyData.ts index d473f13e..3272805e 100644 --- a/webapp/src/app/api/model/yearlyData.ts +++ b/webapp/src/app/api/model/yearlyData.ts @@ -1,15 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface YearlyData { - year: number; - publications: number; - citations: number; + +export interface YearlyData { + year: number; + publications: number; + citations: number; } + diff --git a/webapp/src/app/api/param.ts b/webapp/src/app/api/param.ts index 486c804e..78a2d20a 100644 --- a/webapp/src/app/api/param.ts +++ b/webapp/src/app/api/param.ts @@ -8,7 +8,8 @@ export type StandardParamStyle = | 'simple' | 'spaceDelimited' | 'pipeDelimited' - | 'deepObject'; + | 'deepObject' + ; /** * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. @@ -24,12 +25,13 @@ export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; * Standard types as defined in OpenAPI Specification: Data Types */ export type StandardDataType = - | 'integer' - | 'number' - | 'boolean' - | 'string' - | 'object' - | 'array'; + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; /** * Standard {@link DataType}s plus your own types/classes. @@ -40,15 +42,16 @@ export type DataType = StandardDataType | string; * Standard formats as defined in OpenAPI Specification: Data Types */ export type StandardDataFormat = - | 'int32' - | 'int64' - | 'float' - | 'double' - | 'byte' - | 'binary' - | 'date' - | 'date-time' - | 'password'; + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; export type DataFormat = StandardDataFormat | string; @@ -59,7 +62,7 @@ export interface Param { name: string; value: unknown; in: ParamLocation; - style: ParamStyle; + style: ParamStyle, explode: boolean; dataType: DataType; dataFormat: DataFormat | undefined; diff --git a/webapp/src/app/api/provide-api.ts b/webapp/src/app/api/provide-api.ts index 960132f8..19c762ac 100644 --- a/webapp/src/app/api/provide-api.ts +++ b/webapp/src/app/api/provide-api.ts @@ -1,17 +1,15 @@ -import { EnvironmentProviders, makeEnvironmentProviders } from '@angular/core'; +import { EnvironmentProviders, makeEnvironmentProviders } from "@angular/core"; import { Configuration, ConfigurationParameters } from './configuration'; import { BASE_PATH } from './variables'; // Returns the service class providers, to be used in the [ApplicationConfig](https://angular.dev/api/core/ApplicationConfig). -export function provideApi( - configOrBasePath: string | ConfigurationParameters, -): EnvironmentProviders { - return makeEnvironmentProviders([ - typeof configOrBasePath === 'string' - ? { provide: BASE_PATH, useValue: configOrBasePath } - : { - provide: Configuration, - useValue: new Configuration({ ...configOrBasePath }), - }, - ]); -} +export function provideApi(configOrBasePath: string | ConfigurationParameters): EnvironmentProviders { + return makeEnvironmentProviders([ + typeof configOrBasePath === "string" + ? { provide: BASE_PATH, useValue: configOrBasePath } + : { + provide: Configuration, + useValue: new Configuration({ ...configOrBasePath }), + }, + ]); +} \ No newline at end of file diff --git a/webapp/src/app/api/variables.ts b/webapp/src/app/api/variables.ts index 2277a9cc..6fe58549 100644 --- a/webapp/src/app/api/variables.ts +++ b/webapp/src/app/api/variables.ts @@ -2,8 +2,8 @@ import { InjectionToken } from '@angular/core'; export const BASE_PATH = new InjectionToken('basePath'); export const COLLECTION_FORMATS = { - csv: ',', - tsv: ' ', - ssv: ' ', - pipes: '|', -}; + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 24fd129f..9f1f73aa 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -1,4 +1,4 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component, inject, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup, @@ -14,6 +14,7 @@ import { CommonModule } from '@angular/common'; import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; +import { AuthService } from '../../api'; @Component({ selector: 'app-app-login', @@ -53,6 +54,8 @@ export class AppLoginComponent implements OnInit, OnDestroy { protected snackBar: MatSnackBar, ) {} + private readonly authService = inject(AuthService); + ngOnInit(): void { this.subscription = this.credentialService.validating.subscribe( (validating) => { diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index ac649afd..e4024263 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -8,13 +8,16 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { (req.method == 'POST' && (req.url.endsWith('/auth/id') || req.url.endsWith('/auth/access') || - req.url.endsWith('/inse-account/create'))) || + req.url.endsWith('/inse-account/create') || + req.url.endsWith('/auth/v2/request-otk'))) || req.url.endsWith('/institutions/autocomplete') ) { return next(req); } else { const credentialService = inject(CredentialService); const tokenProvider = credentialService.getBearerToken(); + console.log("Intercepting request to:", req.url, "with method:", req.method); + return tokenProvider.pipe( switchMap((response) => { if (response == undefined) { From 91ec7d841c8e1feed3a8639b799c19502b10c909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 25 Jun 2026 17:33:24 +0200 Subject: [PATCH 09/31] Added token type to JWT payload --- service/src/main/inse/auth/model.py | 6 +++--- service/src/main/inse/auth/service.py | 29 +++++++++++++++++++------- webapp/src/app/api/api/auth.service.ts | 15 ++++--------- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 43408c69..b5c0d47a 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -15,9 +15,9 @@ class UserRole(StrEnum): class TokenType(StrEnum): - ID_TOKEN = "ID_TOKEN" - REFRESH_TOKEN = "REFRESH_TOKEN" - ACCESS_TOKEN = "ACCESS_TOKEN" + ID_TOKEN = "ID" + REFRESH_TOKEN = "REFRESH" + ACCESS_TOKEN = "ACCESS" class Durable(SQLModel): diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 1c6be36c..14da4395 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -9,7 +9,7 @@ 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, Header, Request, Response, status +from fastapi import Depends, HTTPException, Request, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from inse.auth.model import ( AccessToken, @@ -18,6 +18,7 @@ from inse.auth.model import ( Organization, RefreshToken, Secret, + TokenType, UserRole, ) from inse.config import get_settings @@ -44,7 +45,7 @@ settings = get_settings() logger = logging.getLogger(__name__) -security_scheme = HTTPBearer(auto_error=False) +security_scheme = HTTPBearer() _password_hasher = PasswordHasher() @@ -668,7 +669,9 @@ def _refresh_access_token( USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash, } return _build_token( - payload=access_payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES + payload=access_payload, + expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES, + token_type=TokenType.ACCESS_TOKEN, ) @@ -690,7 +693,11 @@ def _build_id_token(response: Response, real_account_id: uuid.UUID, epoch: int) EPOCH_KEY: epoch, USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } - return _build_token(payload=payload, expiration_min=ID_TOKEN_EXPIRATION_MINUTES) + return _build_token( + payload=payload, + expiration_min=ID_TOKEN_EXPIRATION_MINUTES, + token_type=TokenType.ID_TOKEN, + ) def _build_action_tokens( @@ -710,20 +717,27 @@ def _build_action_tokens( return { "access_token": _build_token( - payload=payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES + payload=payload, + expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES, + token_type=TokenType.ACCESS_TOKEN, ), "refresh_token": _build_token( - payload=payload, expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES + payload=payload, + expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES, + token_type=TokenType.REFRESH_TOKEN, ), } -def _build_token(payload: Dict[str, Any], expiration_min: int) -> str: +def _build_token( + payload: Dict[str, Any], expiration_min: int, 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_min (int): The expiration time in minutes. + token_type (TokenType): The type of the token to build. Returns: str: The encoded JWT token. @@ -736,6 +750,7 @@ def _build_token(payload: Dict[str, Any], expiration_min: int) -> str: "iss": settings.token_issuer_id, "iat": now, "nbf": now, + "type": token_type.value, } ) if not settings.token_hmac_key: diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 24618227..d3174504 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -116,26 +116,19 @@ export class AuthService extends BaseService { * Get Access Token * Retrieve an access token for the authenticated user. * @endpoint post /api/auth/v2/access - * @param authorization * @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(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<{ [key: string]: string | null; }>; - public getAccessToken(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(authorization: string, bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorization === null || authorization === undefined) { - throw new Error('Required parameter authorization was null or undefined when calling getAccessToken.'); - } + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<{ [key: string]: string | null; }>; + 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; - if (authorization !== undefined && authorization !== null) { - localVarHeaders = localVarHeaders.set('Authorization', String(authorization)); - } // authentication (HTTPBearer) required localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); From 653dcb0a149054fb1b9f3c4fb825446e85aa3c50 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 26 Jun 2026 00:27:58 +0200 Subject: [PATCH 10/31] Log OTK code for development testing --- service/src/main/inse/auth/service.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 14da4395..3c390c8c 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -203,11 +203,21 @@ def request_otk(session: Session, email: str, password: str): session.commit() - logger.info( - "Saved OTK for account %s with expiration at %s", account.id, expires_at - ) + if settings.environment == "prod": + logger.info( + "Saved OTK for account %s with expiration at %s", + account.id, + expires_at, + ) + else: + logger.info( + "OTK code for account %s: %s, expires at %s", + account.id, + otk_code, + expires_at, + ) - return {"status": "ok"} + return {"status": "ok", "account_id": str(account.id)} def login(session: Session, response: Response, account_id: uuid.UUID, email_code: str): From 901cca5eb97e97faf82b1cbf06e3287fb06943d3 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Fri, 26 Jun 2026 10:31:20 +0200 Subject: [PATCH 11/31] connect front to back --- .../main/inse/account_management/__init__.py | 1 + .../src/main/inse/account_management/model.py | 51 +++ .../main/inse/account_management/router.py | 125 +++++++ .../main/inse/account_management/service.py | 311 ++++++++++++++++++ service/src/main/inse/auth/service.py | 4 +- service/src/main/inse/main.py | 2 + webapp/package.json | 2 +- webapp/src/app/app.config.ts | 6 +- webapp/src/app/app.routes.ts | 8 + .../accounts/account-dialog.component.html | 71 ++++ .../accounts/account-dialog.component.scss | 22 ++ .../accounts/account-dialog.component.ts | 123 +++++++ .../modules/accounts/accounts.component.html | 140 ++++++++ .../modules/accounts/accounts.component.scss | 147 +++++++++ .../modules/accounts/accounts.component.ts | 243 ++++++++++++++ .../modules/app-login/app-login.component.ts | 107 ++++-- .../error-page/error-page.component.ts | 4 +- .../authentication.interceptor.ts | 5 +- .../services/account-management.service.ts | 117 +++++++ .../app/shared/services/credential.service.ts | 252 ++++++++++++-- .../ui/app-layout/app-layout.component.html | 9 + .../ui/app-layout/app-layout.component.scss | 20 ++ .../ui/app-layout/app-layout.component.ts | 7 + .../shared/ui/app-menu/app-menu.component.ts | 6 + webapp/src/proxy.conf.json | 17 +- 25 files changed, 1736 insertions(+), 64 deletions(-) create mode 100644 service/src/main/inse/account_management/__init__.py create mode 100644 service/src/main/inse/account_management/model.py create mode 100644 service/src/main/inse/account_management/router.py create mode 100644 service/src/main/inse/account_management/service.py create mode 100644 webapp/src/app/modules/accounts/account-dialog.component.html create mode 100644 webapp/src/app/modules/accounts/account-dialog.component.scss create mode 100644 webapp/src/app/modules/accounts/account-dialog.component.ts create mode 100644 webapp/src/app/modules/accounts/accounts.component.html create mode 100644 webapp/src/app/modules/accounts/accounts.component.scss create mode 100644 webapp/src/app/modules/accounts/accounts.component.ts create mode 100644 webapp/src/app/shared/services/account-management.service.ts diff --git a/service/src/main/inse/account_management/__init__.py b/service/src/main/inse/account_management/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/service/src/main/inse/account_management/__init__.py @@ -0,0 +1 @@ + diff --git a/service/src/main/inse/account_management/model.py b/service/src/main/inse/account_management/model.py new file mode 100644 index 00000000..2bb7613d --- /dev/null +++ b/service/src/main/inse/account_management/model.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.py b/service/src/main/inse/account_management/router.py new file mode 100644 index 00000000..82781fb0 --- /dev/null +++ b/service/src/main/inse/account_management/router.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.py b/service/src/main/inse/account_management/service.py new file mode 100644 index 00000000..5ef45372 --- /dev/null +++ b/service/src/main/inse/account_management/service.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/service.py b/service/src/main/inse/auth/service.py index 3c390c8c..c772012f 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -4,6 +4,8 @@ import json import secrets import uuid import logging +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText from typing import Annotated, Any, Dict, Literal, Optional import jwt @@ -140,7 +142,6 @@ def _verify_password(password: str, password_hash: str) -> bool: 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. @@ -183,6 +184,7 @@ def request_otk(session: Session, email: str, password: str): ) otk_code = f"{secrets.randbelow(1_000_000):06d}" + print(otk_code) secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first() diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index e1030d0e..71d27db6 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -29,6 +29,7 @@ from inse.news.service import router as news_service_router from inse.patents.service import router as patents_service_router from inse.auth.router import router as auth_router +from inse.account_management.router import router as account_management_router from inse.institutions.router import router as institutions_router @@ -80,6 +81,7 @@ app.include_router(projects_router) app.include_router(service_router) app.include_router(auth_router) +app.include_router(account_management_router) app.add_middleware( ETagCacheMiddleware, diff --git a/webapp/package.json b/webapp/package.json index 7c6bbb36..0ac6a13e 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "scripts": { "ng": "ng", - "start": "ng serve", + "start": "ng serve --proxy-config src/proxy.conf.json", "build": "ng build", "generate:api": "openapi-generator-cli generate --generator-key inse-service", "watch": "ng build --watch --configuration development", diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 0325060b..1c579be1 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -22,6 +22,7 @@ import { MatPaginatorIntl } from '@angular/material/paginator'; import { PaginatorIntl } from './shared/utils/paginatorIntl'; import { provideEchartsCore } from 'ngx-echarts'; import { ErrorService } from './shared/services/error.service'; +import { provideApi } from './api/provide-api'; registerLocaleData(locale); @@ -72,7 +73,10 @@ export const appConfig: ApplicationConfig = { }), ), provideHttpClient(withInterceptors([authenticationInterceptor])), - // provideApi('/inse-service'), + provideApi({ + basePath: '/inse-webapp', + withCredentials: true, + }), provideAnimationsAsync(), provideEchartsCore({ echarts: () => import('echarts') }), ], diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a7d8b279..1204da01 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -90,6 +90,14 @@ export const routes: Routes = [ loadComponent: () => import('./modules/news/news.component').then((mod) => mod.NewsComponent), }, + { + path: 'accounts', + canActivate: [userGuard], + loadComponent: () => + import('./modules/accounts/accounts.component').then( + (mod) => mod.AccountsComponent, + ), + }, { path: 'news/:id', canActivate: [userGuard], diff --git a/webapp/src/app/modules/accounts/account-dialog.component.html b/webapp/src/app/modules/accounts/account-dialog.component.html new file mode 100644 index 00000000..0e08dbc8 --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component.html @@ -0,0 +1,71 @@ +

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

+ + + + + + + + + diff --git a/webapp/src/app/modules/accounts/account-dialog.component.scss b/webapp/src/app/modules/accounts/account-dialog.component.scss new file mode 100644 index 00000000..ccc5f64e --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component.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.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts new file mode 100644 index 00000000..784a2474 --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -0,0 +1,123 @@ +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; + } + + this.dialogRef.close({ + mode: 'edit', + accountId: this.data.account!.id, + payload: { + email: value.email ?? '', + name: value.name ?? '', + role: value.role ?? 'USER', + organization_id: value.organizationId ?? '', + password: value.password || undefined, + }, + }); + } + + protected close(): void { + this.dialogRef.close(undefined); + } +} diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html new file mode 100644 index 00000000..f9610b4e --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -0,0 +1,140 @@ +
+ + +
+ + Name oder E-Mail + + + + @if (credentialService.superadmin | async) { + + 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.scss b/webapp/src/app/modules/accounts/accounts.component.scss new file mode 100644 index 00000000..53149e49 --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component.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.ts b/webapp/src/app/modules/accounts/accounts.component.ts new file mode 100644 index 00000000..dc99bd2e --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -0,0 +1,243 @@ +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 readonly roles: AccountRole[] = [ + 'SUPER_ADMIN', + 'ADMIN', + '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.superadmin.value, + roles: this.roles, + }, + }); + + 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.superadmin.value) { + return true; + } + + return ( + this.credentialService.universityadmin.value && + (account.role === 'MANAGER' || account.role === 'USER') + ); + } +} diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 547068a7..eecd2512 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -1,4 +1,4 @@ -import { Component, inject, OnDestroy, OnInit } from '@angular/core'; +import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup, @@ -11,10 +11,10 @@ import { MatInputModule } from '@angular/material/input'; import { CredentialService } from '../../shared/services/credential.service'; import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; -import { Subscription } from 'rxjs'; +import { finalize, Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; -import { AuthService } from '../../api'; +import { HttpErrorResponse } from '@angular/common/http'; type LoginStep = 'credentials' | 'otk'; @@ -58,6 +58,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { subscription?: Subscription; private countdownInterval?: ReturnType; + private accountId?: string; constructor( protected credentialService: CredentialService, @@ -65,8 +66,6 @@ export class AppLoginComponent implements OnInit, OnDestroy { protected snackBar: MatSnackBar, ) {} - private readonly authService = inject(AuthService); - ngOnInit(): void { this.subscription = this.credentialService.validating.subscribe( (validating) => { @@ -80,7 +79,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { } }, ); - if (!this.credentialService.validating) { + if (!this.credentialService.validating.value) { this.checkEnter(); } } @@ -108,16 +107,42 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.isSubmitting = true; this.credentialsForm.disable(); - setTimeout(() => { - this.isSubmitting = false; - this.credentialsForm.enable(); - this.currentStep = 'otk'; - this.otkForm.reset(); - this.startCountdown(); - this.snackBar.open('OTK-Code wurde an die E-Mail-Adresse gesendet.', 'OK', { - duration: 4000, + const email = this.credentialsForm.controls.email.value ?? ''; + const password = this.credentialsForm.controls.password.value ?? ''; + + this.credentialService + .requestOtk(email, password) + .pipe( + finalize(() => { + this.isSubmitting = false; + this.credentialsForm.enable(); + }), + ) + .subscribe({ + next: (accountId) => { + if (!accountId) { + return; + } + + this.accountId = accountId; + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open( + 'OTK-Code wurde an die E-Mail-Adresse gesendet.', + 'OK', + { + duration: 4000, + }, + ); + }, + error: (error: HttpErrorResponse) => { + this.credentialService.logoutAcount(); + this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { + duration: 5000, + }); + }, }); - }, 450); } resendCode() { @@ -143,22 +168,46 @@ export class AppLoginComponent implements OnInit, OnDestroy { return; } - this.isSubmitting = true; - this.otkForm.disable(); - - setTimeout(() => { - this.isSubmitting = false; - this.otkForm.enable(); + if (!this.accountId) { this.snackBar.open( - 'Backend-Anbindung folgt: login(emailCode) wird hier ausgeführt.', + 'Bitte fordere zuerst einen neuen Code an.', 'OK', { duration: 5000 }, ); - }, 450); + return; + } + + this.isSubmitting = true; + this.otkForm.disable(); + + const email = this.credentialsForm.controls.email.value ?? ''; + const code = this.otkForm.controls.code.value ?? ''; + + this.credentialService + .loginWithOtk(this.accountId, email, code) + .pipe( + finalize(() => { + this.isSubmitting = false; + this.otkForm.enable(); + }), + ) + .subscribe({ + next: () => { + this.stopCountdown(); + this.router.navigate(['/dashboard']); + }, + error: (error: HttpErrorResponse) => { + this.credentialService.logoutAcount(); + this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { + duration: 5000, + }); + }, + }); } editCredentials() { this.currentStep = 'credentials'; + this.accountId = undefined; this.stopCountdown(); this.otkForm.reset(); } @@ -191,4 +240,16 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.codeExpiresIn = 0; } } + + private getLoginErrorMessage(error: HttpErrorResponse): string { + if (error.status === 401) { + return 'E-Mail, Passwort oder OTK-Code ist ungültig.'; + } + + if (error.status === 403) { + return 'Dieses Konto ist nicht für die Anmeldung freigeschaltet.'; + } + + return 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.'; + } } diff --git a/webapp/src/app/modules/error-page/error-page.component.ts b/webapp/src/app/modules/error-page/error-page.component.ts index 26acf5ee..1315396c 100644 --- a/webapp/src/app/modules/error-page/error-page.component.ts +++ b/webapp/src/app/modules/error-page/error-page.component.ts @@ -1,4 +1,3 @@ -import { Location } from '@angular/common'; import { Component, input, OnInit, signal, inject } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; @@ -28,7 +27,6 @@ export class ErrorPageComponent implements OnInit { isDetailsOpen = signal(false); - private readonly location = inject(Location); private readonly errorService = inject(ErrorService); ngOnInit() { @@ -53,6 +51,6 @@ export class ErrorPageComponent implements OnInit { } goBack() { - this.location.back(); + window.history.back(); } } diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index e4024263..6cbac0b4 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -8,6 +8,10 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { (req.method == 'POST' && (req.url.endsWith('/auth/id') || req.url.endsWith('/auth/access') || + req.url.endsWith('/api/auth/v2/request-otk') || + req.url.endsWith('/api/auth/v2/login') || + req.url.endsWith('/api/auth/v2/access') || + req.url.endsWith('/api/auth/v2/refresh') || req.url.endsWith('/inse-account/create') || req.url.endsWith('/auth/v2/request-otk'))) || req.url.endsWith('/institutions/autocomplete') @@ -16,7 +20,6 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { } else { const credentialService = inject(CredentialService); const tokenProvider = credentialService.getBearerToken(); - console.log("Intercepting request to:", req.url, "with method:", req.method); return tokenProvider.pipe( switchMap((response) => { diff --git a/webapp/src/app/shared/services/account-management.service.ts b/webapp/src/app/shared/services/account-management.service.ts new file mode 100644 index 00000000..bc64586f --- /dev/null +++ b/webapp/src/app/shared/services/account-management.service.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/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index a6963764..ce13f616 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,17 +1,20 @@ import { Injectable, inject } from '@angular/core'; import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman -import { Observable, of } from 'rxjs'; // review +import { Observable, of, switchMap, tap, throwError } from 'rxjs'; // review import { BehaviorSubject } from 'rxjs'; //review import { + AuthService, + Configuration, INSEAccountServiceService, IdentityGrant as ApiIdentityGrant, AccessGrant as ApiAccessGrant, } from '../../api'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; export interface AuthAccount { - i: number; + i: string; l: string; - o: number; + o: string; e: string; on: string; } @@ -41,11 +44,14 @@ export interface AccessGrant { interface TimedIdentityGrant { grant: IdentityGrant; expiration: number; + accountId: string; } interface TimedAccessGrant { grant: AccessGrant; expiration: number; + realAccountId: string; + effectiveAccountId: string; } @Injectable({ @@ -53,6 +59,9 @@ interface TimedAccessGrant { }) export class CredentialService { private accountService = inject(INSEAccountServiceService); + private authService = inject(AuthService); + private httpClient = inject(HttpClient); + private apiConfiguration = inject(Configuration, { optional: true }); private static readonly KEY_GRANT = 'grant'; @@ -60,12 +69,15 @@ export class CredentialService { public readonly authenticated = new BehaviorSubject(false); public readonly superadmin = new BehaviorSubject(false); public readonly universityadmin = new BehaviorSubject(false); - public readonly organization = new BehaviorSubject( + public readonly organization = new BehaviorSubject( undefined, ); public readonly login = new BehaviorSubject(''); public readonly email = new BehaviorSubject(''); public readonly organizationName = new BehaviorSubject(''); + public readonly impersonating = new BehaviorSubject(false); + public readonly realAccountId = new BehaviorSubject(''); + public readonly effectiveAccountId = new BehaviorSubject(''); private readonly identityToken = new BehaviorSubject< TimedIdentityGrant | undefined @@ -81,16 +93,22 @@ export class CredentialService { if (token) { const r = token.grant.scope.r as string[]; this.superadmin.next(r.includes('SUPER_ADMIN')); - this.universityadmin.next(r.includes('UNI_ADMIN')); + this.universityadmin.next(r.includes('UNI_ADMIN') || r.includes('ADMIN')); this.login.next(token.grant.scope.a?.l ?? ''); this.email.next(token.grant.scope.a?.e ?? ''); this.organizationName.next(token.grant.scope.a?.on ?? ''); + this.impersonating.next(token.realAccountId !== token.effectiveAccountId); + this.realAccountId.next(token.realAccountId); + this.effectiveAccountId.next(token.effectiveAccountId); } else { this.superadmin.next(false); this.universityadmin.next(false); this.login.next(''); this.email.next(''); this.organizationName.next(''); + this.impersonating.next(false); + this.realAccountId.next(''); + this.effectiveAccountId.next(''); } }); const data = localStorage.getItem(CredentialService.KEY_GRANT); @@ -102,6 +120,67 @@ export class CredentialService { } } + public requestOtk(email: string, password: string): Observable { + const request = ++this.request; + this.validating.next(true); + this.authenticated.next(false); + this.organization.next(undefined); + this.superadmin.next(false); + this.universityadmin.next(false); + this.identityToken.next(undefined); + this.accessToken.next(undefined); + + return this.authService + .requestOtk({ email: email.trim().toLowerCase(), password }) + .pipe( + map((response: { account_id?: string }) => { + if (this.request != request) return ''; + this.validating.next(false); + return response.account_id ?? ''; + }), + ); + } + + public loginWithOtk( + accountId: string, + email: string, + emailCode: string, + ): Observable { + const request = ++this.request; + this.validating.next(true); + this.authenticated.next(false); + this.organization.next(undefined); + this.superadmin.next(false); + this.universityadmin.next(false); + this.identityToken.next(undefined); + this.accessToken.next(undefined); + + return this.authService + .login({ account_id: accountId, email_code: emailCode.trim() }) + .pipe( + switchMap((response: { id_token: string }) => { + if (this.request != request) return of(undefined); + const payload = this.decodeJwtPayload(response.id_token); + const token: TimedIdentityGrant = { + accountId, + grant: { + token_type: 'ID', + access_token: response.id_token, + expires_in: Math.max(payload.exp - Math.floor(Date.now() / 1000), 0), + scope: this.buildIdentityScope(accountId, email), + }, + expiration: payload.exp * 1000, + }; + this.identityToken.next(token); + localStorage.setItem( + CredentialService.KEY_GRANT, + JSON.stringify(token), + ); + return this.getAccessGrantForIdentity(token, request); + }), + ); + } + public loginAccount(login: string, password: string) { const request = ++this.request; const now = Date.now(); @@ -123,6 +202,7 @@ export class CredentialService { const token: TimedIdentityGrant = { grant: result as any as IdentityGrant, expiration: result.expires_in * 1000 + now, + accountId: String((result as any).scope?.a?.i ?? ''), }; this.identityToken.next(token); localStorage.setItem( @@ -140,36 +220,49 @@ export class CredentialService { public refreshAccessToken(identityToken: TimedIdentityGrant) { const request = ++this.request; - const now = Date.now(); this.validating.next(true); this.accessToken.next(undefined); - const uid = identityToken.grant.scope.a!.i; - const org = identityToken.grant.scope.a!.o; + this.getAccessGrantForIdentity(identityToken, request).subscribe({ + error: () => { + if (this.request != request) return; + this.identityToken.next(undefined); + this.organization.next(undefined); + this.authenticated.next(false); + this.superadmin.next(false); + this.universityadmin.next(false); + this.validating.next(false); + }, + }); + } - this.accountService - .getAccessGrant(identityToken.grant.access_token, uid, org) - .subscribe({ - next: (result) => { - if (this.request != request) return; - const token: TimedAccessGrant = { - grant: result as any as AccessGrant, - expiration: result.expires_in * 1000 + now, - }; - this.accessToken.next(token); - this.organization.next(result.scope.a!.o); - this.authenticated.next(true); - this.validating.next(false); - }, - error: () => { - if (this.request != request) return; - this.identityToken.next(undefined); - this.organization.next(undefined); - this.authenticated.next(false); - this.superadmin.next(false); - this.universityadmin.next(false); - this.validating.next(false); - }, - }); + public impersonateAccount(accountId: string): Observable { + if (!this.identityToken.value) { + return throwError(() => new Error('No identity token available.')); + } + + const request = ++this.request; + this.validating.next(true); + this.accessToken.next(undefined); + return this.getAccessGrantForIdentity( + this.identityToken.value, + request, + accountId, + ).pipe(tap({ error: () => this.validating.next(false) })); + } + + public stopImpersonating(): Observable { + if (!this.identityToken.value) { + return throwError(() => new Error('No identity token available.')); + } + + const request = ++this.request; + this.validating.next(true); + this.accessToken.next(undefined); + return this.getAccessGrantForIdentity( + this.identityToken.value, + request, + this.identityToken.value.accountId, + ).pipe(tap({ error: () => this.validating.next(false) })); } public logoutAcount() { @@ -217,6 +310,101 @@ export class CredentialService { ), ); } + + private getAccessGrantForIdentity( + identityToken: TimedIdentityGrant, + request: number, + effectiveAccountId?: string, + ): Observable { + const accountId = + identityToken.accountId || String(identityToken.grant.scope.a?.i ?? ''); + const headers = new HttpHeaders({ + Authorization: `Bearer ${identityToken.grant.access_token}`, + }); + + return this.httpClient + .post<{ access_token: string; refresh_token: string }>( + `${this.apiBasePath}/api/auth/v2/access`, + { + real_account_id: accountId, + effective_account_id: effectiveAccountId ?? accountId, + }, + { headers, withCredentials: true }, + ) + .pipe( + tap((result) => { + if (this.request != request) return; + const payload = this.decodeJwtPayload(result.access_token); + const scope = this.buildAccessScope( + payload, + identityToken.grant.scope.a?.e ?? '', + ); + const token: TimedAccessGrant = { + grant: { + token_type: 'ACCESS', + access_token: result.access_token, + refresh_token: result.refresh_token, + expires_in: Math.max( + payload.exp - Math.floor(Date.now() / 1000), + 0, + ), + scope, + }, + expiration: payload.exp * 1000, + realAccountId: payload.real_account_id ?? accountId, + effectiveAccountId: payload.effective_account_id ?? accountId, + }; + this.accessToken.next(token); + this.organization.next(scope.a.o); + this.authenticated.next(true); + this.validating.next(false); + }), + map(() => undefined), + ); + } + + private get apiBasePath(): string { + return this.apiConfiguration?.basePath ?? ''; + } + + private decodeJwtPayload(token: string): any { + const payload = token.split('.')[1]; + return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))); + } + + private buildIdentityScope(accountId: string, email: string): AuthScope { + return { + t: 'ID', + d: null, + r: [], + a: { + i: accountId, + l: email, + o: '', + e: email, + on: '', + }, + }; + } + + private buildAccessScope(payload: any, email: string): AuthScope { + const accountId = payload.effective_account_id ?? payload.real_account_id ?? ''; + const organizationId = payload.organization_id ?? ''; + const role = String(payload.effective_role ?? ''); + + return { + t: 'ACCESS', + d: null, + r: role ? [role] : [], + a: { + i: accountId, + l: email || accountId, + o: organizationId, + e: email, + on: organizationId, + }, + }; + } /* Old version with added complete statements to resolve loading spinner issue public getBearerToken(): Observable { return new Observable((observer) => { diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 7b479fe8..e299503c 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -23,6 +23,15 @@ } @if (credentialService.authenticated | async) { + @if (credentialService.impersonating | async) { +
+ switch_account + Impersonation aktiv + +
+ }
@if (mediaQuery.matches) { diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index 1f16e6cf..7c3ff20a 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -58,6 +58,26 @@ mat-toolbar.main { color: var(--sg-text); } +.impersonation-banner { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + min-height: 44px; + padding: 6px 20px; + background: #fff7ed; + border-bottom: 1px solid #fed7aa; + color: #9a3412; + font-size: 13px; + font-weight: 700; +} + +.impersonation-banner mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + .back-link { display: inline-flex; align-items: center; diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index f0a1e6c1..8bb0ab1a 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -107,6 +107,13 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.credentialService.logoutAcount(); this.router.navigate(['/']); } + + stopImpersonating(): void { + this.credentialService.stopImpersonating().subscribe({ + next: () => this.router.navigate(['/accounts']), + }); + } + navigateBack() { this.location.back(); } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 3386701a..ca664e06 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -90,6 +90,12 @@ export class AppMenuComponent { sorting_order: 'asc', }, }, + { + label: 'Accounts', + icon: 'manage_accounts', + route: '/accounts', + disabled: false, + }, ]; constructor( diff --git a/webapp/src/proxy.conf.json b/webapp/src/proxy.conf.json index 1e0c9ebd..e5656e77 100644 --- a/webapp/src/proxy.conf.json +++ b/webapp/src/proxy.conf.json @@ -1,12 +1,25 @@ { - "/inse-service/": { + "/inse-service": { "target": "http://127.0.0.1:8000", "secure": false, "changeOrigin": true }, - "/inse-account/": { + "/inse-account": { "target": "http://127.0.0.1:8000", "secure": false, "changeOrigin": true + }, + "/api": { + "target": "http://127.0.0.1:8000", + "secure": false, + "changeOrigin": true + }, + "/inse-webapp/api": { + "target": "http://127.0.0.1:8000", + "secure": false, + "changeOrigin": true, + "pathRewrite": { + "^/inse-webapp/api": "/api" + } } } From b4257f2efa4ba12aff62c8581e054fdbbe97584f Mon Sep 17 00:00:00 2001 From: Roman Date: Fri, 26 Jun 2026 17:35:46 +0200 Subject: [PATCH 12/31] Exclude auth endpoints from ETag cache --- service/src/main/inse/middleware/etag_cache.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index 934ca51e..3bc9f9a7 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -1,5 +1,8 @@ # middleware/etag_cache.py -import hashlib, json, time +import hashlib +import json +import time + from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response @@ -22,6 +25,12 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): if request.method != "GET": return await call_next(request) + if request.url.path.startswith(("/api/auth", "/api/accounts")): + return await call_next(request) + + if request.headers.get("authorization"): + return await call_next(request) + key = self._cache_key(request) entry = self.cache.get(key) client_etag = request.headers.get("if-none-match") From 7b13db6dbfc25e7a0f5b4ee01e70c3fa4a9b10af Mon Sep 17 00:00:00 2001 From: Roman Date: Sat, 27 Jun 2026 01:38:05 +0200 Subject: [PATCH 13/31] fix(auth): clean up auth v2 integration and legacy auth flow Connect logout and change-password handling to the new auth v2 flow and remove remaining legacy auth usage from the active frontend/backend flow. Main changes: - wire frontend logout and change-password handling to auth v2 - remove old auth service references from the active flow - fix self-access handling so real_account_id == effective_account_id is not treated as impersonation - update CredentialService token/session state handling - update guards to validate the current session through /api/accounts/me - update the auth interceptor for bearer tokens, public endpoint skips, and 401 recovery - improve impersonation recovery UX with snackbar feedback and focus cleanup - keep the registration page for now, but disable registration in CredentialService --- service/src/data/users.json | 22 -- service/src/main/inse/account/__init__.py | 0 service/src/main/inse/account/logic.py | 66 ---- service/src/main/inse/account/model.py | 56 ---- service/src/main/inse/account/security.py | 62 ---- service/src/main/inse/account/service.py | 169 ----------- service/src/main/inse/auth/service.py | 27 +- service/src/main/inse/main.py | 2 - service/src/main/inse/security.py | 119 -------- webapp/src/app/api/.openapi-generator/FILES | 6 - webapp/src/app/api/api/api.ts | 17 +- .../app/api/api/iNSEAccountService.service.ts | 282 ------------------ webapp/src/app/api/model/accessGrant.ts | 20 -- webapp/src/app/api/model/authAccount.ts | 19 -- webapp/src/app/api/model/authScope.ts | 19 -- webapp/src/app/api/model/bodyCreateUser.ts | 19 -- webapp/src/app/api/model/identityGrant.ts | 19 -- webapp/src/app/api/model/models.ts | 6 - webapp/src/app/api/model/user.ts | 45 --- webapp/src/app/app.routes.ts | 3 +- .../accounts/account-dialog.component.ts | 54 +++- .../modules/accounts/accounts.component.ts | 47 +-- .../modules/app-login/app-login.component.ts | 12 +- webapp/src/app/shared/guards/admin.guard.ts | 46 +-- webapp/src/app/shared/guards/user.guard.ts | 41 ++- .../authentication.interceptor.ts | 111 +++++-- .../app/shared/services/credential.service.ts | 216 ++++++++------ .../app/shared/services/ui-focus.service.ts | 14 + .../ui/app-layout/app-layout.component.html | 6 +- .../ui/app-layout/app-layout.component.ts | 11 +- .../ui/app-menu/app-menu.component.html | 56 ++-- .../shared/ui/app-menu/app-menu.component.ts | 23 +- 32 files changed, 432 insertions(+), 1183 deletions(-) delete mode 100644 service/src/data/users.json delete mode 100644 service/src/main/inse/account/__init__.py delete mode 100644 service/src/main/inse/account/logic.py delete mode 100644 service/src/main/inse/account/model.py delete mode 100644 service/src/main/inse/account/security.py delete mode 100644 service/src/main/inse/account/service.py delete mode 100644 service/src/main/inse/security.py delete mode 100644 webapp/src/app/api/api/iNSEAccountService.service.ts delete mode 100644 webapp/src/app/api/model/accessGrant.ts delete mode 100644 webapp/src/app/api/model/authAccount.ts delete mode 100644 webapp/src/app/api/model/authScope.ts delete mode 100644 webapp/src/app/api/model/bodyCreateUser.ts delete mode 100644 webapp/src/app/api/model/identityGrant.ts delete mode 100644 webapp/src/app/api/model/user.ts create mode 100644 webapp/src/app/shared/services/ui-focus.service.ts diff --git a/service/src/data/users.json b/service/src/data/users.json deleted file mode 100644 index 450db22c..00000000 --- a/service/src/data/users.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "users": [ - { - "username": "superadmin", - "password": "superadmin", - "email": "some_email@uni-due.de", - "account": 0, - "organization": 0, - "organization_name": "University of Duisburg-Essen", - "superadmin": true - }, - { - "username": "user", - "password": "user", - "email": "user_email@uni-due.de", - "account": 1, - "organization": 1, - "organization_name": "University of Duisburg-Essen", - "superadmin": false - } - ] -} diff --git a/service/src/main/inse/account/__init__.py b/service/src/main/inse/account/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/service/src/main/inse/account/logic.py b/service/src/main/inse/account/logic.py deleted file mode 100644 index b443254c..00000000 --- a/service/src/main/inse/account/logic.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module contains the validation logic for - user names and passwords. -""" -import typing -import logging -from . import model - -logger = logging.getLogger(__name__) - -def _get_users() -> typing.List[model.User]: - ''' Returns the list of users from the user configuration file. ''' - try: - with open('../data/users.json') as file: - config = model.UserFile.model_validate_json(file.read()) - return config.users - except Exception as e: - logger.error('Could not read user configuration file.', exc_info=e) - return [] - -def get_user(username: str) -> typing.Optional[model.User]: - ''' Returns the user with the given username. ''' - for user in _get_users(): - if user.username == username: - return user - return None - -def validate_user(username: str, password: str) -> typing.Optional[model.User]: - ''' Validates the user with the given username and password. ''' - user = get_user(username) - if user and user.password == password: - return user - return None - -def create_user(username, password, email, institution, superadmin) -> typing.Optional[model.User]: - ''' Adds a new user to the user configuration file. ''' - users = _get_users() - if any(u.username == username for u in users): - logger.warning("Attempt to create duplicate user: %s", username) - return None - - # Determine new IDs - next_account = max((u.account for u in users), default=0) + 1 - next_org = max((u.organization for u in users), default=0) + 1 - - new_user = model.User( - username=username, - password=password, - email=email, - account=next_account, - organization=next_org, - organization_name=institution, - superadmin=superadmin - ) - - users.append(new_user) - user_file = model.UserFile(users=users) - try: - with open('../data/users.json', 'w') as file: - file.write(user_file.model_dump_json(indent=4)) - return new_user - except Exception as e: - logger.error('Could not write user configuration file.', exc_info=e) - return None diff --git a/service/src/main/inse/account/model.py b/service/src/main/inse/account/model.py deleted file mode 100644 index 6a2cca19..00000000 --- a/service/src/main/inse/account/model.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - Data models for the standalone account sub-app. -""" -from pydantic import BaseModel -from pydantic import Field -from pydantic import StrictInt -from typing import List, Optional - - -class User(BaseModel): - ''' An entry in the user configuration file. ''' - username: str = Field(description="The username of the user.") - password: str = Field(description="The password of the user.") - email: str = Field(description="The email of the user.") - account: StrictInt = Field(description="The account id of the user.") - organization: StrictInt = Field(description="The organization id of the user.") - organization_name: str = Field(description="The organization name of the user.") - superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.") - - -class UserFile(BaseModel): - ''' The data model for the file containing the user configuration. ''' - users: List[User] = Field(default=[], description="The list of users.") - - -class AuthAccount(BaseModel): - i: int - l: str - o: int - e: str - on: str - - -class AuthScope(BaseModel): - t: str - a: AuthAccount - d: Optional[int] = None - r: List[str] = [] - - -class IdentityGrant(BaseModel): - token_type: str - access_token: str - expires_in: int - scope: AuthScope - - -class AccessGrant(BaseModel): - token_type: str - access_token: str - expires_in: int - scope: AuthScope - refresh_token: str - diff --git a/service/src/main/inse/account/security.py b/service/src/main/inse/account/security.py deleted file mode 100644 index 44fdb5dd..00000000 --- a/service/src/main/inse/account/security.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module defines the security-related code. -""" -from typing import Optional -from typing import Dict -from typing import Literal -import jwt -import time -import logging -from .. import config -from .. import security -from . import model - -logger = logging.getLogger(__name__) - -def principal(id_token: str) -> Optional[security.Principal]: - ''' Extracts the principal from the id token. ''' - return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH']) - -def id_token(user: model.User, exp: int) -> str: - ''' Creates a new identity token for the specified user. ''' - return _encode(_payload(user, 'ID', exp)) - -def access_token(user: model.User, exp: int) -> str: - ''' Creates a new access token for the specified user. ''' - return _encode(_payload(user, 'ACCESS', exp)) - -def refresh_token(user: model.User, exp: int) -> str: - ''' Creates a new refresh token for the specified user. ''' - return _encode(_payload(user, 'REFRESH', exp)) - -def _encode(payload: Dict[str, any]) -> str: - ''' Creates a valid web token that encodes the contents with the symmetric key. ''' - headers = { - "kid" : "sym", - } - return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers) - -def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str: - ''' Creates the payload of the token for the specified user and token type. ''' - now = int(time.time()) - roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ] - payload = { - "iss" : "my-app", - "exp" : now + exp, - "iat" : now, - "nbf" : now, - "inse" : { - "t" : type, - "a" : { - "i" : user.account, - "l" : user.username, - "o" : user.organization - }, - "d" : None, - "r" : roles if type == 'ACCESS' else [] - } - } - return payload - diff --git a/service/src/main/inse/account/service.py b/service/src/main/inse/account/service.py deleted file mode 100644 index ae99cd7b..00000000 --- a/service/src/main/inse/account/service.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -Standalone account service that provides identity and access -token endpoints for authentication. -""" - -import logging -import fastapi -import typing -from . import logic -from . import model -from . import security -from starlette.status import HTTP_400_BAD_REQUEST -from starlette.status import HTTP_403_FORBIDDEN -from starlette.status import HTTP_200_OK -from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR - -logger = logging.getLogger(__name__) - -router = fastapi.APIRouter( - prefix="/inse-account", - tags=["INSE Account Service"], - responses={404: {"description": "Not found"}}, -) - - -@router.post( - "/auth/id", - operation_id="getIdentityGrant", - responses={ - HTTP_200_OK: {"model": model.IdentityGrant}, - HTTP_400_BAD_REQUEST: { - "model": None, - "description": "Invalid request parameters.", - }, - HTTP_403_FORBIDDEN: { - "model": None, - "description": "Account login not successful.", - }, - HTTP_500_INTERNAL_SERVER_ERROR: { - "model": None, - "description": "Token generation failed.", - }, - }, -) -async def get_identity_grant( - username: typing.Annotated[str, fastapi.Form()], - password: typing.Annotated[str, fastapi.Form()], -): - user = logic.validate_user(username, password) - if user is None: - logger.info("Invalid login attempt (%s).", username) - raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN) - try: - exp = 12 * 60 * 60 - token = security.id_token(user, exp=exp) - account = model.AuthAccount( - i=user.account, - l=user.username, - o=user.organization, - e=user.email, - on=user.organization_name, - ) - scope = model.AuthScope(t="ID", a=account, d=None, r=[]) - grant = model.IdentityGrant( - token_type="bearer", access_token=token, expires_in=exp, scope=scope - ) - logger.info("Identity token generated (%s).", username) - return grant - except Exception as e: - logger.error("Token generation failed (%s).", username, exc_info=e) - raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR) - - -@router.post( - "/auth/access", - operation_id="getAccessGrant", - responses={ - HTTP_200_OK: {"model": model.AccessGrant}, - HTTP_400_BAD_REQUEST: { - "model": None, - "description": "Invalid request parameters.", - }, - HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."}, - HTTP_500_INTERNAL_SERVER_ERROR: { - "model": None, - "description": "Token generation failed.", - }, - }, -) -async def get_access_grant( - secret: typing.Annotated[str, fastapi.Form()], - account: typing.Annotated[int, fastapi.Form()], - organization: typing.Annotated[int, fastapi.Form()], -): - principal = security.principal(secret) - if principal is None: - logger.info("Invalid access attempt without principal (%s).", account) - raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST) - user = logic.get_user(principal.account.login) - if user is None: - logger.info("Invalid access attempt without user (%s).", account) - raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN) - if user.organization != organization or user.account != account: - logger.info("Invalid personation attempt (%s).", account) - raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN) - try: - exp = 10 * 60 - token = security.access_token(user, exp=exp) - refresh = security.refresh_token(user, exp=exp) - auth_account = model.AuthAccount( - i=user.account, - l=user.username, - o=user.organization, - e=user.email, - on=user.organization_name, - ) - scope = model.AuthScope( - t="ACCESS", - a=auth_account, - d=None, - r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"], - ) - grant = model.AccessGrant( - token_type="bearer", - access_token=token, - expires_in=exp, - scope=scope, - refresh_token=refresh, - ) - logger.info("Access token generated (%s).", user.username) - return grant - except Exception as e: - logger.error("Token generation failed (%s).", user.username, exc_info=e) - raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR) - - -@router.post( - "/create", - operation_id="createUser", - responses={ - HTTP_200_OK: {"model": model.User}, - HTTP_400_BAD_REQUEST: { - "model": None, - "description": "User creation failed (e.g. duplicate username).", - }, - HTTP_500_INTERNAL_SERVER_ERROR: { - "model": None, - "description": "Internal server error.", - }, - }, -) -async def create_user( - username: typing.Annotated[str, fastapi.Body()], - password: typing.Annotated[str, fastapi.Body()], - email: typing.Annotated[str, fastapi.Body()], - institution: typing.Annotated[str, fastapi.Body()], - superadmin: typing.Annotated[bool, fastapi.Body()] = False, -): - user = logic.create_user(username, password, email, institution, superadmin) - if user is None: - logger.info("User creation failed for (%s).", username) - raise fastapi.HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail="User creation failed. Username might already exist." - ) - logger.info("User created successfully (%s).", username) - return user diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index c772012f..d8da0821 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,9 +1,9 @@ import datetime import hashlib import json +import logging import secrets import uuid -import logging from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from typing import Annotated, Any, Dict, Literal, Optional @@ -25,7 +25,7 @@ from inse.auth.model import ( ) from inse.config import get_settings from inse.database import get_session -from sqlmodel import Session, select, func +from sqlmodel import Session, func, select ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes @@ -142,6 +142,7 @@ def _verify_password(password: str, password_hash: str) -> bool: 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. @@ -507,11 +508,12 @@ def _is_valid_impersonation( ]: 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 + # 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 @@ -547,7 +549,13 @@ def get_access_token( detail="Real account ID does not match ID token", ) - if effective_account_id: + # 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, @@ -557,9 +565,6 @@ def get_access_token( status_code=status.HTTP_403_FORBIDDEN, detail="Impersonation not allowed", ) - else: - # No impersonation, set effective_account_id to real_account_id - effective_account_id = real_account_id role = _get_account_role(session=session, account_id=effective_account_id) epoch = _get_account_epoch(account_id=effective_account_id, session=session) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 71d27db6..443107d7 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -36,7 +36,6 @@ from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from . import config -from .account.service import router as account_router from .service import router as service_router @@ -73,7 +72,6 @@ app.include_router(persons_service_router) app.include_router(funders_service_router) app.include_router(news_service_router) app.include_router(company_connections_router) -app.include_router(account_router) app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) diff --git a/service/src/main/inse/security.py b/service/src/main/inse/security.py deleted file mode 100644 index d6495cb9..00000000 --- a/service/src/main/inse/security.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -This module defines the security-related code. -""" - -from typing import Optional -from typing import List -from typing import Callable -from typing import Literal -from starlette.status import HTTP_403_FORBIDDEN -from fastapi import Depends -from fastapi.security import HTTPBearer -from fastapi.security import HTTPAuthorizationCredentials -from fastapi import HTTPException -from pydantic import BaseModel -from pydantic import Field -import jwt -import logging -from . import config -from . import database - - -class Account(BaseModel): - id: int = Field(description="The id of the account.") - login: Optional[str] = Field(description="The optional login of the account.") - organization: int = Field(description="The organization id of the account.") - - -class Principal(BaseModel): - account: Account = Field(description="The account of the principal.") - delegate: Optional[Account] = Field( - default=None, description="The optional delegate of the principal." - ) - roles: List[str] = Field(description="The roles of the principal.") - - -logger = logging.getLogger(__name__) - -bearer = HTTPBearer( - bearerFormat="JWT", - scheme_name="bearer", - description="JSON Web Token provided via bearer authorization.", - auto_error=False, -) - - -def principal( - db: database.SessionDep, - credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), -) -> Optional[Principal]: - if config.settings.auth_disabled: - account = Account(id=0, login="AUTH_DISABLED", organization=0) - return Principal(account=account, delegate=None, roles=["SUPER_ADMIN"]) - if credentials is None or credentials.credentials is None: - return None - return _extract_principal( - credentials.credentials, config.settings.auth_secret, "HS256" - ) - - -def _extract_principal( - token: str, - secret_key, - algorithm: Literal["RS256", "HS256"], - token_types: List[Literal["ID", "ACCESS", "REFRESH"]] = ["ACCESS"], -) -> Optional[Principal]: - try: - content = jwt.decode( - token, - secret_key, - verify=True, - issuer="my-app", - algorithms=[algorithm], - options={"require": ["iss", "iat", "nbf", "exp", "inse"]}, - ) - except jwt.exceptions.ExpiredSignatureError as e: - logger.info(f"Received expired token, ignoring content ({e}).") - return None - except Exception as e: - logger.info(f"Received invalid token content, ignoring content ({e}).") - return None - scope = content.get("inse") - if scope is None: - return None - token_type = scope.get("t") - if token_type not in token_types: - logger.info( - f"Received invalid token type, ignoring content (Type was {token_type})" - ) - return None - a = scope.get("a", {}) - account = Account(id=a.get("i", 0), login=a.get("l"), organization=a.get("o", 0)) - delegate = None - d = scope.get("d") - if d is not None: - delegate = Account( - id=d.get("i", 0), login=d.get("l"), organization=d.get("o", 0) - ) - return Principal(account=account, delegate=delegate, roles=scope.get("r", [])) - - -def roles_allowed(roles: List[str] | str) -> Callable[[Optional[Principal]], Principal]: - if isinstance(roles, str): - roles = [roles] - if len(roles) < 1: - raise ValueError("Must specify at least one role in roles_allowed.") - - def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal: - if principal is None: - logger.info("Rejecting call due to missing principal.") - raise HTTPException(status_code=HTTP_403_FORBIDDEN) - for role in roles: - if role in principal.roles: - return principal - logger.info("Rejecting call due to missing roles.") - raise HTTPException(status_code=HTTP_403_FORBIDDEN) - - return verify_roles diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 49ac1868..a2407030 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -7,7 +7,6 @@ api/api.ts api/auth.service.ts api/companyConnections.service.ts api/funding.service.ts -api/iNSEAccountService.service.ts api/iNSEService.service.ts api/institutions.service.ts api/news.service.ts @@ -21,9 +20,6 @@ configuration.ts encoder.ts git_push.sh index.ts -model/accessGrant.ts -model/authAccount.ts -model/authScope.ts model/author.ts model/authorAffiliationsInner.ts model/authorCountsByYearInner.ts @@ -40,7 +36,6 @@ model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts model/award.ts model/bodyChangePassword.ts -model/bodyCreateUser.ts model/bodyGetAccessToken.ts model/bodyLogin.ts model/bodyRequestOtk.ts @@ -76,7 +71,6 @@ model/fundingProjectPage.ts model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts -model/identityGrant.ts model/institution.ts model/institutionFunderSummary.ts model/institutionGeo.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index dda89ae3..f78dee69 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -4,8 +4,6 @@ export * from './companyConnections.service'; import { CompanyConnectionsService } from './companyConnections.service'; export * from './funding.service'; import { FundingService } from './funding.service'; -export * from './iNSEAccountService.service'; -import { INSEAccountServiceService } from './iNSEAccountService.service'; export * from './iNSEService.service'; import { INSEServiceService } from './iNSEService.service'; export * from './institutions.service'; @@ -24,4 +22,17 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; +export const APIS = [ + AuthService, + CompanyConnectionsService, + FundingService, + INSEServiceService, + InstitutionsService, + NewsService, + PatentsService, + PersonNetworkService, + PersonsService, + ProjectsService, + TopicsService, + WorksService, +]; diff --git a/webapp/src/app/api/api/iNSEAccountService.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts deleted file mode 100644 index 90181dbd..00000000 --- a/webapp/src/app/api/api/iNSEAccountService.service.ts +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -/* 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 { AccessGrant } from '../model/accessGrant'; -// @ts-ignore -import { BodyCreateUser } from '../model/bodyCreateUser'; -// @ts-ignore -import { HTTPValidationError } from '../model/hTTPValidationError'; -// @ts-ignore -import { IdentityGrant } from '../model/identityGrant'; -// @ts-ignore -import { User } from '../model/user'; - -// @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; -import { BaseService } from '../api.base.service'; - - - -@Injectable({ - providedIn: 'root' -}) -export class INSEAccountServiceService extends BaseService { - - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); - } - - /** - * Create User - * @endpoint post /inse-account/create - * @param bodyCreateUser - * @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 createUser(bodyCreateUser: BodyCreateUser, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createUser(bodyCreateUser: BodyCreateUser, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createUser(bodyCreateUser: BodyCreateUser, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createUser(bodyCreateUser: BodyCreateUser, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (bodyCreateUser === null || bodyCreateUser === undefined) { - throw new Error('Required parameter bodyCreateUser was null or undefined when calling createUser.'); - } - - 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 = `/inse-account/create`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: bodyCreateUser, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Get Access Grant - * @endpoint post /inse-account/auth/access - * @param secret - * @param account - * @param organization - * @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 getAccessGrant(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAccessGrant(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessGrant(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessGrant(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (secret === null || secret === undefined) { - throw new Error('Required parameter secret was null or undefined when calling getAccessGrant.'); - } - if (account === null || account === undefined) { - throw new Error('Required parameter account was null or undefined when calling getAccessGrant.'); - } - if (organization === null || organization === undefined) { - throw new Error('Required parameter organization was null or undefined when calling getAccessGrant.'); - } - - 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/x-www-form-urlencoded' - ]; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any; }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({encoder: this.encoder}); - } - - if (secret !== undefined) { - localVarFormParams = localVarFormParams.append('secret', secret) as any || localVarFormParams; - } - if (account !== undefined) { - localVarFormParams = localVarFormParams.append('account', account) as any || localVarFormParams; - } - if (organization !== undefined) { - localVarFormParams = localVarFormParams.append('organization', organization) as any || localVarFormParams; - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/inse-account/auth/access`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Get Identity Grant - * @endpoint post /inse-account/auth/id - * @param username - * @param password - * @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 getIdentityGrant(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getIdentityGrant(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getIdentityGrant(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getIdentityGrant(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling getIdentityGrant.'); - } - if (password === null || password === undefined) { - throw new Error('Required parameter password was null or undefined when calling getIdentityGrant.'); - } - - 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/x-www-form-urlencoded' - ]; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any; }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({encoder: this.encoder}); - } - - if (username !== undefined) { - localVarFormParams = localVarFormParams.append('username', username) as any || localVarFormParams; - } - if (password !== undefined) { - localVarFormParams = localVarFormParams.append('password', password) as any || localVarFormParams; - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/inse-account/auth/id`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - -} diff --git a/webapp/src/app/api/model/accessGrant.ts b/webapp/src/app/api/model/accessGrant.ts deleted file mode 100644 index ad1f537a..00000000 --- a/webapp/src/app/api/model/accessGrant.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { AuthScope } from './authScope'; - - -export interface AccessGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; - refresh_token: string; -} - diff --git a/webapp/src/app/api/model/authAccount.ts b/webapp/src/app/api/model/authAccount.ts deleted file mode 100644 index 770a61f5..00000000 --- a/webapp/src/app/api/model/authAccount.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -export interface AuthAccount { - i: number; - l: string; - o: number; - e: string; - on: string; -} - diff --git a/webapp/src/app/api/model/authScope.ts b/webapp/src/app/api/model/authScope.ts deleted file mode 100644 index 65ffa9b5..00000000 --- a/webapp/src/app/api/model/authScope.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { AuthAccount } from './authAccount'; - - -export interface AuthScope { - t: string; - a: AuthAccount; - d?: number | null; - r?: Array; -} - diff --git a/webapp/src/app/api/model/bodyCreateUser.ts b/webapp/src/app/api/model/bodyCreateUser.ts deleted file mode 100644 index 76caab3b..00000000 --- a/webapp/src/app/api/model/bodyCreateUser.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -export interface BodyCreateUser { - username: string; - password: string; - email: string; - institution: string; - superadmin?: boolean; -} - diff --git a/webapp/src/app/api/model/identityGrant.ts b/webapp/src/app/api/model/identityGrant.ts deleted file mode 100644 index 9ec3fe50..00000000 --- a/webapp/src/app/api/model/identityGrant.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { AuthScope } from './authScope'; - - -export interface IdentityGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; -} - diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 3690cd69..5680353b 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -1,6 +1,3 @@ -export * from './accessGrant'; -export * from './authAccount'; -export * from './authScope'; export * from './author'; export * from './authorAffiliationsInner'; export * from './authorCountsByYearInner'; @@ -17,7 +14,6 @@ export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; export * from './bodyChangePassword'; -export * from './bodyCreateUser'; export * from './bodyGetAccessToken'; export * from './bodyLogin'; export * from './bodyRequestOtk'; @@ -53,7 +49,6 @@ export * from './fundingProjectPage'; export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; -export * from './identityGrant'; export * from './institution'; export * from './institutionFunderSummary'; export * from './institutionGeo'; @@ -98,7 +93,6 @@ export * from './topicsByYear'; export * from './topicsListResponse'; export * from './universityRanking'; export * from './universityTopicData'; -export * from './user'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; diff --git a/webapp/src/app/api/model/user.ts b/webapp/src/app/api/model/user.ts deleted file mode 100644 index def604e1..00000000 --- a/webapp/src/app/api/model/user.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -/** - * An entry in the user configuration file. - */ -export interface User { - /** - * The username of the user. - */ - username: string; - /** - * The password of the user. - */ - password: string; - /** - * The email of the user. - */ - email: string; - /** - * The account id of the user. - */ - account: number; - /** - * The organization id of the user. - */ - organization: number; - /** - * The organization name of the user. - */ - organization_name: string; - /** - * Indicates whether the user is a superadmin. - */ - superadmin?: boolean; -} - diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 1204da01..ac7dbf07 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -1,5 +1,6 @@ import { Routes } from '@angular/router'; import { userGuard } from './shared/guards/user.guard'; +import { adminGuard } from './shared/guards/admin.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; import { personListResolver } from './resolvers/person-list.resolver'; import { personBioResolver } from './resolvers/person-bio.resolver'; @@ -92,7 +93,7 @@ export const routes: Routes = [ }, { path: 'accounts', - canActivate: [userGuard], + canActivate: [adminGuard], loadComponent: () => import('./modules/accounts/accounts.component').then( (mod) => mod.AccountsComponent, diff --git a/webapp/src/app/modules/accounts/account-dialog.component.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts index 784a2474..a10cff43 100644 --- a/webapp/src/app/modules/accounts/account-dialog.component.ts +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -55,9 +55,10 @@ export type AccountDialogResult = standalone: true, }) export class AccountDialogComponent { - private readonly dialogRef = inject< - MatDialogRef - >(MatDialogRef); + private readonly dialogRef = + inject< + MatDialogRef + >(MatDialogRef); protected readonly data = inject(MAT_DIALOG_DATA); protected readonly form = new FormGroup({ @@ -73,7 +74,9 @@ export class AccountDialogComponent { ]), organizationId: new FormControl( this.data.account?.organization_id ?? - (this.data.organizations.length === 1 ? this.data.organizations[0].id : ''), + (this.data.organizations.length === 1 + ? this.data.organizations[0].id + : ''), [Validators.required], ), password: new FormControl('', [ @@ -104,16 +107,43 @@ export class AccountDialogComponent { 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: this.data.account!.id, - payload: { - email: value.email ?? '', - name: value.name ?? '', - role: value.role ?? 'USER', - organization_id: value.organizationId ?? '', - password: value.password || undefined, - }, + accountId: account.id, + payload, }); } diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index dc99bd2e..87865007 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -10,9 +10,7 @@ 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 { AccountManagementService } from '../../shared/services/account-management.service'; import type { AccountProfile, AccountRole, @@ -48,12 +46,13 @@ export class AccountsComponent implements OnInit { private readonly router = inject(Router); private readonly dialog = inject(MatDialog); - protected readonly roles: AccountRole[] = [ - 'SUPER_ADMIN', - 'ADMIN', - 'MANAGER', - 'USER', - ]; + protected get availableRoles(): AccountRole[] { + if (this.credentialService.superadmin.value) { + return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER']; + } + + return ['MANAGER', 'USER']; + } protected accounts: AccountProfile[] = []; protected organizations: OrganizationProfile[] = []; protected total = 0; @@ -150,14 +149,14 @@ export class AccountsComponent implements OnInit { }): void { import('./account-dialog.component').then(({ AccountDialogComponent }) => { const dialogRef = this.dialog.open< - AccountDialogComponent, - { - mode: 'create' | 'edit'; - account?: AccountProfile; - organizations: OrganizationProfile[]; - canSelectOrganization: boolean; - roles: AccountRole[]; - }, + AccountDialogComponent, + { + mode: 'create' | 'edit'; + account?: AccountProfile; + organizations: OrganizationProfile[]; + canSelectOrganization: boolean; + roles: AccountRole[]; + }, AccountDialogResult | undefined >(AccountDialogComponent, { width: '760px', @@ -166,7 +165,7 @@ export class AccountsComponent implements OnInit { ...data, organizations: this.organizations, canSelectOrganization: this.credentialService.superadmin.value, - roles: this.roles, + roles: this.availableRoles, }, }); @@ -211,9 +210,13 @@ export class AccountsComponent implements OnInit { this.router.navigate(['/dashboard']); }, error: () => { - this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', { - duration: 5000, - }); + this.snackBar.open( + 'Impersonation konnte nicht gestartet werden.', + 'OK', + { + duration: 5000, + }, + ); }, }); } @@ -236,7 +239,7 @@ export class AccountsComponent implements OnInit { } return ( - this.credentialService.universityadmin.value && + this.credentialService.admin.value && (account.role === 'MANAGER' || account.role === 'USER') ); } diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index eecd2512..21fb3e79 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -137,7 +137,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { ); }, error: (error: HttpErrorResponse) => { - this.credentialService.logoutAcount(); + this.credentialService.clearLocalAuthState(); this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { duration: 5000, }); @@ -169,11 +169,9 @@ export class AppLoginComponent implements OnInit, OnDestroy { } if (!this.accountId) { - this.snackBar.open( - 'Bitte fordere zuerst einen neuen Code an.', - 'OK', - { duration: 5000 }, - ); + this.snackBar.open('Bitte fordere zuerst einen neuen Code an.', 'OK', { + duration: 5000, + }); return; } @@ -197,7 +195,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.router.navigate(['/dashboard']); }, error: (error: HttpErrorResponse) => { - this.credentialService.logoutAcount(); + this.credentialService.clearLocalAuthState(); this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { duration: 5000, }); diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index b5b48337..06b7f24c 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -1,23 +1,35 @@ 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'; -import { Observable, of, switchMap, takeWhile } from 'rxjs'; -export const adminGuard: CanActivateFn = (route, state) => { - let credentialService = inject(CredentialService); - let router = inject(Router); - return new Observable((subscriber) => { - credentialService.validating - .pipe(takeWhile((validating) => validating)) - .subscribe({ - complete: () => { - if (!credentialService.superadmin.value) { - router.navigate(['/login']); - return subscriber.next(false); - } else { - return subscriber.next(true); +export const adminGuard: CanActivateFn = () => { + const credentialService = inject(CredentialService); + const router = inject(Router); + + return credentialService.validating.pipe( + filter((validating) => !validating), + take(1), + switchMap(() => { + if (!credentialService.authenticated.value) { + void router.navigate(['/login']); + return of(false); + } + + return credentialService.validateCurrentSession().pipe( + switchMap(() => { + if ( + !credentialService.superadmin.value && + !credentialService.admin.value + ) { + void router.navigate(['/dashboard']); + return of(false); } - }, - }); - }); + + return of(true); + }), + catchError(() => of(false)), + ); + }), + ); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index c64e9cbc..6be9e6e0 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -1,26 +1,25 @@ import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; +import { catchError, filter, map, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; -import { Observable, of, switchMap, takeWhile } from 'rxjs'; -export const userGuard: CanActivateFn = (route, state) => { - let credentialService = inject(CredentialService); - let router = inject(Router); - return new Observable((subscriber) => { - credentialService.validating - .pipe(takeWhile((validating) => validating)) - .subscribe({ - complete: () => { - if ( - !credentialService.superadmin.value && - !credentialService.universityadmin.value - ) { - router.navigate(['/login']); - return subscriber.next(false); - } else { - return subscriber.next(true); - } - }, - }); - }); +export const userGuard: CanActivateFn = () => { + const credentialService = inject(CredentialService); + const router = inject(Router); + + return credentialService.validating.pipe( + filter((validating) => !validating), + take(1), + switchMap(() => { + if (!credentialService.authenticated.value) { + void router.navigate(['/login']); + return of(false); + } + + return credentialService.validateCurrentSession().pipe( + map(() => true), + catchError(() => of(false)), + ); + }), + ); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 6cbac0b4..130e6c94 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -1,41 +1,86 @@ import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; import { inject } from '@angular/core'; +import { Router } from '@angular/router'; +import { MatSnackBar } from '@angular/material/snack-bar'; +import { catchError, switchMap, tap, throwError } from 'rxjs'; import { CredentialService } from '../services/credential.service'; -import { switchMap, throwError } from 'rxjs'; +import { UiFocusService } from '../services/ui-focus.service'; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { - if ( - (req.method == 'POST' && - (req.url.endsWith('/auth/id') || - req.url.endsWith('/auth/access') || - req.url.endsWith('/api/auth/v2/request-otk') || - req.url.endsWith('/api/auth/v2/login') || - req.url.endsWith('/api/auth/v2/access') || - req.url.endsWith('/api/auth/v2/refresh') || - req.url.endsWith('/inse-account/create') || - req.url.endsWith('/auth/v2/request-otk'))) || - req.url.endsWith('/institutions/autocomplete') - ) { - return next(req); - } else { - const credentialService = inject(CredentialService); - const tokenProvider = credentialService.getBearerToken(); + const url = req.url.split('?')[0]; + const uiFocusService = inject(UiFocusService); - return tokenProvider.pipe( - switchMap((response) => { - if (response == undefined) { - return throwError( - () => - new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), - ); - } else { - return next( - req.clone({ - headers: req.headers.set('Authorization', 'Bearer ' + response), - }), - ); - } - }), - ); + const isPublicAuthRequest = + req.method === 'POST' && + (url.endsWith('/api/auth/v2/request-otk') || + url.endsWith('/api/auth/v2/login') || + url.endsWith('/api/auth/v2/access') || + url.endsWith('/api/auth/v2/refresh')); + + if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) { + return next(req); } + + const credentialService = inject(CredentialService); + const router = inject(Router); + const snackBar = inject(MatSnackBar); + const tokenProvider = credentialService.getBearerToken(); + const isLogoutRequest = url.endsWith('/api/auth/v2/logout'); + + return tokenProvider.pipe( + switchMap((response) => { + if (response == undefined) { + credentialService.clearLocalAuthState(); + + snackBar.open( + 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', + 'OK', + { duration: 7000 }, + ); + + void router.navigate(['/login']); + + return throwError( + () => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), + ); + } + + const authorizedRequest = req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + response), + }); + + return next(authorizedRequest).pipe( + catchError((error: HttpErrorResponse) => { + if (error.status === 401 && !isLogoutRequest) { + return credentialService.handleUnauthorized().pipe( + tap((result) => { + uiFocusService.blurActiveElement(); + + if (result === 'stopped-impersonating') { + snackBar.open( + 'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.', + 'OK', + { duration: 7000 }, + ); + + void router.navigate(['/accounts']); + } else if (result === 'logged-out') { + snackBar.open( + 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', + 'OK', + { duration: 7000 }, + ); + + void router.navigate(['/login']); + } + }), + switchMap(() => throwError(() => error)), + ); + } + + return throwError(() => error); + }), + ); + }), + ); }; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index ce13f616..6ae05269 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,14 +1,14 @@ import { Injectable, inject } from '@angular/core'; -import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman -import { Observable, of, switchMap, tap, throwError } from 'rxjs'; // review -import { BehaviorSubject } from 'rxjs'; //review +import { filter, take, map, catchError, finalize } from 'rxjs/operators'; import { - AuthService, - Configuration, - INSEAccountServiceService, - IdentityGrant as ApiIdentityGrant, - AccessGrant as ApiAccessGrant, -} from '../../api'; + BehaviorSubject, + Observable, + of, + switchMap, + tap, + throwError, +} from 'rxjs'; +import { AuthService, Configuration } from '../../api'; import { HttpClient, HttpHeaders } from '@angular/common/http'; export interface AuthAccount { @@ -54,21 +54,27 @@ interface TimedAccessGrant { effectiveAccountId: string; } +type LogoutResult = 'logged-out' | 'stopped-impersonating'; +type UnauthorizedRecoveryResult = + | 'logged-out' + | 'stopped-impersonating' + | 'already-handling'; + @Injectable({ providedIn: 'root', }) export class CredentialService { - private accountService = inject(INSEAccountServiceService); private authService = inject(AuthService); private httpClient = inject(HttpClient); private apiConfiguration = inject(Configuration, { optional: true }); + private handlingUnauthorized = false; private static readonly KEY_GRANT = 'grant'; public readonly validating = new BehaviorSubject(false); public readonly authenticated = new BehaviorSubject(false); public readonly superadmin = new BehaviorSubject(false); - public readonly universityadmin = new BehaviorSubject(false); + public readonly admin = new BehaviorSubject(false); public readonly organization = new BehaviorSubject( undefined, ); @@ -93,16 +99,18 @@ export class CredentialService { if (token) { const r = token.grant.scope.r as string[]; this.superadmin.next(r.includes('SUPER_ADMIN')); - this.universityadmin.next(r.includes('UNI_ADMIN') || r.includes('ADMIN')); + this.admin.next(r.includes('ADMIN')); this.login.next(token.grant.scope.a?.l ?? ''); this.email.next(token.grant.scope.a?.e ?? ''); this.organizationName.next(token.grant.scope.a?.on ?? ''); - this.impersonating.next(token.realAccountId !== token.effectiveAccountId); + this.impersonating.next( + token.realAccountId !== token.effectiveAccountId, + ); this.realAccountId.next(token.realAccountId); this.effectiveAccountId.next(token.effectiveAccountId); } else { this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.login.next(''); this.email.next(''); this.organizationName.next(''); @@ -120,13 +128,19 @@ export class CredentialService { } } + public validateCurrentSession(): Observable { + return this.httpClient + .get(`${this.apiBasePath}/api/accounts/me`, { withCredentials: true }) + .pipe(map(() => undefined)); + } + public requestOtk(email: string, password: string): Observable { const request = ++this.request; this.validating.next(true); this.authenticated.next(false); this.organization.next(undefined); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.identityToken.next(undefined); this.accessToken.next(undefined); @@ -134,10 +148,17 @@ export class CredentialService { .requestOtk({ email: email.trim().toLowerCase(), password }) .pipe( map((response: { account_id?: string }) => { - if (this.request != request) return ''; - this.validating.next(false); + if (this.request !== request) { + return ''; + } + return response.account_id ?? ''; }), + finalize(() => { + if (this.request === request) { + this.validating.next(false); + } + }), ); } @@ -151,7 +172,7 @@ export class CredentialService { this.authenticated.next(false); this.organization.next(undefined); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.identityToken.next(undefined); this.accessToken.next(undefined); @@ -166,7 +187,10 @@ export class CredentialService { grant: { token_type: 'ID', access_token: response.id_token, - expires_in: Math.max(payload.exp - Math.floor(Date.now() / 1000), 0), + expires_in: Math.max( + payload.exp - Math.floor(Date.now() / 1000), + 0, + ), scope: this.buildIdentityScope(accountId, email), }, expiration: payload.exp * 1000, @@ -181,43 +205,6 @@ export class CredentialService { ); } - public loginAccount(login: string, password: string) { - const request = ++this.request; - const now = Date.now(); - this.validating.next(true); - this.authenticated.next(false); - this.organization.next(undefined); - this.superadmin.next(false); - this.universityadmin.next(false); - this.identityToken.next(undefined); - this.accessToken.next(undefined); - - const body = new URLSearchParams(); - body.set('username', login); - body.set('password', password); - - this.accountService.getIdentityGrant(login, password).subscribe({ - next: (result) => { - if (this.request != request) return; - const token: TimedIdentityGrant = { - grant: result as any as IdentityGrant, - expiration: result.expires_in * 1000 + now, - accountId: String((result as any).scope?.a?.i ?? ''), - }; - this.identityToken.next(token); - localStorage.setItem( - CredentialService.KEY_GRANT, - JSON.stringify(token), - ); - this.refreshAccessToken(token); - }, - error: () => { - if (this.request != request) return; - this.validating.next(false); - }, - }); - } - public refreshAccessToken(identityToken: TimedIdentityGrant) { const request = ++this.request; this.validating.next(true); @@ -229,7 +216,7 @@ export class CredentialService { this.organization.next(undefined); this.authenticated.next(false); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.validating.next(false); }, }); @@ -265,20 +252,96 @@ export class CredentialService { ).pipe(tap({ error: () => this.validating.next(false) })); } - public logoutAcount() { + public logoutAccount(): Observable { + const wasImpersonating = this.impersonating.value; + + return this.authService + .logout('body', false, { transferCache: false }) + .pipe( + catchError((error) => { + console.error('Backend logout failed', error); + return of(null); + }), + switchMap(() => { + if (!wasImpersonating) { + this.clearLocalAuthState(); + return of('logged-out' as const); + } + + return this.stopImpersonating().pipe( + map(() => 'stopped-impersonating' as const), + catchError((error) => { + console.error('Stop impersonating after logout failed', error); + this.clearLocalAuthState(); + return of('logged-out' as const); + }), + ); + }), + ); + } + + public clearLocalAuthState(): void { this.request += 1; localStorage.removeItem(CredentialService.KEY_GRANT); this.authenticated.next(false); this.organization.next(undefined); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.identityToken.next(undefined); this.accessToken.next(undefined); this.validating.next(false); } - public registerAccount(data: any): Observable { - return this.accountService.createUser(data); + public handleUnauthorized(): Observable { + if (this.handlingUnauthorized) { + return of('already-handling' as const); + } + + this.handlingUnauthorized = true; + + const recovery$ = + this.impersonating.value && this.identityToken.value + ? this.stopImpersonating().pipe( + map(() => 'stopped-impersonating' as const), + catchError((error) => { + console.error('Failed to stop impersonation after 401', error); + this.clearLocalAuthState(); + return of('logged-out' as const); + }), + ) + : of(null).pipe( + tap(() => this.clearLocalAuthState()), + map(() => 'logged-out' as const), + ); + + return recovery$.pipe( + finalize(() => { + this.handlingUnauthorized = false; + }), + ); + } + + public changePassword( + currentPassword: string, + newPassword: string, + ): Observable { + return this.httpClient + .post( + `${this.apiBasePath}/api/auth/v2/change-password`, + { + current_password: currentPassword, + new_password: newPassword, + }, + { withCredentials: true }, + ) + .pipe( + tap(() => this.clearLocalAuthState()), + map(() => undefined), + ); + } + + public registerAccount(_data: unknown): Observable { + return throwError(() => new Error('Registration is temporarily disabled.')); } //review: arman (generated fix) @@ -388,7 +451,8 @@ export class CredentialService { } private buildAccessScope(payload: any, email: string): AuthScope { - const accountId = payload.effective_account_id ?? payload.real_account_id ?? ''; + const accountId = + payload.effective_account_id ?? payload.real_account_id ?? ''; const organizationId = payload.organization_id ?? ''; const role = String(payload.effective_role ?? ''); @@ -405,32 +469,4 @@ export class CredentialService { }, }; } - /* Old version with added complete statements to resolve loading spinner issue - public getBearerToken(): Observable { - return new Observable((observer) => { - if (this.validating.value) { - this.validating.pipe(takeWhile((validating) => validating)).subscribe({ - complete: () => { - observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined); - observer.complete(); // added complete - } - }); - } else if (!this.accessToken.value) { - observer.next(undefined); - observer.complete(); // added complete - } else if (Date.now() < this.accessToken.value.expiration) { - observer.next(this.accessToken.value.grant.access_token); - observer.complete(); // added complete - } else { - this.refreshAccessToken(this.identityToken.value!); - this.validating.pipe(takeWhile((validating) => validating)).subscribe({ - complete: () => { - observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined); - observer.complete(); // added complete - } - }); - } - }); - } - */ } diff --git a/webapp/src/app/shared/services/ui-focus.service.ts b/webapp/src/app/shared/services/ui-focus.service.ts new file mode 100644 index 00000000..ba149da8 --- /dev/null +++ b/webapp/src/app/shared/services/ui-focus.service.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(); + } + } +} diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index e299503c..3de4c98b 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -3,11 +3,7 @@ - @if ( - (credentialService.authenticated | async) && - ((credentialService.superadmin | async) || - (credentialService.universityadmin | async)) - ) { + @if (credentialService.authenticated | async) { { + if (result === 'stopped-impersonating') { + this.router.navigate(['/accounts']); + } else { + this.router.navigate(['/login']); + } + }, + }); } stopImpersonating(): void { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index ab143d54..7a766163 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -42,31 +42,37 @@ @for (item of navItems; track item.label) { - @if (collapsed()) { - - {{ item.icon }} - - } @else { - - {{ item.icon }} - {{ item.label }} - + @if ( + !item.adminOnly || + (credentialService.superadmin | async) || + (credentialService.admin | async) + ) { + @if (collapsed()) { + + {{ item.icon }} + + } @else { + + {{ item.icon }} + {{ item.label }} + + } } } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index ca664e06..37eaaca7 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -15,6 +15,15 @@ import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatDialog } from '@angular/material/dialog'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; +type NavItem = { + label: string; + icon: string; + route: string; + disabled: boolean; + queryParams?: Record; + adminOnly?: boolean; +}; + @Component({ selector: 'app-menu', imports: [ @@ -41,7 +50,7 @@ export class AppMenuComponent { matrixParams: 'ignored', fragment: 'ignored', }; - navItems = [ + navItems: NavItem[] = [ { label: 'Dashboard', icon: 'dashboard', @@ -95,6 +104,7 @@ export class AppMenuComponent { icon: 'manage_accounts', route: '/accounts', disabled: false, + adminOnly: true, }, ]; @@ -117,8 +127,15 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAcount(); - this.router.navigate(['/login']); + this.credentialService.logoutAccount().subscribe({ + next: (result) => { + if (result === 'stopped-impersonating') { + this.router.navigate(['/accounts']); + } else { + this.router.navigate(['/login']); + } + }, + }); }); } } From 1351264c80e6b9ab9ca5e661ddae1a01f27c1651 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 27 Jun 2026 10:41:29 +0200 Subject: [PATCH 14/31] Updated endpoint schemas --- service/src/data/predefined_accounts.json | 16 +- service/src/main/inse/auth/model.py | 18 + service/src/main/inse/auth/router.py | 16 +- service/src/main/inse/auth/service.py | 242 +++++++--- webapp/src/app/api/.openapi-generator/FILES | 12 + webapp/src/app/api/api/auth.service.ts | 418 +++++++++++++++++- webapp/src/app/api/model/accessResponse.ts | 24 + webapp/src/app/api/model/accessToken.ts | 55 +++ webapp/src/app/api/model/accountPage.ts | 19 + webapp/src/app/api/model/accountProfile.ts | 28 ++ .../src/app/api/model/createAccountRequest.ts | 24 + webapp/src/app/api/model/idToken.ts | 42 ++ webapp/src/app/api/model/loginResponse.ts | 19 + webapp/src/app/api/model/models.ts | 12 + .../src/app/api/model/organizationProfile.ts | 17 + webapp/src/app/api/model/refreshToken.ts | 55 +++ webapp/src/app/api/model/tokenType.ts | 18 + .../src/app/api/model/updateAccountRequest.ts | 25 ++ webapp/src/app/api/model/userRole.ts | 19 + 19 files changed, 993 insertions(+), 86 deletions(-) create mode 100644 webapp/src/app/api/model/accessResponse.ts create mode 100644 webapp/src/app/api/model/accessToken.ts create mode 100644 webapp/src/app/api/model/accountPage.ts create mode 100644 webapp/src/app/api/model/accountProfile.ts create mode 100644 webapp/src/app/api/model/createAccountRequest.ts create mode 100644 webapp/src/app/api/model/idToken.ts create mode 100644 webapp/src/app/api/model/loginResponse.ts create mode 100644 webapp/src/app/api/model/organizationProfile.ts create mode 100644 webapp/src/app/api/model/refreshToken.ts create mode 100644 webapp/src/app/api/model/tokenType.ts create mode 100644 webapp/src/app/api/model/updateAccountRequest.ts create mode 100644 webapp/src/app/api/model/userRole.ts diff --git a/service/src/data/predefined_accounts.json b/service/src/data/predefined_accounts.json index 51ea8a4f..b6bf36da 100644 --- a/service/src/data/predefined_accounts.json +++ b/service/src/data/predefined_accounts.json @@ -1,8 +1,20 @@ { "organizations": [ { - "id": "c001beef-cafe-4000-8000-d34db33f000d", + "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": [ @@ -10,7 +22,7 @@ "email": "super@admin.com", "password": "superadmin", "name": "Super Admin", - "organization_id": "c001beef-cafe-4000-8000-d34db33f000d", + "organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c", "role": "SUPER_ADMIN" } ] diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index b5c0d47a..1c8922d3 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -143,6 +143,11 @@ class Token(BaseModel): 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): @@ -189,3 +194,16 @@ class RefreshToken(AccessToken): 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.py b/service/src/main/inse/auth/router.py index 8133c315..2ce4f52a 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -1,5 +1,5 @@ import logging -from typing import Annotated, Dict +from typing import Annotated import uuid from fastapi import APIRouter, Body, Depends, Response, status @@ -9,7 +9,13 @@ from inse.tags import Tags import inse.auth.service as auth_service from inse.database import SessionDep, get_session -from inse.auth.model import AccessToken, IdToken, RefreshToken +from inse.auth.model import ( + AccessResponse, + AccessToken, + IdToken, + LoginResponse, + RefreshToken, +) logger = logging.getLogger(__name__) @@ -52,7 +58,7 @@ async def login( 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 ) @@ -75,7 +81,7 @@ async def get_action_tokens( uuid.UUID, Body(description="Effective account ID for the access token") ], id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], -) -> Dict[str, str]: +) -> AccessResponse: logger.debug( "Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s", real_account_id, @@ -105,7 +111,7 @@ async def refresh_access_token( refresh_token: Annotated[ RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep ], -) -> str: +) -> AccessToken: return auth_service.refresh_access_token(refresh_token=refresh_token) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index c772012f..c1acad02 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -4,8 +4,6 @@ import json import secrets import uuid import logging -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText from typing import Annotated, Any, Dict, Literal, Optional import jwt @@ -14,9 +12,11 @@ from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatc 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, @@ -36,8 +36,8 @@ 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" -ORGANIZATION_ID_KEY = "organization_id" USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" ID_FP_COOKIE_KEY = "_Secure-Fgp-ID" @@ -80,9 +80,11 @@ def create_predefined_accounts(session: Session, file_path: str): try: with open(file_path, "r") as file: - data = json.loads(file.read()) + data: Dict[str, Any] = json.loads(file.read()) for organization_data in data.get("organizations", []): - organization_id = uuid.UUID(organization_data["id"]) + 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) @@ -142,6 +144,7 @@ def _verify_password(password: str, password_hash: str) -> bool: 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. @@ -222,7 +225,9 @@ def request_otk(session: Session, email: str, password: str): return {"status": "ok", "account_id": str(account.id)} -def login(session: Session, response: Response, account_id: uuid.UUID, email_code: str): +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: @@ -234,6 +239,9 @@ def login(session: Session, response: Response, account_id: uuid.UUID, email_cod 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) @@ -282,7 +290,7 @@ def login(session: Session, response: Response, account_id: uuid.UUID, email_cod session.commit() - return {"id_token": id_token} + return LoginResponse(id_token=id_token) def _get_current_user_access_token_payload( @@ -319,8 +327,11 @@ def _get_current_user_access_token_payload( ), epoch=access_token_payload[EPOCH_KEY], effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]), - effective_organization_id=uuid.UUID(access_token_payload[ORGANIZATION_ID_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, ) @@ -356,8 +367,11 @@ def _get_current_user_refresh_token_payload( ), epoch=refresh_token_payload[EPOCH_KEY], effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]), - effective_organization_id=uuid.UUID(refresh_token_payload[ORGANIZATION_ID_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) @@ -378,7 +392,7 @@ def _get_current_user_id_token_payload( credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the ID token. Returns: - Dict[str, Any]: The verified ID token payload. + IdToken: The verified ID token payload. """ logger.debug( "Verifying ID token for request %s with credentials %s", @@ -403,6 +417,7 @@ def _get_current_user_id_token_payload( ), epoch=id_token_payload[EPOCH_KEY], user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY], + raw_token=token, ) @@ -522,7 +537,7 @@ def get_access_token( id_token: IdToken, real_account_id: uuid.UUID, effective_account_id: Optional[uuid.UUID] = None, -) -> Dict[str, Any]: +) -> 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: @@ -537,7 +552,7 @@ def get_access_token( HTTPException: If impersonation is not allowed. Returns: - Dict[str, Any]: A dictionary containing the generated access and refresh tokens. + 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. @@ -569,17 +584,25 @@ def get_access_token( user_fingerprint_hash = _set_act_fp_cookie(response=response) - access_token_payload = { - REAL_ACCOUNT_ID_KEY: str(real_account_id), - EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id), - EPOCH_KEY: epoch, - EFFECTIVE_ROLE_KEY: role.value, - ORGANIZATION_ID_KEY: str(organization_id), - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, - } - - return _build_action_tokens( - payload=access_token_payload, + 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, ) @@ -639,7 +662,7 @@ def _set_fingerprint_cookie( return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() -def refresh_access_token(refresh_token: RefreshToken) -> str: +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: @@ -648,7 +671,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> str: refresh_token (RefreshToken): The refresh token to verify. Returns: - str: The refreshed access token. + 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. @@ -659,7 +682,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> str: def _refresh_access_token( refresh_token: RefreshToken, -) -> str: +) -> AccessToken: """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. Args: @@ -668,97 +691,182 @@ def _refresh_access_token( current_user_epoch (int): The epoch value for the tokens. Returns: - str: The refreshed access token. + 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. - access_payload = { - REAL_ACCOUNT_ID_KEY: str(refresh_token.real_account_id), - EFFECTIVE_ACCOUNT_ID_KEY: str(refresh_token.effective_account_id), - EPOCH_KEY: refresh_token.epoch, - EFFECTIVE_ROLE_KEY: refresh_token.effective_role, - ORGANIZATION_ID_KEY: str(refresh_token.effective_organization_id), - USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash, - } - return _build_token( - payload=access_payload, - expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES, - token_type=TokenType.ACCESS_TOKEN, + 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) -> str: - """Builds an ID token for the specified real account ID and sets the appropriate fingerprint cookie. +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: - str: The built ID token. + 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, } - return _build_token( + raw_token = _build_token( payload=payload, - expiration_min=ID_TOKEN_EXPIRATION_MINUTES, + 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_action_tokens( - payload: Dict[str, Any], -) -> Dict[str, str]: - """Builds both access and refresh tokens for the specified account IDs and sets the appropriate fingerprint cookies. +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 cookies will be added. + 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: - Dict[str, str]: A dictionary containing the built access and refresh tokens. + RefreshToken: The generated refresh token object. """ - - return { - "access_token": _build_token( - payload=payload, - expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES, - token_type=TokenType.ACCESS_TOKEN, - ), - "refresh_token": _build_token( - payload=payload, - expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES, - token_type=TokenType.REFRESH_TOKEN, - ), + 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_min: int, token_type: TokenType + 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_min (int): The expiration time in minutes. + 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) - expiration_date = now + datetime.timedelta(minutes=expiration_min) payload.update( { - "exp": expiration_date, + "exp": expiration_datetime, "iss": settings.token_issuer_id, "iat": now, "nbf": now, diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 49ac1868..0e1261a3 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -22,6 +22,10 @@ encoder.ts git_push.sh index.ts model/accessGrant.ts +model/accessResponse.ts +model/accessToken.ts +model/accountPage.ts +model/accountProfile.ts model/authAccount.ts model/authScope.ts model/author.ts @@ -56,6 +60,7 @@ model/companyConnectionsResponse.ts model/cordisEuProject.ts model/cordisEuProjectPage.ts model/costUsd.ts +model/createAccountRequest.ts model/customAuthor.ts model/customAuthorsListResponse.ts model/dehydratedAuthor.ts @@ -76,6 +81,7 @@ model/fundingProjectPage.ts model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts +model/idToken.ts model/identityGrant.ts model/institution.ts model/institutionFunderSummary.ts @@ -88,6 +94,7 @@ model/institutionsListResponse.ts model/keywords.ts model/latitude.ts model/location.ts +model/loginResponse.ts model/longitude.ts model/matchedOfficer.ts model/mentionedPerson.ts @@ -98,6 +105,7 @@ model/newsArticle.ts model/newsArticleDetail.ts model/newsPage.ts model/openAccess.ts +model/organizationProfile.ts model/patentEntry.ts model/patentsByAuthorResponse.ts model/personBio.ts @@ -108,8 +116,10 @@ model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/rankingResponse.ts +model/refreshToken.ts model/score.ts model/sortDirection.ts +model/tokenType.ts model/topic.ts model/topicCount.ts model/topicDomain.ts @@ -122,7 +132,9 @@ model/topicsByYear.ts model/topicsListResponse.ts model/universityRanking.ts model/universityTopicData.ts +model/updateAccountRequest.ts model/user.ts +model/userRole.ts model/validationError.ts model/validationErrorLocInner.ts model/value.ts diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index d3174504..a927c77c 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -16,6 +16,14 @@ import { HttpClient, HttpHeaders, HttpParams, 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 @@ -25,7 +33,15 @@ 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'; @@ -112,6 +128,132 @@ export class AuthService extends BaseService { ); } + /** + * 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. @@ -120,9 +262,9 @@ export class AuthService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<{ [key: string]: string | null; }>; - 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?: '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.'); @@ -167,7 +309,7 @@ export class AuthService extends BaseService { let localVarPath = `/api/auth/v2/access`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request<{ [key: string]: string | null; }>('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: bodyGetAccessToken, @@ -181,6 +323,60 @@ export class AuthService extends BaseService { ); } + /** + * 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 @@ -232,6 +428,132 @@ export class AuthService extends BaseService { ); } + /** + * 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. @@ -240,9 +562,9 @@ export class AuthService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public 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?: '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.'); @@ -284,7 +606,7 @@ export class AuthService extends BaseService { let localVarPath = `/api/auth/v2/login`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: bodyLogin, @@ -360,9 +682,9 @@ export class AuthService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public 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?: '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; @@ -395,7 +717,7 @@ export class AuthService extends BaseService { let localVarPath = `/api/auth/v2/refresh`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -474,4 +796,76 @@ export class AuthService extends BaseService { ); } + /** + * 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.ts b/webapp/src/app/api/model/accessResponse.ts new file mode 100644 index 00000000..f1610895 --- /dev/null +++ b/webapp/src/app/api/model/accessResponse.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.ts b/webapp/src/app/api/model/accessToken.ts new file mode 100644 index 00000000..ce3ea930 --- /dev/null +++ b/webapp/src/app/api/model/accessToken.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.ts b/webapp/src/app/api/model/accountPage.ts new file mode 100644 index 00000000..c92c4ba3 --- /dev/null +++ b/webapp/src/app/api/model/accountPage.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.ts b/webapp/src/app/api/model/accountProfile.ts new file mode 100644 index 00000000..17a68e22 --- /dev/null +++ b/webapp/src/app/api/model/accountProfile.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/createAccountRequest.ts b/webapp/src/app/api/model/createAccountRequest.ts new file mode 100644 index 00000000..3be9003b --- /dev/null +++ b/webapp/src/app/api/model/createAccountRequest.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.ts b/webapp/src/app/api/model/idToken.ts new file mode 100644 index 00000000..e6a88cd3 --- /dev/null +++ b/webapp/src/app/api/model/idToken.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.ts b/webapp/src/app/api/model/loginResponse.ts new file mode 100644 index 00000000..ace8f15d --- /dev/null +++ b/webapp/src/app/api/model/loginResponse.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/models.ts b/webapp/src/app/api/model/models.ts index 3690cd69..9fa7b50a 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -1,4 +1,8 @@ export * from './accessGrant'; +export * from './accessResponse'; +export * from './accessToken'; +export * from './accountPage'; +export * from './accountProfile'; export * from './authAccount'; export * from './authScope'; export * from './author'; @@ -33,6 +37,7 @@ export * from './companyConnectionsResponse'; export * from './cordisEuProject'; export * from './cordisEuProjectPage'; export * from './costUsd'; +export * from './createAccountRequest'; export * from './customAuthor'; export * from './customAuthorsListResponse'; export * from './dehydratedAuthor'; @@ -53,6 +58,7 @@ export * from './fundingProjectPage'; export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; +export * from './idToken'; export * from './identityGrant'; export * from './institution'; export * from './institutionFunderSummary'; @@ -65,6 +71,7 @@ export * from './institutionsListResponse'; export * from './keywords'; export * from './latitude'; export * from './location'; +export * from './loginResponse'; export * from './longitude'; export * from './matchedOfficer'; export * from './mentionedPerson'; @@ -74,6 +81,7 @@ export * from './newsArticle'; export * from './newsArticleDetail'; export * from './newsPage'; export * from './openAccess'; +export * from './organizationProfile'; export * from './patentEntry'; export * from './patentsByAuthorResponse'; export * from './personBio'; @@ -84,8 +92,10 @@ export * from './publicationDetailByFunder'; export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './rankingResponse'; +export * from './refreshToken'; export * from './score'; export * from './sortDirection'; +export * from './tokenType'; export * from './topic'; export * from './topicCount'; export * from './topicDomain'; @@ -98,7 +108,9 @@ export * from './topicsByYear'; export * from './topicsListResponse'; export * from './universityRanking'; export * from './universityTopicData'; +export * from './updateAccountRequest'; export * from './user'; +export * from './userRole'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; diff --git a/webapp/src/app/api/model/organizationProfile.ts b/webapp/src/app/api/model/organizationProfile.ts new file mode 100644 index 00000000..939671ba --- /dev/null +++ b/webapp/src/app/api/model/organizationProfile.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface OrganizationProfile { + id: string; + name: string; + openalex_institution_id?: string | null; +} + diff --git a/webapp/src/app/api/model/refreshToken.ts b/webapp/src/app/api/model/refreshToken.ts new file mode 100644 index 00000000..89506b70 --- /dev/null +++ b/webapp/src/app/api/model/refreshToken.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.ts b/webapp/src/app/api/model/tokenType.ts new file mode 100644 index 00000000..06231c11 --- /dev/null +++ b/webapp/src/app/api/model/tokenType.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.ts b/webapp/src/app/api/model/updateAccountRequest.ts new file mode 100644 index 00000000..15b0043d --- /dev/null +++ b/webapp/src/app/api/model/updateAccountRequest.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.ts b/webapp/src/app/api/model/userRole.ts new file mode 100644 index 00000000..83b5c595 --- /dev/null +++ b/webapp/src/app/api/model/userRole.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]; + From f951eba7e45b763a08d872f7f7ba833d2621cf42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 27 Jun 2026 11:42:35 +0200 Subject: [PATCH 15/31] Removed Armans old auth models --- .../app/shared/services/credential.service.ts | 203 +++++------------- 1 file changed, 54 insertions(+), 149 deletions(-) diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index e934860b..0163c1d1 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -10,55 +10,14 @@ import { } from 'rxjs'; import { AccessResponse, + AccessToken, AuthService, Configuration, + IdToken, LoginResponse, } from '../../api'; import { HttpClient, HttpHeaders } from '@angular/common/http'; -export interface AuthAccount { - i: string; - l: string; - o: string; - e: string; - on: string; -} - -export interface AuthScope { - t: string; - a: AuthAccount; - d: number | null; - r: string[]; -} - -export interface IdentityGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; -} - -export interface AccessGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; - refresh_token: string; -} - -interface TimedIdentityGrant { - grant: IdentityGrant; - expiration: number; - accountId: string; -} - -interface TimedAccessGrant { - grant: AccessGrant; - expiration: number; - realAccountId: string; - effectiveAccountId: string; -} - type LogoutResult = 'logged-out' | 'stopped-impersonating'; type UnauthorizedRecoveryResult = | 'logged-out' @@ -90,29 +49,29 @@ export class CredentialService { public readonly realAccountId = new BehaviorSubject(''); public readonly effectiveAccountId = new BehaviorSubject(''); - private readonly identityToken = new BehaviorSubject< - TimedIdentityGrant | undefined - >(undefined); - private readonly accessToken = new BehaviorSubject< - TimedAccessGrant | undefined - >(undefined); + + private readonly identityToken = new BehaviorSubject( + undefined, + ); + private readonly accessToken = new BehaviorSubject( + undefined, + ); private request = 0; constructor() { - this.accessToken.subscribe((token) => { + this.accessToken.subscribe((token: AccessToken | undefined) => { if (token) { - const r = token.grant.scope.r; - this.superadmin.next(r.includes('SUPER_ADMIN')); - this.admin.next(r.includes('ADMIN')); - this.login.next(token.grant.scope.a?.l ?? ''); - this.email.next(token.grant.scope.a?.e ?? ''); - this.organizationName.next(token.grant.scope.a?.on ?? ''); + this.superadmin.next(token.effective_role === 'SUPER_ADMIN'); + this.admin.next(token.effective_role === 'ADMIN'); + // this.login.next(token.grant.scope.a?.l ?? ''); + // this.email.next(token.grant.scope.a?.e ?? ''); + // this.organizationName.next(token.grant.scope.a?.on ?? ''); this.impersonating.next( - token.realAccountId !== token.effectiveAccountId, + token.real_account_id !== token.effective_account_id, ); - this.realAccountId.next(token.realAccountId); - this.effectiveAccountId.next(token.effectiveAccountId); + this.realAccountId.next(token.real_account_id); + this.effectiveAccountId.next(token.effective_account_id); } else { this.superadmin.next(false); this.admin.next(false); @@ -125,8 +84,8 @@ export class CredentialService { } }); const data = localStorage.getItem(CredentialService.KEY_GRANT); - const id = data ? (JSON.parse(data) as TimedIdentityGrant) : undefined; - if (id?.expiration && id.expiration >= Date.now()) { + const id = data ? (JSON.parse(data) as AccessToken) : undefined; + if (id && new Date(id.expires_at).getTime() >= Date.now()) { this.identityToken.next(id); this.validating.next(true); setTimeout(() => this.refreshAccessToken(id), 0); @@ -187,31 +146,33 @@ export class CredentialService { switchMap((response: LoginResponse) => { if (this.request != request) return of(undefined); - const token: TimedIdentityGrant = { - accountId, - grant: { - token_type: 'ID', - access_token: response.id_token.raw_token, - expires_in: Math.max( - new Date(response.id_token.expires_at).getTime() - - Math.floor(Date.now() / 1000), - 0, - ), - scope: this.buildIdentityScope(accountId, email), - }, - expiration: new Date(response.id_token.expires_at).getTime(), - }; - this.identityToken.next(token); + const idToken = response.id_token; + + // const token: TimedIdentityGrant = { + // accountId, + // grant: { + // token_type: 'ID', + // access_token: response.id_token.raw_token, + // expires_in: Math.max( + // new Date(response.id_token.expires_at).getTime() - + // Math.floor(Date.now() / 1000), + // 0, + // ), + // scope: this.buildIdentityScope(accountId, email), + // }, + // expiration: new Date(response.id_token.expires_at).getTime(), + // }; + this.identityToken.next(idToken); localStorage.setItem( CredentialService.KEY_GRANT, - JSON.stringify(token), + JSON.stringify(idToken), ); - return this.getAccessGrantForIdentity(token, request); + return this.getAccessGrantForIdentity(idToken, request); }), ); } - public refreshAccessToken(identityToken: TimedIdentityGrant) { + public refreshAccessToken(identityToken: IdToken) { const request = ++this.request; this.validating.next(true); this.accessToken.next(undefined); @@ -254,7 +215,6 @@ export class CredentialService { return this.getAccessGrantForIdentity( this.identityToken.value, request, - this.identityToken.value.accountId, ).pipe(tap({ error: () => this.validating.next(false) })); } @@ -355,9 +315,9 @@ export class CredentialService { // 1. If we have a valid access token, return it immediately and complete. if ( this.accessToken.value && - Date.now() < this.accessToken.value.expiration + Date.now() < new Date(this.accessToken.value.expires_at).getTime() ) { - return of(this.accessToken.value.grant.access_token); + return of(this.accessToken.value.raw_token); } // 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh. @@ -373,26 +333,23 @@ export class CredentialService { filter((isValidating) => !isValidating), // Wait until validating becomes false take(1), // Take exactly 1 emission and then automatically complete() map(() => - this.accessToken.value - ? this.accessToken.value.grant.access_token - : undefined, + this.accessToken.value ? this.accessToken.value.raw_token : undefined, ), ); } private getAccessGrantForIdentity( - identityToken: TimedIdentityGrant, + idToken: IdToken, request: number, effectiveAccountId?: string, ): Observable { - const accountId = - identityToken.accountId || String(identityToken.grant.scope.a?.i ?? ''); + const realAccountId = idToken.real_account_id; const headers = new HttpHeaders({ - Authorization: `Bearer ${identityToken.grant.access_token}`, + Authorization: `Bearer ${idToken.raw_token}`, }); const payload = { - real_account_id: accountId, - effective_account_id: effectiveAccountId ?? accountId, + real_account_id: realAccountId, + effective_account_id: effectiveAccountId ?? realAccountId, }; return this.httpClient @@ -401,30 +358,13 @@ export class CredentialService { withCredentials: true, }) .pipe( - tap((result) => { + tap((result: AccessResponse) => { if (this.request != request) return; - const scope = this.buildAccessScope( - payload, - identityToken.grant.scope.a?.e ?? '', - ); - const token: TimedAccessGrant = { - grant: { - token_type: 'ACCESS', - access_token: result.access_token.raw_token, - refresh_token: result.refresh_token.raw_token, - expires_in: Math.max( - new Date(result.access_token.expires_at).getTime() - - Math.floor(Date.now() / 1000), - 0, - ), - scope, - }, - expiration: new Date(result.access_token.expires_at).getTime(), - realAccountId: payload.real_account_id ?? accountId, - effectiveAccountId: payload.effective_account_id ?? accountId, - }; - this.accessToken.next(token); - this.organization.next(scope.a.o); + + const accessToken = result.access_token; + + this.accessToken.next(accessToken); + this.organization.next(accessToken.effective_organization_id); this.authenticated.next(true); this.validating.next(false); }), @@ -435,39 +375,4 @@ export class CredentialService { private get apiBasePath(): string { return this.apiConfiguration?.basePath ?? ''; } - - private buildIdentityScope(accountId: string, email: string): AuthScope { - return { - t: 'ID', - d: null, - r: [], - a: { - i: accountId, - l: email, - o: '', - e: email, - on: '', - }, - }; - } - - private buildAccessScope(payload: any, email: string): AuthScope { - const accountId = - payload.effective_account_id ?? payload.real_account_id ?? ''; - const organizationId = payload.organization_id ?? ''; - const role = String(payload.effective_role ?? ''); - - return { - t: 'ACCESS', - d: null, - r: role ? [role] : [], - a: { - i: accountId, - l: email || accountId, - o: organizationId, - e: email, - on: organizationId, - }, - }; - } } From b993862afba5adc765f72cab7aadf64960f25e28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 27 Jun 2026 11:57:30 +0200 Subject: [PATCH 16/31] Updated credential service to modern signal api --- .../modules/accounts/accounts.component.html | 12 +- .../modules/accounts/accounts.component.ts | 9 +- .../modules/app-login/app-login.component.ts | 2 +- .../app-register/app-register.component.ts | 2 +- webapp/src/app/shared/guards/admin.guard.ts | 6 +- webapp/src/app/shared/guards/user.guard.ts | 2 +- .../app/shared/services/credential.service.ts | 165 +++++++----------- .../ui/app-layout/app-layout.component.html | 6 +- .../ui/app-layout/app-layout.component.ts | 5 +- .../ui/app-menu/app-menu.component.html | 4 +- 10 files changed, 87 insertions(+), 126 deletions(-) diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index f9610b4e..8137c2f2 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -4,7 +4,11 @@

Accounts

Account-Zugänge verwalten, Rollen setzen und Impersonation starten.

- @@ -16,7 +20,7 @@ - @if (credentialService.superadmin | async) { + @if (credentialService.isEffectiveSuperAdmin()) { Organisation @@ -74,7 +78,9 @@ {{ account.email }} {{ account.organization_name }} - {{ account.role }} + + {{ account.role }} + {{ account.deleted ? 'deleted' : 'active' }} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index 87865007..845f0990 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -47,7 +47,7 @@ export class AccountsComponent implements OnInit { private readonly dialog = inject(MatDialog); protected get availableRoles(): AccountRole[] { - if (this.credentialService.superadmin.value) { + if (this.credentialService.isEffectiveSuperAdmin()) { return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER']; } @@ -164,7 +164,8 @@ export class AccountsComponent implements OnInit { data: { ...data, organizations: this.organizations, - canSelectOrganization: this.credentialService.superadmin.value, + canSelectOrganization: + this.credentialService.isEffectiveSuperAdmin(), roles: this.availableRoles, }, }); @@ -234,12 +235,12 @@ export class AccountsComponent implements OnInit { return false; } - if (this.credentialService.superadmin.value) { + if (this.credentialService.isEffectiveSuperAdmin()) { return true; } return ( - this.credentialService.admin.value && + this.credentialService.isEffectiveAdmin() && (account.role === 'MANAGER' || account.role === 'USER') ); } diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 21fb3e79..7d3b0cf7 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -85,7 +85,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { } checkEnter(): void { - if (this.credentialService.authenticated.value) { + if (this.credentialService.isAuthenticated.value) { this.router.navigate(['/dashboard']); } } diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts index 42d53887..d4169732 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -95,7 +95,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit { } checkEnter(): void { - if (this.credentialService.authenticated.value) { + if (this.credentialService.isAuthenticated.value) { this.router.navigate(['/dashboard']); } } diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index 06b7f24c..55e18ca8 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -11,7 +11,7 @@ export const adminGuard: CanActivateFn = () => { filter((validating) => !validating), take(1), switchMap(() => { - if (!credentialService.authenticated.value) { + if (!credentialService.isAuthenticated.value) { void router.navigate(['/login']); return of(false); } @@ -19,8 +19,8 @@ export const adminGuard: CanActivateFn = () => { return credentialService.validateCurrentSession().pipe( switchMap(() => { if ( - !credentialService.superadmin.value && - !credentialService.admin.value + !credentialService.isEffectiveSuperAdmin() && + !credentialService.isEffectiveAdmin() ) { void router.navigate(['/dashboard']); return of(false); diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index 6be9e6e0..190780ae 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -11,7 +11,7 @@ export const userGuard: CanActivateFn = () => { filter((validating) => !validating), take(1), switchMap(() => { - if (!credentialService.authenticated.value) { + if (!credentialService.isAuthenticated.value) { void router.navigate(['/login']); return of(false); } diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index 0163c1d1..d3d4a569 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,4 +1,4 @@ -import { Injectable, inject } from '@angular/core'; +import { Injectable, computed, inject, signal } from '@angular/core'; import { filter, take, map, catchError, finalize } from 'rxjs/operators'; import { BehaviorSubject, @@ -36,57 +36,40 @@ export class CredentialService { private static readonly KEY_GRANT = 'grant'; public readonly validating = new BehaviorSubject(false); - public readonly authenticated = new BehaviorSubject(false); - public readonly superadmin = new BehaviorSubject(false); - public readonly admin = new BehaviorSubject(false); - public readonly organization = new BehaviorSubject( - undefined, + public readonly isAuthenticated = new BehaviorSubject(false); + public readonly isEffectiveSuperAdmin = computed( + () => this.accessToken()?.effective_role === 'SUPER_ADMIN', + ); + public readonly isEffectiveAdmin = computed( + () => this.accessToken()?.effective_role === 'ADMIN', + ); + public readonly effectiveOrganizationId = computed( + () => this.accessToken()?.effective_organization_id, ); public readonly login = new BehaviorSubject(''); public readonly email = new BehaviorSubject(''); public readonly organizationName = new BehaviorSubject(''); - public readonly impersonating = new BehaviorSubject(false); - public readonly realAccountId = new BehaviorSubject(''); - public readonly effectiveAccountId = new BehaviorSubject(''); - - private readonly identityToken = new BehaviorSubject( - undefined, + public readonly realAccountId = computed( + () => this.accessToken()?.real_account_id ?? '', ); - private readonly accessToken = new BehaviorSubject( - undefined, + public readonly effectiveAccountId = computed( + () => this.accessToken()?.effective_account_id ?? '', ); + public readonly isImpersonating = computed( + () => this.realAccountId() !== this.effectiveAccountId(), + ); + + private readonly identityToken = signal(undefined); + private readonly accessToken = signal(undefined); private request = 0; constructor() { - this.accessToken.subscribe((token: AccessToken | undefined) => { - if (token) { - this.superadmin.next(token.effective_role === 'SUPER_ADMIN'); - this.admin.next(token.effective_role === 'ADMIN'); - // this.login.next(token.grant.scope.a?.l ?? ''); - // this.email.next(token.grant.scope.a?.e ?? ''); - // this.organizationName.next(token.grant.scope.a?.on ?? ''); - this.impersonating.next( - token.real_account_id !== token.effective_account_id, - ); - this.realAccountId.next(token.real_account_id); - this.effectiveAccountId.next(token.effective_account_id); - } else { - this.superadmin.next(false); - this.admin.next(false); - this.login.next(''); - this.email.next(''); - this.organizationName.next(''); - this.impersonating.next(false); - this.realAccountId.next(''); - this.effectiveAccountId.next(''); - } - }); const data = localStorage.getItem(CredentialService.KEY_GRANT); const id = data ? (JSON.parse(data) as AccessToken) : undefined; if (id && new Date(id.expires_at).getTime() >= Date.now()) { - this.identityToken.next(id); + this.identityToken.set(id); this.validating.next(true); setTimeout(() => this.refreshAccessToken(id), 0); } @@ -101,12 +84,9 @@ export class CredentialService { public requestOtk(email: string, password: string): Observable { const request = ++this.request; this.validating.next(true); - this.authenticated.next(false); - this.organization.next(undefined); - this.superadmin.next(false); - this.admin.next(false); - this.identityToken.next(undefined); - this.accessToken.next(undefined); + this.isAuthenticated.next(false); + this.identityToken.set(undefined); + this.accessToken.set(undefined); return this.authService .requestOtk({ email: email.trim().toLowerCase(), password }) @@ -133,12 +113,7 @@ export class CredentialService { ): Observable { const request = ++this.request; this.validating.next(true); - this.authenticated.next(false); - this.organization.next(undefined); - this.superadmin.next(false); - this.admin.next(false); - this.identityToken.next(undefined); - this.accessToken.next(undefined); + this.isAuthenticated.next(false); return this.authService .login({ account_id: accountId, email_code: emailCode.trim() }) @@ -148,21 +123,7 @@ export class CredentialService { const idToken = response.id_token; - // const token: TimedIdentityGrant = { - // accountId, - // grant: { - // token_type: 'ID', - // access_token: response.id_token.raw_token, - // expires_in: Math.max( - // new Date(response.id_token.expires_at).getTime() - - // Math.floor(Date.now() / 1000), - // 0, - // ), - // scope: this.buildIdentityScope(accountId, email), - // }, - // expiration: new Date(response.id_token.expires_at).getTime(), - // }; - this.identityToken.next(idToken); + this.identityToken.set(idToken); localStorage.setItem( CredentialService.KEY_GRANT, JSON.stringify(idToken), @@ -175,51 +136,47 @@ export class CredentialService { public refreshAccessToken(identityToken: IdToken) { const request = ++this.request; this.validating.next(true); - this.accessToken.next(undefined); + this.accessToken.set(undefined); this.getAccessGrantForIdentity(identityToken, request).subscribe({ error: () => { if (this.request != request) return; - this.identityToken.next(undefined); - this.organization.next(undefined); - this.authenticated.next(false); - this.superadmin.next(false); - this.admin.next(false); - this.validating.next(false); + this.identityToken.set(undefined); }, }); } public impersonateAccount(accountId: string): Observable { - if (!this.identityToken.value) { + const idToken = this.identityToken(); + + if (!idToken) { return throwError(() => new Error('No identity token available.')); } const request = ++this.request; this.validating.next(true); - this.accessToken.next(undefined); - return this.getAccessGrantForIdentity( - this.identityToken.value, - request, - accountId, - ).pipe(tap({ error: () => this.validating.next(false) })); + this.accessToken.set(undefined); + return this.getAccessGrantForIdentity(idToken, request, accountId).pipe( + tap({ error: () => this.validating.next(false) }), + ); } public stopImpersonating(): Observable { - if (!this.identityToken.value) { + const idToken = this.identityToken(); + + if (!idToken) { return throwError(() => new Error('No identity token available.')); } const request = ++this.request; this.validating.next(true); - this.accessToken.next(undefined); - return this.getAccessGrantForIdentity( - this.identityToken.value, - request, - ).pipe(tap({ error: () => this.validating.next(false) })); + this.accessToken.set(undefined); + return this.getAccessGrantForIdentity(idToken, request).pipe( + tap({ error: () => this.validating.next(false) }), + ); } public logoutAccount(): Observable { - const wasImpersonating = this.impersonating.value; + const wasImpersonating = this.isImpersonating(); return this.authService .logout('body', false, { transferCache: false }) @@ -249,13 +206,8 @@ export class CredentialService { public clearLocalAuthState(): void { this.request += 1; localStorage.removeItem(CredentialService.KEY_GRANT); - this.authenticated.next(false); - this.organization.next(undefined); - this.superadmin.next(false); - this.admin.next(false); - this.identityToken.next(undefined); - this.accessToken.next(undefined); - this.validating.next(false); + this.identityToken.set(undefined); + this.accessToken.set(undefined); } public handleUnauthorized(): Observable { @@ -265,8 +217,11 @@ export class CredentialService { this.handlingUnauthorized = true; + const isImpersonating = this.isImpersonating(); + const identityToken = this.identityToken(); + const recovery$ = - this.impersonating.value && this.identityToken.value + isImpersonating && identityToken ? this.stopImpersonating().pipe( map(() => 'stopped-impersonating' as const), catchError((error) => { @@ -312,29 +267,30 @@ export class CredentialService { //review: arman (generated fix) public getBearerToken(): Observable { + const accessToken = this.accessToken(); + const identityToken = this.identityToken(); + // 1. If we have a valid access token, return it immediately and complete. if ( - this.accessToken.value && - Date.now() < new Date(this.accessToken.value.expires_at).getTime() + accessToken && + Date.now() < new Date(accessToken.expires_at).getTime() ) { - return of(this.accessToken.value.raw_token); + return of(accessToken.raw_token); } // 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh. if (!this.validating.value) { - if (!this.identityToken.value) { + if (!identityToken) { return of(undefined); // No identity token to refresh with. } - this.refreshAccessToken(this.identityToken.value); + this.refreshAccessToken(identityToken); } // 3. Wait for the validation to finish, then return the resulting token. return this.validating.pipe( filter((isValidating) => !isValidating), // Wait until validating becomes false take(1), // Take exactly 1 emission and then automatically complete() - map(() => - this.accessToken.value ? this.accessToken.value.raw_token : undefined, - ), + map(() => (accessToken ? accessToken.raw_token : undefined)), ); } @@ -363,9 +319,8 @@ export class CredentialService { const accessToken = result.access_token; - this.accessToken.next(accessToken); - this.organization.next(accessToken.effective_organization_id); - this.authenticated.next(true); + this.accessToken.set(accessToken); + this.isAuthenticated.next(true); this.validating.next(false); }), map(() => undefined), diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 3de4c98b..f4ae841c 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -3,7 +3,7 @@ - @if (credentialService.authenticated | async) { + @if (credentialService.isAuthenticated | async) { } - @if (credentialService.authenticated | async) { - @if (credentialService.impersonating | async) { + @if (credentialService.isAuthenticated | async) { + @if (credentialService.isImpersonating()) {
switch_account Impersonation aktiv diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 32280b16..127f842d 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -6,7 +6,7 @@ import { ViewChild, inject, } from '@angular/core'; -import { CommonModule } from '@angular/common'; +import { CommonModule, Location } from '@angular/common'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; @@ -16,7 +16,6 @@ import { MediaMatcher } from '@angular/cdk/layout'; import { AppMenuComponent } from '../app-menu/app-menu.component'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CredentialService } from '../../services/credential.service'; -import { Location } from '@angular/common'; import { AppSearchbarComponent } from '../app-searchbar/app-searchbar.component'; import { ResolverStateService } from '../../services/resolver-state.service'; import { LoadingComponent } from '../loading/loading.component'; @@ -52,7 +51,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy { constructor( public credentialService: CredentialService, public router: Router, - private location: Location, + private readonly location: Location, public changeDetector: ChangeDetectorRef, media: MediaMatcher, ) { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index 7a766163..bbe843c4 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -44,8 +44,8 @@ @for (item of navItems; track item.label) { @if ( !item.adminOnly || - (credentialService.superadmin | async) || - (credentialService.admin | async) + credentialService.isEffectiveSuperAdmin() || + credentialService.isEffectiveAdmin() ) { @if (collapsed()) { Date: Sat, 27 Jun 2026 13:57:18 +0200 Subject: [PATCH 17/31] fix(auth): reset frontend auth state on logout and failed refresh --- webapp/src/app/shared/services/credential.service.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index d3d4a569..ed9134fa 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -140,7 +140,7 @@ export class CredentialService { this.getAccessGrantForIdentity(identityToken, request).subscribe({ error: () => { if (this.request != request) return; - this.identityToken.set(undefined); + this.clearLocalAuthState(); }, }); } @@ -208,6 +208,11 @@ export class CredentialService { localStorage.removeItem(CredentialService.KEY_GRANT); this.identityToken.set(undefined); this.accessToken.set(undefined); + this.isAuthenticated.next(false); + this.validating.next(false); + this.login.next(''); + this.email.next(''); + this.organizationName.next(''); } public handleUnauthorized(): Observable { @@ -290,7 +295,7 @@ export class CredentialService { return this.validating.pipe( filter((isValidating) => !isValidating), // Wait until validating becomes false take(1), // Take exactly 1 emission and then automatically complete() - map(() => (accessToken ? accessToken.raw_token : undefined)), + map(() => this.accessToken()?.raw_token), ); } From 4b6ad1ec3df52880dff8409b546a31635c0ea9e4 Mon Sep 17 00:00:00 2001 From: Roman Date: Sat, 27 Jun 2026 14:16:45 +0200 Subject: [PATCH 18/31] show effective account profile in sidebar --- .../app/shared/services/credential.service.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index ed9134fa..8e72953f 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -15,6 +15,7 @@ import { Configuration, IdToken, LoginResponse, + AccountProfile, } from '../../api'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @@ -76,9 +77,7 @@ export class CredentialService { } public validateCurrentSession(): Observable { - return this.httpClient - .get(`${this.apiBasePath}/api/accounts/me`, { withCredentials: true }) - .pipe(map(() => undefined)); + return this.loadCurrentProfile(); } public requestOtk(email: string, password: string): Observable { @@ -335,4 +334,19 @@ export class CredentialService { private get apiBasePath(): string { return this.apiConfiguration?.basePath ?? ''; } + + private loadCurrentProfile(): Observable { + return this.httpClient + .get(`${this.apiBasePath}/api/accounts/me`, { + withCredentials: true, + }) + .pipe( + tap((profile) => { + this.login.next(profile.name ?? profile.email ?? ''); + this.email.next(profile.email ?? ''); + this.organizationName.next(profile.organization_name ?? ''); + }), + map(() => undefined), + ); + } } From 1019cedb97ca9ea5c5a5600ade575c79bdf868e8 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 27 Jun 2026 13:59:19 +0200 Subject: [PATCH 19/31] Add SMTP support for OTK emails --- service/src/main/inse/auth/email_service.py | 29 +++++++++++++++++++++ service/src/main/inse/auth/service.py | 29 ++++++++++++--------- service/src/main/inse/config.py | 8 ++++++ 3 files changed, 54 insertions(+), 12 deletions(-) create mode 100644 service/src/main/inse/auth/email_service.py diff --git a/service/src/main/inse/auth/email_service.py b/service/src/main/inse/auth/email_service.py new file mode 100644 index 00000000..85ef913c --- /dev/null +++ b/service/src/main/inse/auth/email_service.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/service.py b/service/src/main/inse/auth/service.py index d88e5c0c..2845ef62 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -27,7 +27,8 @@ from inse.auth.model import ( ) from inse.config import get_settings from inse.database import get_session -from sqlmodel import Session, func, select +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 @@ -210,19 +211,23 @@ def request_otk(session: Session, email: str, password: str): session.commit() - if settings.environment == "prod": - logger.info( - "Saved OTK for account %s with expiration at %s", - account.id, - expires_at, + 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 code for account %s: %s, expires at %s", - account.id, - otk_code, - expires_at, - ) + logger.info("OTK generated for account %s", account.id) return {"status": "ok", "account_id": str(account.id)} diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 717f01ea..944e0185 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -68,6 +68,14 @@ class Settings(BaseSettings): token_hmac_key: Optional[str] = None skip_otk_validation: bool = True + # SMTP / email config + send_otk_email: bool = False + smtp_server: str = "localhost" + smtp_port: int = 25 + smtp_sender: str = "no-reply@smartguide.local" + smtp_username: Optional[str] = None + smtp_password: Optional[str] = None + smtp_use_tls: bool = False settings = Settings() From c8179d44f6ea387eceed73a721a95cdf7119374a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 28 Jun 2026 15:27:53 +0200 Subject: [PATCH 20/31] Added tests for auth service --- service/src/main/inse/auth/__init__.py | 0 service/src/main/inse/auth/service.py | 15 +- .../src/main/inse/auth/test_auth_service.py | 517 ++++++++++++++++++ 3 files changed, 529 insertions(+), 3 deletions(-) create mode 100644 service/src/main/inse/auth/__init__.py create mode 100644 service/src/main/inse/auth/test_auth_service.py diff --git a/service/src/main/inse/auth/__init__.py b/service/src/main/inse/auth/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 2845ef62..ff9e518f 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -4,8 +4,6 @@ import json import logging import secrets import uuid -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText from typing import Annotated, Any, Dict, Literal, Optional import jwt @@ -261,7 +259,18 @@ def login( ).first() if not settings.skip_otk_validation: - if secret is None or secret.expires_at <= now: + 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, diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py new file mode 100644 index 00000000..cc647292 --- /dev/null +++ b/service/src/main/inse/auth/test_auth_service.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="Test Org") + 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) From dfa9c70a255ef8941f6425105331ee82201a58a6 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 18:35:15 +0200 Subject: [PATCH 21/31] removed httpx imports --- service/src/main/inse/logic.py | 1 - service/src/main/inse/patents/logic.py | 1 - service/src/main/inse/persons/logic.py | 1 - service/src/main/inse/projects/projects_search_client.py | 1 - service/src/main/inse/works/logic.py | 1 - service/src/main/inse/works/test_search_client.py | 1 - 6 files changed, 6 deletions(-) diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index bc3edcf6..ae1dc1c7 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -13,7 +13,6 @@ from sqlalchemy.orm import Session from sqlalchemy import select from sqlalchemy import func import logging -import httpx import json from . import schema from . import model diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 9ff5b490..de39f902 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -6,7 +6,6 @@ import logging import asyncio -import httpx from ..persons import logic as person_logic from ..models.openalex.author import Author diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index a7d74fde..bc96081d 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -10,7 +10,6 @@ import time from datetime import datetime from typing import Optional, Callable, Any, List import hashlib -import httpx from inse.exceptions import ( NotFoundException, ElasticsearchException, diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index bbb09625..22acb5bd 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -2,7 +2,6 @@ import json import logging from typing import Any, Dict, List, Optional, Set, Tuple -import httpx import urllib from inse.config import get_settings from inse.models.bund_project import BundProject diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 2ffb73e4..eb36f5a9 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -8,7 +8,6 @@ import logging from time import time from typing import Any, List -import httpx from pydantic import ValidationError from starlette.status import HTTP_404_NOT_FOUND diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 39dbf091..2d9e2a41 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -1,6 +1,5 @@ import json -import httpx import pytest from inse.exceptions import MissingApiKeyError From 5a91887861d4eca49657de0a80e65e52f2b7bc06 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Mon, 29 Jun 2026 19:11:03 +0200 Subject: [PATCH 22/31] implement organisation management --- service/src/main/inse/auth/model.py | 5 +- service/src/main/inse/main.py | 2 + .../inse/organization_management/__init__.py | 1 + .../inse/organization_management/model.py | 30 +++ .../inse/organization_management/router.py | 81 ++++++++ .../inse/organization_management/service.py | 183 ++++++++++++++++++ .../organization_management/test_service.py | 181 +++++++++++++++++ service/src/main/inse/tags.py | 1 + webapp/src/app/app.routes.ts | 9 + .../organization-dialog.component.html | 38 ++++ .../organization-dialog.component.scss | 20 ++ .../organization-dialog.component.ts | 105 ++++++++++ .../organizations.component.html | 105 ++++++++++ .../organizations.component.scss | 130 +++++++++++++ .../organizations/organizations.component.ts | 158 +++++++++++++++ .../app/shared/guards/super-admin.guard.ts | 31 +++ .../organization-management.service.ts | 75 +++++++ .../ui/app-menu/app-menu.component.html | 9 +- .../shared/ui/app-menu/app-menu.component.ts | 8 + 19 files changed, 1167 insertions(+), 5 deletions(-) create mode 100644 service/src/main/inse/organization_management/__init__.py create mode 100644 service/src/main/inse/organization_management/model.py create mode 100644 service/src/main/inse/organization_management/router.py create mode 100644 service/src/main/inse/organization_management/service.py create mode 100644 service/src/main/inse/organization_management/test_service.py create mode 100644 webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.html create mode 100644 webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.scss create mode 100644 webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts create mode 100644 webapp/src/app/modules/organizations/organizations.component.html create mode 100644 webapp/src/app/modules/organizations/organizations.component.scss create mode 100644 webapp/src/app/modules/organizations/organizations.component.ts create mode 100644 webapp/src/app/shared/guards/super-admin.guard.ts create mode 100644 webapp/src/app/shared/services/organization-management.service.ts diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 1c8922d3..a79aa113 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -36,7 +36,10 @@ class Organization(Durable, table=True): description="Unique identifier for the organization. Generated automatically if not provided.", ) name: str = Field( - index=True, nullable=False, description="The name of the organization." + index=True, + unique=True, + nullable=False, + description="The unique name of the organization.", ) openalex_institution_id: str | None = Field( default=None, diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 443107d7..7ca533dd 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -30,6 +30,7 @@ from inse.patents.service import router as patents_service_router from inse.auth.router import router as auth_router from inse.account_management.router import router as account_management_router +from inse.organization_management.router import router as organization_management_router from inse.institutions.router import router as institutions_router @@ -80,6 +81,7 @@ app.include_router(service_router) app.include_router(auth_router) app.include_router(account_management_router) +app.include_router(organization_management_router) app.add_middleware( ETagCacheMiddleware, diff --git a/service/src/main/inse/organization_management/__init__.py b/service/src/main/inse/organization_management/__init__.py new file mode 100644 index 00000000..9955b679 --- /dev/null +++ b/service/src/main/inse/organization_management/__init__.py @@ -0,0 +1 @@ +"""Organization management API.""" diff --git a/service/src/main/inse/organization_management/model.py b/service/src/main/inse/organization_management/model.py new file mode 100644 index 00000000..e5e0a615 --- /dev/null +++ b/service/src/main/inse/organization_management/model.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.py b/service/src/main/inse/organization_management/router.py new file mode 100644 index 00000000..0a8b82ca --- /dev/null +++ b/service/src/main/inse/organization_management/router.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.py b/service/src/main/inse/organization_management/service.py new file mode 100644 index 00000000..56d97db2 --- /dev/null +++ b/service/src/main/inse/organization_management/service.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.py b/service/src/main/inse/organization_management/test_service.py new file mode 100644 index 00000000..ce3b3e03 --- /dev/null +++ b/service/src/main/inse/organization_management/test_service.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/tags.py b/service/src/main/inse/tags.py index bcfcd086..08fc4bd0 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -11,3 +11,4 @@ class Tags(StrEnum): PROJECTS = "Projects" AUTH = "Auth" ACCOUNT = "Account" + ORGANIZATION = "Organization" diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index ac7dbf07..5fcca07d 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -1,6 +1,7 @@ import { Routes } from '@angular/router'; import { userGuard } from './shared/guards/user.guard'; import { adminGuard } from './shared/guards/admin.guard'; +import { superAdminGuard } from './shared/guards/super-admin.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; import { personListResolver } from './resolvers/person-list.resolver'; import { personBioResolver } from './resolvers/person-bio.resolver'; @@ -99,6 +100,14 @@ export const routes: Routes = [ (mod) => mod.AccountsComponent, ), }, + { + path: 'organizations', + canActivate: [superAdminGuard], + loadComponent: () => + import('./modules/organizations/organizations.component').then( + (mod) => mod.OrganizationsComponent, + ), + }, { path: 'news/:id', canActivate: [userGuard], diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.html b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.html new file mode 100644 index 00000000..ee5a86f6 --- /dev/null +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.html @@ -0,0 +1,38 @@ +

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

+ + +
+ + Name + + @if (form.controls.name.hasError('required')) { + Name ist erforderlich. + } + + + + Externe Institutions-ID + + + + @if (data.mode === 'edit') { + + Organisation als gelöscht markieren + + } +
+
+ + + + + diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.scss b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.scss new file mode 100644 index 00000000..73a882d6 --- /dev/null +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.scss @@ -0,0 +1,20 @@ +.organization-form { + display: grid; + gap: 12px; + min-width: min(540px, calc(100vw - 64px)); + padding-top: 4px; +} + +.organization-form mat-form-field { + width: 100%; +} + +mat-dialog-actions { + padding: 12px 24px 20px; +} + +@media (max-width: 600px) { + .organization-form { + min-width: 0; + } +} diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts new file mode 100644 index 00000000..6348c11f --- /dev/null +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts @@ -0,0 +1,105 @@ +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 { MatCheckboxModule } from '@angular/material/checkbox'; +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 type { + CreateOrganizationPayload, + OrganizationProfile, + UpdateOrganizationPayload, +} from '../../../shared/services/organization-management.service'; + +export interface OrganizationDialogData { + mode: 'create' | 'edit'; + organization?: OrganizationProfile; +} + +export type OrganizationDialogResult = + | { mode: 'create'; payload: CreateOrganizationPayload } + | { + mode: 'edit'; + organizationId: string; + payload: UpdateOrganizationPayload; + }; + +@Component({ + selector: 'app-organization-dialog', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatCheckboxModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + ], + templateUrl: './organization-dialog.component.html', + styleUrl: './organization-dialog.component.scss', + standalone: true, +}) +export class OrganizationDialogComponent { + private readonly dialogRef = + inject< + MatDialogRef< + OrganizationDialogComponent, + OrganizationDialogResult | undefined + > + >(MatDialogRef); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly form = new FormGroup({ + name: new FormControl(this.data.organization?.name ?? '', { + nonNullable: true, + validators: [Validators.required], + }), + otherInstId: new FormControl( + this.data.organization?.other_inst_id ?? '', + { nonNullable: true }, + ), + deleted: new FormControl(this.data.organization?.deleted ?? false, { + nonNullable: true, + }), + }); + + protected submit(): void { + if (this.form.invalid) { + this.form.markAllAsTouched(); + return; + } + + const value = this.form.getRawValue(); + const payload = { + name: value.name.trim(), + other_inst_id: value.otherInstId.trim(), + }; + + if (this.data.mode === 'create') { + this.dialogRef.close({ mode: 'create', payload }); + return; + } + + this.dialogRef.close({ + mode: 'edit', + organizationId: this.data.organization!.id, + payload: { ...payload, deleted: value.deleted }, + }); + } + + protected close(): void { + this.dialogRef.close(undefined); + } +} diff --git a/webapp/src/app/modules/organizations/organizations.component.html b/webapp/src/app/modules/organizations/organizations.component.html new file mode 100644 index 00000000..a6486b74 --- /dev/null +++ b/webapp/src/app/modules/organizations/organizations.component.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.scss b/webapp/src/app/modules/organizations/organizations.component.scss new file mode 100644 index 00000000..b558f858 --- /dev/null +++ b/webapp/src/app/modules/organizations/organizations.component.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.ts b/webapp/src/app/modules/organizations/organizations.component.ts new file mode 100644 index 00000000..0d061c50 --- /dev/null +++ b/webapp/src/app/modules/organizations/organizations.component.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/shared/guards/super-admin.guard.ts b/webapp/src/app/shared/guards/super-admin.guard.ts new file mode 100644 index 00000000..b1936483 --- /dev/null +++ b/webapp/src/app/shared/guards/super-admin.guard.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/organization-management.service.ts b/webapp/src/app/shared/services/organization-management.service.ts new file mode 100644 index 00000000..9597a005 --- /dev/null +++ b/webapp/src/app/shared/services/organization-management.service.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/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index bbe843c4..159f2598 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -43,9 +43,11 @@ @for (item of navItems; track item.label) { @if ( - !item.adminOnly || - credentialService.isEffectiveSuperAdmin() || - credentialService.isEffectiveAdmin() + (!item.adminOnly || + credentialService.isEffectiveSuperAdmin() || + credentialService.isEffectiveAdmin()) && + (!item.superAdminOnly || + credentialService.isEffectiveSuperAdmin()) ) { @if (collapsed()) {
{{ credentialService.organizationName | async }} - Startup Coach
expand_more diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 37eaaca7..e8e34eb1 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -22,6 +22,7 @@ type NavItem = { disabled: boolean; queryParams?: Record; adminOnly?: boolean; + superAdminOnly?: boolean; }; @Component({ @@ -106,6 +107,13 @@ export class AppMenuComponent { disabled: false, adminOnly: true, }, + { + label: 'Organisationen', + icon: 'domain', + route: '/organizations', + disabled: false, + superAdminOnly: true, + }, ]; constructor( From 97ba57b9a263750019ac0d61eebfacb31026c162 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Mon, 29 Jun 2026 19:36:11 +0200 Subject: [PATCH 23/31] fix test service --- service/src/main/inse/auth/test_auth_service.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index cc647292..7db19bb4 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -43,7 +43,7 @@ def in_memory_session(): def create_org_and_account( session: Session, email: str, password: str, role=UserRole.USER ): - org = Organization(name="Test Org") + org = Organization(name=f"Test Org {email}") session.add(org) session.flush() assert org.id is not None From eb8780e9f9cef1f9c2e5f015e3b5755e3bbe33e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 30 Jun 2026 08:23:42 +0200 Subject: [PATCH 24/31] Added openalex institution id for predefined organizations --- service/src/data/predefined_accounts.json | 6 +++--- service/src/main/inse/auth/service.py | 11 ++++++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/service/src/data/predefined_accounts.json b/service/src/data/predefined_accounts.json index b6bf36da..9bd44c0c 100644 --- a/service/src/data/predefined_accounts.json +++ b/service/src/data/predefined_accounts.json @@ -6,15 +6,15 @@ }, { "name": "Universität Duisburg-Essen", - "openalex_instution_id": "https://openalex.org/I62318514" + "openalex_institution_id": "I62318514" }, { "name": "Ruhr-Universität Bochum", - "openalex_instution_id": "https://openalex.org/I904495901" + "openalex_institution_id": "I904495901" }, { "name": "TU Dortmund", - "openalex_instution_id": "https://openalex.org/I200332995" + "openalex_institution_id": "I200332995" } ], "accounts": [ diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index ff9e518f..3c24086e 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -87,7 +87,16 @@ def create_predefined_accounts(session: Session, file_path: str): 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) + openalex_institution_id = organization_data.get( + "openalex_institution_id" + ) + if openalex_institution_id is not None: + openalex_institution_id = str(openalex_institution_id) + organization = Organization( + id=organization_id, + name=organization_name, + openalex_institution_id=openalex_institution_id, + ) session.add(organization) for account_data in data.get("accounts", []): organization_id = uuid.UUID(account_data["organization_id"]) From 9388ad9bdba3e0ee5a9d11bbe321a461a40dcc32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 30 Jun 2026 08:30:31 +0200 Subject: [PATCH 25/31] Added optional group separator for app menu --- .../ui/app-menu/app-menu.component.html | 62 +++++++++++-------- .../ui/app-menu/app-menu.component.scss | 11 ++++ .../shared/ui/app-menu/app-menu.component.ts | 16 +++++ 3 files changed, 62 insertions(+), 27 deletions(-) diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index 159f2598..1d34aefc 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -46,34 +46,42 @@ (!item.adminOnly || credentialService.isEffectiveSuperAdmin() || credentialService.isEffectiveAdmin()) && - (!item.superAdminOnly || - credentialService.isEffectiveSuperAdmin()) + (!item.superAdminOnly || credentialService.isEffectiveSuperAdmin()) ) { - @if (collapsed()) { - - {{ item.icon }} - - } @else { - - {{ item.icon }} - {{ item.label }} - + @if (item.type === 'link') { + @if (collapsed()) { + + {{ item.icon }} + + } @else { + + {{ item.icon }} + {{ item.label }} + + } + } @else if (item.type === 'separator') { + + @if (!collapsed()) { + + } } } } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.scss b/webapp/src/app/shared/ui/app-menu/app-menu.component.scss index 70c13978..0a3cc8fb 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.scss +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.scss @@ -277,3 +277,14 @@ .sidebar--collapsed .account-icon { margin-inline: auto; } + +.nav-separator { + display: flex; + align-items: center; + gap: 8px; + padding: 0 12px; + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 600; + text-transform: uppercase; +} diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index e8e34eb1..ce9c80aa 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -16,6 +16,7 @@ import { MatDialog } from '@angular/material/dialog'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; type NavItem = { + type: 'link' | 'separator'; label: string; icon: string; route: string; @@ -53,12 +54,14 @@ export class AppMenuComponent { }; navItems: NavItem[] = [ { + type: 'link', label: 'Dashboard', icon: 'dashboard', route: '/dashboard', disabled: false, }, { + type: 'link', label: 'Personen', icon: 'groups', route: '/persons', @@ -68,12 +71,14 @@ export class AppMenuComponent { disabled: false, }, { + type: 'link', label: 'News', icon: 'newspaper', route: '/news', disabled: false, }, { + type: 'link', label: 'Institutionen', icon: 'apartment', route: '/institutions', @@ -87,6 +92,7 @@ export class AppMenuComponent { }, }, { + type: 'link', label: 'Projekte', icon: 'work', route: '/projects', @@ -101,6 +107,15 @@ export class AppMenuComponent { }, }, { + type: 'separator', + label: 'Verwaltung', + icon: '', + route: '', + disabled: false, + adminOnly: true, + }, + { + type: 'link', label: 'Accounts', icon: 'manage_accounts', route: '/accounts', @@ -108,6 +123,7 @@ export class AppMenuComponent { adminOnly: true, }, { + type: 'link', label: 'Organisationen', icon: 'domain', route: '/organizations', From 05eb9a3b5030cacec1bd49fb79b2323ef247aa09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 30 Jun 2026 08:46:15 +0200 Subject: [PATCH 26/31] Updated app menu grouping structure --- .../ui/app-menu/app-menu.component.html | 76 ++++++++++--------- .../shared/ui/app-menu/app-menu.component.ts | 44 +++++++---- 2 files changed, 67 insertions(+), 53 deletions(-) diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index 1d34aefc..d946b5aa 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -41,49 +41,51 @@ - @for (item of navItems; track item.label) { - @if ( - (!item.adminOnly || - credentialService.isEffectiveSuperAdmin() || - credentialService.isEffectiveAdmin()) && - (!item.superAdminOnly || credentialService.isEffectiveSuperAdmin()) - ) { - @if (item.type === 'link') { - @if (collapsed()) { - - {{ item.icon }} - - } @else { - - {{ item.icon }} - {{ item.label }} - - } - } @else if (item.type === 'separator') { + @for (itemGroup of navItemGroups; track $index) { +
+ @if ( + (!itemGroup.adminOnly || + credentialService.isEffectiveSuperAdmin() || + credentialService.isEffectiveAdmin()) && + (!itemGroup.superAdminOnly || + credentialService.isEffectiveSuperAdmin()) + ) { @if (!collapsed()) { } + @for (item of itemGroup.items; track item.label) { + @if (collapsed()) { + + {{ item.icon }} + + } @else { + + {{ item.icon }} + {{ item.label }} + + } + } } - } +
}
diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index ce9c80aa..66abe19e 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -16,7 +16,6 @@ import { MatDialog } from '@angular/material/dialog'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; type NavItem = { - type: 'link' | 'separator'; label: string; icon: string; route: string; @@ -26,6 +25,13 @@ type NavItem = { superAdminOnly?: boolean; }; +type NavItemGroup = { + label: string; + items: NavItem[]; + adminOnly?: boolean; + superAdminOnly?: boolean; +}; + @Component({ selector: 'app-menu', imports: [ @@ -52,16 +58,15 @@ export class AppMenuComponent { matrixParams: 'ignored', fragment: 'ignored', }; + navItems: NavItem[] = [ { - type: 'link', label: 'Dashboard', icon: 'dashboard', route: '/dashboard', disabled: false, }, { - type: 'link', label: 'Personen', icon: 'groups', route: '/persons', @@ -71,14 +76,12 @@ export class AppMenuComponent { disabled: false, }, { - type: 'link', label: 'News', icon: 'newspaper', route: '/news', disabled: false, }, { - type: 'link', label: 'Institutionen', icon: 'apartment', route: '/institutions', @@ -92,7 +95,6 @@ export class AppMenuComponent { }, }, { - type: 'link', label: 'Projekte', icon: 'work', route: '/projects', @@ -107,15 +109,6 @@ export class AppMenuComponent { }, }, { - type: 'separator', - label: 'Verwaltung', - icon: '', - route: '', - disabled: false, - adminOnly: true, - }, - { - type: 'link', label: 'Accounts', icon: 'manage_accounts', route: '/accounts', @@ -123,7 +116,6 @@ export class AppMenuComponent { adminOnly: true, }, { - type: 'link', label: 'Organisationen', icon: 'domain', route: '/organizations', @@ -131,6 +123,26 @@ export class AppMenuComponent { superAdminOnly: true, }, ]; + navItemGroups: NavItemGroup[] = [ + { + label: 'Navigation', + items: this.navItems.filter( + (item) => !item.adminOnly && !item.superAdminOnly, + ), + }, + { + label: 'Administration', + items: this.navItems.filter( + (item) => item.adminOnly && !item.superAdminOnly, + ), + adminOnly: true, + }, + { + label: 'Super Administration', + items: this.navItems.filter((item) => item.superAdminOnly), + superAdminOnly: true, + }, + ]; constructor( public credentialService: CredentialService, From ab18134c581dd3731bb0d85954cd49607eef2a3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 30 Jun 2026 14:28:30 +0200 Subject: [PATCH 27/31] Added initial account page --- webapp/src/app/api/.openapi-generator/FILES | 7 +- webapp/src/app/api/api/api.ts | 4 +- webapp/src/app/api/api/auth.service.ts | 12 +- .../src/app/api/api/organization.service.ts | 310 ++++++++++++++++++ .../api/model/createOrganizationRequest.ts | 16 + ...ountManagementModelOrganizationProfile.ts} | 2 +- ...ationManagementModelOrganizationProfile.ts | 19 ++ webapp/src/app/api/model/models.ts | 6 +- webapp/src/app/api/model/organizationPage.ts | 19 ++ .../api/model/updateOrganizationRequest.ts | 17 + webapp/src/app/app.config.ts | 2 +- webapp/src/app/app.routes.ts | 12 + .../modules/account/account.component.html | 20 ++ .../modules/account/account.component.scss | 44 +++ .../app/modules/account/account.component.ts | 24 ++ .../modules/accounts/accounts.component.html | 2 +- .../modules/accounts/accounts.component.ts | 5 +- .../person-interesting.component.ts | 2 +- .../research-timeline.component.ts | 4 +- .../person-publications.component.ts | 2 +- webapp/src/app/resolvers/account.resolver.ts | 8 + .../utils/errorHandler.ts | 0 .../{shared => resolvers}/utils/filters.ts | 0 .../utils/paginatorIntl.ts | 0 .../utils/topic-colors.ts | 0 .../utils/topic-tooltip.ts | 0 webapp/src/app/shared/pipes/role.pipe.ts | 22 ++ .../services/account-management.service.ts | 13 +- .../ui/app-menu/app-menu.component.html | 25 +- .../ui/app-menu/app-menu.component.scss | 14 +- .../shared/ui/app-menu/app-menu.component.ts | 13 +- .../ui/topic-chip/topic-chip.component.ts | 2 +- 32 files changed, 580 insertions(+), 46 deletions(-) create mode 100644 webapp/src/app/api/api/organization.service.ts create mode 100644 webapp/src/app/api/model/createOrganizationRequest.ts rename webapp/src/app/api/model/{organizationProfile.ts => inseAccountManagementModelOrganizationProfile.ts} (81%) create mode 100644 webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts create mode 100644 webapp/src/app/api/model/organizationPage.ts create mode 100644 webapp/src/app/api/model/updateOrganizationRequest.ts create mode 100644 webapp/src/app/modules/account/account.component.html create mode 100644 webapp/src/app/modules/account/account.component.scss create mode 100644 webapp/src/app/modules/account/account.component.ts create mode 100644 webapp/src/app/resolvers/account.resolver.ts rename webapp/src/app/{shared => resolvers}/utils/errorHandler.ts (100%) rename webapp/src/app/{shared => resolvers}/utils/filters.ts (100%) rename webapp/src/app/{shared => resolvers}/utils/paginatorIntl.ts (100%) rename webapp/src/app/{shared => resolvers}/utils/topic-colors.ts (100%) rename webapp/src/app/{shared => resolvers}/utils/topic-tooltip.ts (100%) create mode 100644 webapp/src/app/shared/pipes/role.pipe.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index afff695a..1b1f7bc6 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -10,6 +10,7 @@ api/funding.service.ts api/iNSEService.service.ts api/institutions.service.ts api/news.service.ts +api/organization.service.ts api/patents.service.ts api/personNetwork.service.ts api/persons.service.ts @@ -56,6 +57,7 @@ model/cordisEuProject.ts model/cordisEuProjectPage.ts model/costUsd.ts model/createAccountRequest.ts +model/createOrganizationRequest.ts model/customAuthor.ts model/customAuthorsListResponse.ts model/dehydratedAuthor.ts @@ -77,6 +79,8 @@ model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts model/idToken.ts +model/inseAccountManagementModelOrganizationProfile.ts +model/inseOrganizationManagementModelOrganizationProfile.ts model/institution.ts model/institutionFunderSummary.ts model/institutionGeo.ts @@ -99,7 +103,7 @@ model/newsArticle.ts model/newsArticleDetail.ts model/newsPage.ts model/openAccess.ts -model/organizationProfile.ts +model/organizationPage.ts model/patentEntry.ts model/patentsByAuthorResponse.ts model/personBio.ts @@ -127,6 +131,7 @@ model/topicsListResponse.ts model/universityRanking.ts model/universityTopicData.ts model/updateAccountRequest.ts +model/updateOrganizationRequest.ts model/userRole.ts model/validationError.ts model/validationErrorLocInner.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index a7107b6c..62bac5d0 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -10,6 +10,8 @@ export * from './institutions.service'; import { InstitutionsService } from './institutions.service'; export * from './news.service'; import { NewsService } from './news.service'; +export * from './organization.service'; +import { OrganizationService } from './organization.service'; export * from './patents.service'; import { PatentsService } from './patents.service'; export * from './personNetwork.service'; @@ -22,4 +24,4 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; +export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index a927c77c..6beb60cc 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -37,9 +37,9 @@ import { CreateAccountRequest } from '../model/createAccountRequest'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { LoginResponse } from '../model/loginResponse'; +import { InseAccountManagementModelOrganizationProfile } from '../model/inseAccountManagementModelOrganizationProfile'; // @ts-ignore -import { OrganizationProfile } from '../model/organizationProfile'; +import { LoginResponse } from '../model/loginResponse'; // @ts-ignore import { UpdateAccountRequest } from '../model/updateAccountRequest'; @@ -434,9 +434,9 @@ export class AuthService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public 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?: '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; @@ -469,7 +469,7 @@ export class AuthService extends BaseService { let localVarPath = `/api/accounts/organizations`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request>('get', `${basePath}${localVarPath}`, + return this.httpClient.request>('get', `${basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts new file mode 100644 index 00000000..2af0ed8b --- /dev/null +++ b/webapp/src/app/api/api/organization.service.ts @@ -0,0 +1,310 @@ +/** + * 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 { CreateOrganizationRequest } from '../model/createOrganizationRequest'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile'; +// @ts-ignore +import { OrganizationPage } from '../model/organizationPage'; +// @ts-ignore +import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class OrganizationService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Create Organization + * @endpoint post /api/organizations + * @param createOrganizationRequest + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (createOrganizationRequest === null || createOrganizationRequest === undefined) { + throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.'); + } + + 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/organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: createOrganizationRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Delete Organization + * @endpoint delete /api/organizations/{organization_id} + * @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 deleteOrganisation(organizationId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (organizationId === null || organizationId === undefined) { + throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.'); + } + + 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/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, 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 Organizations + * @endpoint get /api/organizations + * @param page + * @param pageSize + * @param offset + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + 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'); + + 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/organizations`; + 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 + } + ); + } + + /** + * Update Organization + * @endpoint put /api/organizations/{organization_id} + * @param organizationId + * @param updateOrganizationRequest + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (organizationId === null || organizationId === undefined) { + throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); + } + if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) { + throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.'); + } + + 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/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, 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: updateOrganizationRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/model/createOrganizationRequest.ts b/webapp/src/app/api/model/createOrganizationRequest.ts new file mode 100644 index 00000000..fffb5457 --- /dev/null +++ b/webapp/src/app/api/model/createOrganizationRequest.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface CreateOrganizationRequest { + name: string; + other_inst_id?: string | null; +} + diff --git a/webapp/src/app/api/model/organizationProfile.ts b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts similarity index 81% rename from webapp/src/app/api/model/organizationProfile.ts rename to webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts index 939671ba..c67acc71 100644 --- a/webapp/src/app/api/model/organizationProfile.ts +++ b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts @@ -9,7 +9,7 @@ */ -export interface OrganizationProfile { +export interface InseAccountManagementModelOrganizationProfile { id: string; name: string; openalex_institution_id?: string | null; diff --git a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts new file mode 100644 index 00000000..404df0f9 --- /dev/null +++ b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.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 interface InseOrganizationManagementModelOrganizationProfile { + id: string; + name: string; + other_inst_id?: string | null; + deleted: boolean; + member_count: number; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 9f8dbc31..3e2afd5c 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -34,6 +34,7 @@ export * from './cordisEuProject'; export * from './cordisEuProjectPage'; export * from './costUsd'; export * from './createAccountRequest'; +export * from './createOrganizationRequest'; export * from './customAuthor'; export * from './customAuthorsListResponse'; export * from './dehydratedAuthor'; @@ -55,6 +56,8 @@ export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; export * from './idToken'; +export * from './inseAccountManagementModelOrganizationProfile'; +export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './institution'; export * from './institutionFunderSummary'; export * from './institutionGeo'; @@ -76,7 +79,7 @@ export * from './newsArticle'; export * from './newsArticleDetail'; export * from './newsPage'; export * from './openAccess'; -export * from './organizationProfile'; +export * from './organizationPage'; export * from './patentEntry'; export * from './patentsByAuthorResponse'; export * from './personBio'; @@ -104,6 +107,7 @@ export * from './topicsListResponse'; export * from './universityRanking'; export * from './universityTopicData'; export * from './updateAccountRequest'; +export * from './updateOrganizationRequest'; export * from './userRole'; export * from './validationError'; export * from './validationErrorLocInner'; diff --git a/webapp/src/app/api/model/organizationPage.ts b/webapp/src/app/api/model/organizationPage.ts new file mode 100644 index 00000000..5b8294b1 --- /dev/null +++ b/webapp/src/app/api/model/organizationPage.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 { InseOrganizationManagementModelOrganizationProfile } from './inseOrganizationManagementModelOrganizationProfile'; + + +export interface OrganizationPage { + items: Array; + total: number; + page: number; + page_size: number; +} + diff --git a/webapp/src/app/api/model/updateOrganizationRequest.ts b/webapp/src/app/api/model/updateOrganizationRequest.ts new file mode 100644 index 00000000..e12063b6 --- /dev/null +++ b/webapp/src/app/api/model/updateOrganizationRequest.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface UpdateOrganizationRequest { + name?: string | null; + other_inst_id?: string | null; + deleted?: boolean | null; +} + diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 1c579be1..3b700752 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -19,7 +19,7 @@ import { registerLocaleData } from '@angular/common'; import { authenticationInterceptor } from './shared/interceptors/authentication.interceptor'; import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field'; import { MatPaginatorIntl } from '@angular/material/paginator'; -import { PaginatorIntl } from './shared/utils/paginatorIntl'; +import { PaginatorIntl } from './resolvers/utils/paginatorIntl'; import { provideEchartsCore } from 'ngx-echarts'; import { ErrorService } from './shared/services/error.service'; import { provideApi } from './api/provide-api'; diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 5fcca07d..88a90229 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -18,6 +18,7 @@ import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page. import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver'; import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; +import { accountResolver } from './resolvers/account.resolver'; export const routes: Routes = [ { @@ -92,6 +93,17 @@ export const routes: Routes = [ loadComponent: () => import('./modules/news/news.component').then((mod) => mod.NewsComponent), }, + { + path: 'account', + canActivate: [userGuard], + loadComponent: () => + import('./modules/account/account.component').then( + (mod) => mod.AccountComponent, + ), + resolve: { + accountProfile: accountResolver, + }, + }, { path: 'accounts', canActivate: [adminGuard], diff --git a/webapp/src/app/modules/account/account.component.html b/webapp/src/app/modules/account/account.component.html new file mode 100644 index 00000000..7590acb3 --- /dev/null +++ b/webapp/src/app/modules/account/account.component.html @@ -0,0 +1,20 @@ +
+ +
+ + + + + + diff --git a/webapp/src/app/modules/account/account.component.scss b/webapp/src/app/modules/account/account.component.scss new file mode 100644 index 00000000..25c46861 --- /dev/null +++ b/webapp/src/app/modules/account/account.component.scss @@ -0,0 +1,44 @@ +.content { + max-width: 100%; +} + +.account-profile-information { + display: flex; + flex-direction: column; + gap: 0.5rem; + justify-content: center; + align-items: center; + padding: 1rem; +} + +.personal-information { + display: flex; + flex-direction: column; + align-items: center; +} + +.role-chip { + font-size: 10px; + font-weight: 600; + color: var(--sg-text-muted); + background: var(--sg-surface-muted); + border-radius: var(--sg-radius-sm); +} + +.name { + font-size: 16px; + font-weight: 600; + color: var(--sg-text-primary); +} + +.mail { + font-size: 12px; + font-weight: 600; + color: var(--sg-text-muted); +} + +.organization { + font-size: 12px; + font-weight: 600; + color: var(--sg-text-muted); +} diff --git a/webapp/src/app/modules/account/account.component.ts b/webapp/src/app/modules/account/account.component.ts new file mode 100644 index 00000000..7a953dee --- /dev/null +++ b/webapp/src/app/modules/account/account.component.ts @@ -0,0 +1,24 @@ +import { Component, effect, input } from '@angular/core'; +import { AccountProfile, UserRole } from '../../api'; +import { RolePipe } from '../../shared/pipes/role.pipe'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatTabsModule } from '@angular/material/tabs'; +import { MatDividerModule } from '@angular/material/divider'; + +@Component({ + selector: 'app-account', + imports: [RolePipe, MatChipsModule, MatTabsModule, MatDividerModule], + templateUrl: './account.component.html', + styleUrl: './account.component.scss', +}) +export class AccountComponent { + readonly accountProfile = input.required(); + + roles: UserRole[] = []; + + constructor() { + effect(() => { + this.roles = [this.accountProfile().role]; + }); + } +} diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 8137c2f2..6a5fdb83 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -79,7 +79,7 @@ {{ account.email }} {{ account.organization_name }} - {{ account.role }} + {{ account.role | role }} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index 845f0990..f02fa6da 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -21,6 +21,7 @@ import type { AccountDialogComponent, AccountDialogResult, } from './account-dialog.component'; +import { RolePipe } from '../../shared/pipes/role.pipe'; @Component({ selector: 'app-accounts', @@ -34,6 +35,7 @@ import type { MatSelectModule, MatSnackBarModule, MatDialogModule, + RolePipe, ], templateUrl: './accounts.component.html', styleUrl: './accounts.component.scss', @@ -164,8 +166,7 @@ export class AccountsComponent implements OnInit { data: { ...data, organizations: this.organizations, - canSelectOrganization: - this.credentialService.isEffectiveSuperAdmin(), + canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(), roles: this.availableRoles, }, }); diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index d8d496aa..5555f149 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -16,7 +16,7 @@ import { ActivatedRoute, Router } from '@angular/router'; import { TopicCount } from '../../api'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; -import { topicHierarchyColor } from '../../shared/utils/topic-colors'; +import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; interface InterestTag { id: string; diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index fa29012f..12f223ce 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -14,8 +14,8 @@ import { ViewChild, } from '@angular/core'; import { TopicChipComponent } from '../../../../shared/ui/topic-chip/topic-chip.component'; -import { topicHierarchyColor } from '../../../../shared/utils/topic-colors'; -import { buildTopicHierarchyTooltip } from '../../../../shared/utils/topic-tooltip'; +import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors'; +import { buildTopicHierarchyTooltip } from '../../../../resolvers/utils/topic-tooltip'; export interface TopicTimelineTopic { id?: string; 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 8ab1923f..183f3caf 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -39,7 +39,7 @@ import { import { Work, WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; -import { createLoadError } from '../../shared/utils/errorHandler'; +import { createLoadError } from '../../resolvers/utils/errorHandler'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; interface InstitutionAutocompleteOption { diff --git a/webapp/src/app/resolvers/account.resolver.ts b/webapp/src/app/resolvers/account.resolver.ts new file mode 100644 index 00000000..9a2b7936 --- /dev/null +++ b/webapp/src/app/resolvers/account.resolver.ts @@ -0,0 +1,8 @@ +import { ResolveFn } from '@angular/router'; +import { AccountProfile } from '../api'; +import { inject } from '@angular/core'; +import { AccountManagementService } from '../shared/services/account-management.service'; + +export const accountResolver: ResolveFn = (route, state) => { + return inject(AccountManagementService).getCurrentAccount(); +}; diff --git a/webapp/src/app/shared/utils/errorHandler.ts b/webapp/src/app/resolvers/utils/errorHandler.ts similarity index 100% rename from webapp/src/app/shared/utils/errorHandler.ts rename to webapp/src/app/resolvers/utils/errorHandler.ts diff --git a/webapp/src/app/shared/utils/filters.ts b/webapp/src/app/resolvers/utils/filters.ts similarity index 100% rename from webapp/src/app/shared/utils/filters.ts rename to webapp/src/app/resolvers/utils/filters.ts diff --git a/webapp/src/app/shared/utils/paginatorIntl.ts b/webapp/src/app/resolvers/utils/paginatorIntl.ts similarity index 100% rename from webapp/src/app/shared/utils/paginatorIntl.ts rename to webapp/src/app/resolvers/utils/paginatorIntl.ts diff --git a/webapp/src/app/shared/utils/topic-colors.ts b/webapp/src/app/resolvers/utils/topic-colors.ts similarity index 100% rename from webapp/src/app/shared/utils/topic-colors.ts rename to webapp/src/app/resolvers/utils/topic-colors.ts diff --git a/webapp/src/app/shared/utils/topic-tooltip.ts b/webapp/src/app/resolvers/utils/topic-tooltip.ts similarity index 100% rename from webapp/src/app/shared/utils/topic-tooltip.ts rename to webapp/src/app/resolvers/utils/topic-tooltip.ts diff --git a/webapp/src/app/shared/pipes/role.pipe.ts b/webapp/src/app/shared/pipes/role.pipe.ts new file mode 100644 index 00000000..0a20871b --- /dev/null +++ b/webapp/src/app/shared/pipes/role.pipe.ts @@ -0,0 +1,22 @@ +import { Pipe, PipeTransform } from '@angular/core'; +import { UserRole } from '../../api'; + +@Pipe({ + name: 'role', +}) +export class RolePipe implements PipeTransform { + transform(value: UserRole, ...args: unknown[]): string { + switch (value) { + case UserRole.SuperAdmin: + return 'Super Admin'; + case UserRole.Admin: + return 'Admin'; + case UserRole.Manager: + return 'Manager'; + case UserRole.User: + return 'Benutzer'; + default: + return 'Unknown'; + } + } +} diff --git a/webapp/src/app/shared/services/account-management.service.ts b/webapp/src/app/shared/services/account-management.service.ts index bc64586f..2791c921 100644 --- a/webapp/src/app/shared/services/account-management.service.ts +++ b/webapp/src/app/shared/services/account-management.service.ts @@ -56,7 +56,9 @@ export class AccountManagementService { private readonly apiConfiguration = inject(Configuration, { optional: true }); getCurrentAccount(): Observable { - return this.httpClient.get(`${this.apiBasePath}/api/accounts/me`); + return this.httpClient.get( + `${this.apiBasePath}/api/accounts/me`, + ); } listAccounts(options: { @@ -77,9 +79,12 @@ export class AccountManagementService { params = params.set('organization_id', options.organizationId); } - return this.httpClient.get(`${this.apiBasePath}/api/accounts`, { - params, - }); + return this.httpClient.get( + `${this.apiBasePath}/api/accounts`, + { + params, + }, + ); } createAccount(payload: CreateAccountPayload): Observable { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index d946b5aa..b80e7271 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -111,17 +111,20 @@ } @else { - --> - @if (getDuration()) { -
-
Laufzeit
-
{{ getDuration() }}
-
- } + +
+
Laufzeit
+
+ von {{ bundProject.funding_start_date | date: 'dd.MM.yyyy' }} bis + {{ bundProject.funding_end_date | date: 'dd.MM.yyyy' }} +
+
+ @if (bundProject.joint_project) {
Gemeinschaftsprojekt
diff --git a/webapp/src/app/modules/projects/bund-details/bund-details.component.ts b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts index 29fe06ab..73b06e6e 100644 --- a/webapp/src/app/modules/projects/bund-details/bund-details.component.ts +++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts @@ -4,7 +4,6 @@ import { CommonModule } from '@angular/common'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { BundProjectDetails } from '../../../api/model/bundProjectDetails'; -import { formatGermanDate } from '../../../resolvers/utils/formatters'; @Component({ selector: 'app-bund-details', @@ -45,18 +44,6 @@ export class BundDetailsComponent implements OnInit { : `${fundingEndDate}`; } - formatCurrency(amount: number | null | undefined): string { - if (amount === null || amount === undefined) return 'N/A'; - - // Format as Euro with thousands separators - return new Intl.NumberFormat('de-DE', { - style: 'currency', - currency: 'EUR', - minimumFractionDigits: 0, - maximumFractionDigits: 0, - }).format(amount); - } - searchForPersonName(personName: string): void { this.router.navigate(['/persons'], { queryParams: { @@ -110,22 +97,7 @@ export class BundDetailsComponent implements OnInit { getAssociatedPersons(): string[] { return this.bundProject?.associated_persons || []; } - getStartDate(): string { - return formatGermanDate(this.bundProject?.funding_start_date ?? ''); - } - getEndDate(): string { - return formatGermanDate(this.bundProject?.funding_end_date ?? ''); - } - - getDuration(): string { - const start = this.bundProject?.funding_start_date; - const end = this.bundProject?.funding_end_date; - - if (!start || !end) return ''; - - return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`; - } /** * All institutions as a simple list. */ @@ -140,13 +112,6 @@ export class BundDetailsComponent implements OnInit { return this.bundProject?.is_new === true; } - /** - * Get display name for funding amount - */ - getFundingAmountDisplay(): string { - if (!this.bundProject?.funding_amount) return 'N/A'; - return this.formatCurrency(this.bundProject.funding_amount); - } getStatusDisplay(fundingEndDate: string | null | undefined): string { if (!fundingEndDate) return 'N/A'; if (fundingEndDate === '2999') return 'Laufend'; diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 1aa56279..5d3b5fe0 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -72,14 +72,14 @@
calendar_today
- {{ formatDate(euProject.startDate) || 'N/A' }} + {{ euProject.startDate | date: 'dd.MM.yyyy' }} Förderbeginn
event_busy
- {{ formatDate(euProject.endDate) || 'N/A' }} + {{ euProject.endDate | date: 'dd.MM.yyyy' }} Förderende
@@ -94,7 +94,10 @@
euro_symbol
- {{ formatCurr(euProject.ecMaxContribution) }} + {{ + euProject.ecMaxContribution + | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' + }} EU-Beitrag
@@ -103,7 +106,10 @@
attach_money
- {{ formatCurr(euProject.totalCost) }} + {{ + euProject.totalCost + | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' + }} Gesamtkosten
@@ -368,19 +374,29 @@ @if (euProject.ecMaxContribution) {
Max. EU-Beitrag
-
{{ formatCurr(euProject.ecMaxContribution) }}
+
+ {{ + euProject.ecMaxContribution + | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' + }} +
} @if (euProject.totalCost) {
Gesamtkosten
-
{{ formatCurr(euProject.totalCost) }}
+
+ {{ + euProject.totalCost + | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' + }} +
} @if (euProject.ecSignatureDate) {
EU-Unterzeichnung
-
{{ formatDate(euProject.ecSignatureDate) }}
+
{{ euProject.ecSignatureDate | date: 'dd.MM.yyyy' }}
} @if (euProject.nature) { @@ -402,22 +418,21 @@
Laufzeit
- {{ - getDuration(euProject.startDate, euProject.endDate) || - 'N/A' - }} + von + {{ euProject.startDate | date: 'dd.MM.yyyy' }} + bis {{ euProject.endDate | date: 'dd.MM.yyyy' }}
@if (euProject.ecSignatureDate) {
EU-Unterzeichnung
-
{{ formatDate(euProject.ecSignatureDate) }}
+
{{ euProject.ecSignatureDate | date: 'dd.MM.yyyy' }}
} @if (euProject.contentUpdateDate) {
Letzte Aktualisierung
-
{{ formatDate(euProject.contentUpdateDate) }}
+
{{ euProject.contentUpdateDate | date: 'dd.MM.yyyy' }}
} @if (euProject.grantDoi) { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index cc1e83f0..17a030b7 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -1,7 +1,7 @@ // eu-details.component.ts (refactored) import { Component, OnInit, inject, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; -import { CommonModule } from '@angular/common'; +import { CommonModule, CurrencyPipe } from '@angular/common'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { MatChipsModule } from '@angular/material/chips'; @@ -15,10 +15,7 @@ import { OrganizationsTableComponent } from './organizations-table/organizations import { PublicationsTableComponent } from './publications-table/publications-table.component'; import { PatentsCardsComponent } from './patents-cards/patents-cards.component'; import { DeliverablesCardsComponent } from './deliverables-cards/deliverables-cards.component'; -import { - formatCurrency, - formatGermanDate, -} from '../../../resolvers/utils/formatters'; + export type TabType = | 'overview' | 'organizations' @@ -42,6 +39,7 @@ export type TabType = PublicationsTableComponent, PatentsCardsComponent, DeliverablesCardsComponent, + CurrencyPipe, ], templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', @@ -325,25 +323,6 @@ export class EuDetailsComponent implements OnInit, OnDestroy { return end >= now ? 'Laufend' : 'Abgeschlossen'; } - getDuration(start: string | undefined, end: string | undefined): string { - if (!start || !end) return ''; - return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`; - } - - formatDate(date: string | undefined): string | undefined { - if (date) { - return formatGermanDate(date); - } - return date; - } - - formatCurr(value: number | undefined | null): string | null | undefined { - if (value) { - return formatCurrency(value); - } - return String(value); - } - getStatusColor(status: string | null | undefined): string { if (!status) return '#95a5a6'; diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html index 1e5bfd19..817b9833 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html @@ -43,7 +43,9 @@ } @else { @@ -58,7 +60,7 @@ @if (org.ecContribution) { {{ - formatCurr(org.ecContribution) + org.ecContribution | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} } @else { — @@ -118,4 +120,4 @@
- \ No newline at end of file + diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts index a4603eaa..de322d8a 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts @@ -4,10 +4,10 @@ import { Router } from '@angular/router'; import { MatIcon } from '@angular/material/icon'; import { MatCard } from '@angular/material/card'; import { HEUOrganization } from '../../../../../api'; -import { formatCurrency } from '../../../../../resolvers/utils/formatters'; +import { CurrencyPipe } from '@angular/common'; @Component({ selector: 'app-organizations-table', - imports: [MatTableModule, MatIcon, MatCard], + imports: [MatTableModule, MatIcon, MatCard, CurrencyPipe], templateUrl: './organizations-table.component.html', styleUrl: './organizations-table.component.scss', }) @@ -46,10 +46,4 @@ export class OrganizationsTableComponent { getOrgsCount(): number { return this.orgs?.length || 0; } - formatCurr(value: number | undefined | null) { - if (value) { - return formatCurrency(value); - } - return value; - } } diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 0ae1e25c..706f34fb 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -62,8 +62,8 @@ diff --git a/webapp/src/app/resolvers/utils/formatters.ts b/webapp/src/app/resolvers/utils/formatters.ts deleted file mode 100644 index 3131672a..00000000 --- a/webapp/src/app/resolvers/utils/formatters.ts +++ /dev/null @@ -1,20 +0,0 @@ -export function formatGermanDate(dateString: string): string { - if (!dateString) return ''; - - return new Intl.DateTimeFormat('de-DE', { - day: 'numeric', - month: 'long', - year: 'numeric', - }).format(new Date(dateString)); -} - -export function formatCurrency(amount: number | null | undefined): string { - if (amount === null || amount === undefined) return 'N/A'; - - return new Intl.NumberFormat('de-DE', { - style: 'currency', - currency: 'EUR', - minimumFractionDigits: 0, - maximumFractionDigits: 0, - }).format(amount); -}