Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11ea77135e | ||
|
|
5126e530e6 | ||
|
|
8b7f8b7d6a | ||
|
|
a0cd8d0904 | ||
|
|
7e11738481 | ||
|
|
ab18134c58 | ||
|
|
05eb9a3b50 | ||
|
|
9388ad9bdb | ||
|
|
eb8780e9f9 | ||
|
|
ff54ebd438 | ||
|
|
ae92c44092 | ||
|
|
97ba57b9a2 | ||
|
|
5a91887861 | ||
|
|
dfa9c70a25 | ||
|
|
c8179d44f6 | ||
|
|
1019cedb97 | ||
|
|
4b6ad1ec3d | ||
|
|
0648e1774c | ||
|
|
b993862afb | ||
|
|
f951eba7e4 | ||
|
|
d5122a5eb7 | ||
|
|
1351264c80 | ||
|
|
7b13db6dbf | ||
|
|
b4257f2efa | ||
|
|
52a567df3e | ||
|
|
901cca5eb9 | ||
|
|
a1b1cf0473 | ||
|
|
653dcb0a14 | ||
|
|
91ec7d841c | ||
|
|
d8a991cc3a | ||
|
|
6d25d5c51f | ||
|
|
3d8fc2431f | ||
|
|
8390764ff4 | ||
|
|
699dc32b0d | ||
|
|
bea26c70ec | ||
|
|
40fcdba595 | ||
|
|
81441dc588 |
+3
-1
@@ -13,7 +13,9 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
|||||||
"pytest~=8.1.0" \
|
"pytest~=8.1.0" \
|
||||||
"httpx~=0.27.0" \
|
"httpx~=0.27.0" \
|
||||||
"python-multipart~=0.0.19"\
|
"python-multipart~=0.0.19"\
|
||||||
"openai~=2.41.0"
|
"openai~=2.41.0" \
|
||||||
|
"sqlmodel~=0.0.33" \
|
||||||
|
"argon2-cffi~=25.1.0"
|
||||||
|
|
||||||
COPY [ "src/main", "/home" ]
|
COPY [ "src/main", "/home" ]
|
||||||
COPY [ "src/data", "/data" ]
|
COPY [ "src/data", "/data" ]
|
||||||
|
|||||||
@@ -16,10 +16,11 @@ dependencies = [
|
|||||||
"pytest~=8.1.0",
|
"pytest~=8.1.0",
|
||||||
"python-multipart~=0.0.19",
|
"python-multipart~=0.0.19",
|
||||||
"pyyaml~=6.0.1",
|
"pyyaml~=6.0.1",
|
||||||
"sqlalchemy~=2.0.0",
|
|
||||||
"uvicorn~=0.29.0",
|
"uvicorn~=0.29.0",
|
||||||
"sentence-transformers~=5.5.1",
|
"sentence-transformers~=5.5.1",
|
||||||
"torch",
|
"torch",
|
||||||
|
"sqlmodel~=0.0.33",
|
||||||
|
"argon2-cffi~=25.1.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[tool.uv.index]]
|
[[tool.uv.index]]
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Usage (run once from project root):
|
|||||||
"""
|
"""
|
||||||
from sentence_transformers import SentenceTransformer
|
from sentence_transformers import SentenceTransformer
|
||||||
|
|
||||||
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
|
MODEL_NAME = "intfloat/multilingual-e5-base"
|
||||||
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
|
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
|
||||||
model = SentenceTransformer(MODEL_NAME)
|
model = SentenceTransformer(MODEL_NAME)
|
||||||
print("Done.")
|
print("Done.")
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"organizations": [
|
||||||
|
{
|
||||||
|
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||||
|
"name": "The Super Admin Organization"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Universität Duisburg-Essen",
|
||||||
|
"openalex_instution_id": "https://openalex.org/I62318514"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ruhr-Universität Bochum",
|
||||||
|
"openalex_instution_id": "https://openalex.org/I904495901"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "TU Dortmund",
|
||||||
|
"openalex_instution_id": "https://openalex.org/I200332995"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accounts": [
|
||||||
|
{
|
||||||
|
"email": "super@admin.com",
|
||||||
|
"password": "superadmin",
|
||||||
|
"name": "Super Admin",
|
||||||
|
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||||
|
"role": "SUPER_ADMIN"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"organizations": [
|
||||||
|
{
|
||||||
|
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||||
|
"name": "The Super Admin Organization"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Universität Duisburg-Essen",
|
||||||
|
"openalex_institution_id": "I62318514"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ruhr-Universität Bochum",
|
||||||
|
"openalex_institution_id": "I904495901"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "TU Dortmund",
|
||||||
|
"openalex_institution_id": "I200332995"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"accounts": [
|
||||||
|
{
|
||||||
|
"email": "super@admin.com",
|
||||||
|
"password": "superadmin",
|
||||||
|
"name": "Super Admin",
|
||||||
|
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||||
|
"role": "SUPER_ADMIN"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -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_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||||
LLM_MODEL=gemma4-e4b
|
LLM_MODEL=gemma4-e4b
|
||||||
@@ -8,15 +5,15 @@ LLM_MODEL=gemma4-e4b
|
|||||||
# Patent search (EPO + USPTO)
|
# Patent search (EPO + USPTO)
|
||||||
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
|
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
|
||||||
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||||
|
|
||||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
|
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
|
||||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||||
|
|
||||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
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 Configuration
|
||||||
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
|
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
|
||||||
|
|
||||||
|
TOKEN_ISSUER_ID=inse
|
||||||
|
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
|
|
||||||
@@ -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
|
|
||||||
|
|
||||||
@@ -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
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlmodel import Field, Relationship, SQLModel
|
||||||
|
|
||||||
|
|
||||||
|
class UserRole(StrEnum):
|
||||||
|
SUPER_ADMIN = "SUPER_ADMIN"
|
||||||
|
ADMIN = "ADMIN"
|
||||||
|
MANAGER = "MANAGER"
|
||||||
|
USER = "USER"
|
||||||
|
|
||||||
|
|
||||||
|
class TokenType(StrEnum):
|
||||||
|
ID_TOKEN = "ID"
|
||||||
|
REFRESH_TOKEN = "REFRESH"
|
||||||
|
ACCESS_TOKEN = "ACCESS"
|
||||||
|
|
||||||
|
|
||||||
|
class Durable(SQLModel):
|
||||||
|
deleted: bool = Field(
|
||||||
|
default=False,
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
description="Indicates whether the record is marked as deleted.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Organization(Durable, table=True):
|
||||||
|
id: uuid.UUID | None = Field(
|
||||||
|
default_factory=uuid.uuid4,
|
||||||
|
primary_key=True,
|
||||||
|
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||||
|
)
|
||||||
|
name: str = Field(
|
||||||
|
index=True,
|
||||||
|
unique=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The unique name of the organization.",
|
||||||
|
)
|
||||||
|
openalex_institution_id: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
index=True,
|
||||||
|
description="The OpenAlex ID of the institution associated with the organization.",
|
||||||
|
)
|
||||||
|
|
||||||
|
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||||
|
|
||||||
|
|
||||||
|
class Account(Durable, table=True):
|
||||||
|
id: uuid.UUID | None = Field(
|
||||||
|
default_factory=uuid.uuid4,
|
||||||
|
primary_key=True,
|
||||||
|
description="Unique identifier for the account. Generated automatically if not provided.",
|
||||||
|
)
|
||||||
|
email: str = Field(
|
||||||
|
index=True,
|
||||||
|
unique=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The email address associated with the account.",
|
||||||
|
)
|
||||||
|
name: str = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The name of the account holder.",
|
||||||
|
)
|
||||||
|
openalex_person_id: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
index=True,
|
||||||
|
description="The OpenAlex ID of the person associated with the account.",
|
||||||
|
)
|
||||||
|
epoch: int = Field(
|
||||||
|
default=0,
|
||||||
|
nullable=False,
|
||||||
|
description="The epoch value for the account. Used for versioning of tokens.",
|
||||||
|
)
|
||||||
|
password_hash: str = Field(
|
||||||
|
index=False,
|
||||||
|
nullable=False,
|
||||||
|
description="The hashed password for the account using Argon2id algorithm.",
|
||||||
|
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
|
||||||
|
)
|
||||||
|
|
||||||
|
organization_id: uuid.UUID = Field(
|
||||||
|
foreign_key="organization.id",
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the organization strictly associated with this account.",
|
||||||
|
)
|
||||||
|
role: UserRole = Field(
|
||||||
|
default=UserRole.USER,
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The specific role this account holds within its organization.",
|
||||||
|
)
|
||||||
|
|
||||||
|
organization: Organization = Relationship(back_populates="accounts")
|
||||||
|
|
||||||
|
|
||||||
|
class Secret(SQLModel, table=True):
|
||||||
|
id: uuid.UUID | None = Field(
|
||||||
|
default_factory=uuid.uuid4,
|
||||||
|
primary_key=True,
|
||||||
|
description="Unique identifier for the secret. Generated automatically if not provided.",
|
||||||
|
)
|
||||||
|
account_id: uuid.UUID = Field(
|
||||||
|
foreign_key="account.id",
|
||||||
|
unique=True, # Ensure that each account can have only one associated secret
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the account associated with this secret.",
|
||||||
|
)
|
||||||
|
secret_value: str = Field(
|
||||||
|
index=False,
|
||||||
|
nullable=False,
|
||||||
|
description="The actual secret value. This should be stored securely and encrypted.",
|
||||||
|
)
|
||||||
|
expires_at: datetime = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The timestamp indicating when the secret will expire.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Token(BaseModel):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
description="The type of the token (ID, Refresh, or Access).",
|
||||||
|
)
|
||||||
|
real_account_id: uuid.UUID = Field(
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the real account associated with this token.",
|
||||||
|
)
|
||||||
|
expires_at: datetime = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The timestamp indicating when the token will expire.",
|
||||||
|
)
|
||||||
|
epoch: int = Field(
|
||||||
|
default=0,
|
||||||
|
nullable=False,
|
||||||
|
description="The epoch value for the token. Used for versioning of tokens.",
|
||||||
|
)
|
||||||
|
user_fingerprint_hash: str = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||||
|
)
|
||||||
|
raw_token: str = Field(
|
||||||
|
index=False,
|
||||||
|
nullable=False,
|
||||||
|
description="The raw token string.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class IdToken(Token):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
default=TokenType.ID_TOKEN,
|
||||||
|
const=True,
|
||||||
|
description="The type of the token, which is always ID_TOKEN for this class.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AccessToken(Token):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
default=TokenType.ACCESS_TOKEN,
|
||||||
|
const=True,
|
||||||
|
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
||||||
|
)
|
||||||
|
effective_account_id: uuid.UUID = Field(
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
||||||
|
)
|
||||||
|
effective_role: UserRole = Field(
|
||||||
|
default=UserRole.USER,
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The specific role this access token grants within its organization.",
|
||||||
|
)
|
||||||
|
effective_organization_id: uuid.UUID = Field(
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the organization associated with this access token.",
|
||||||
|
)
|
||||||
|
|
||||||
|
def is_impersonating(self) -> bool:
|
||||||
|
"""Determine if the access token is being used for impersonation.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
|
||||||
|
"""
|
||||||
|
return self.effective_account_id != self.real_account_id
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshToken(AccessToken):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
default=TokenType.REFRESH_TOKEN,
|
||||||
|
const=True,
|
||||||
|
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class LoginResponse(BaseModel):
|
||||||
|
id_token: IdToken = Field(description="The ID token issued upon successful login.")
|
||||||
|
|
||||||
|
|
||||||
|
class AccessResponse(BaseModel):
|
||||||
|
access_token: AccessToken = Field(
|
||||||
|
description="The access token issued upon successful authentication."
|
||||||
|
)
|
||||||
|
refresh_token: RefreshToken = Field(
|
||||||
|
description="The refresh token issued alongside the access token for obtaining new access tokens."
|
||||||
|
)
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlmodel import Field, Relationship, SQLModel
|
||||||
|
|
||||||
|
|
||||||
|
class UserRole(StrEnum):
|
||||||
|
SUPER_ADMIN = "SUPER_ADMIN"
|
||||||
|
ADMIN = "ADMIN"
|
||||||
|
MANAGER = "MANAGER"
|
||||||
|
USER = "USER"
|
||||||
|
|
||||||
|
|
||||||
|
class TokenType(StrEnum):
|
||||||
|
ID_TOKEN = "ID"
|
||||||
|
REFRESH_TOKEN = "REFRESH"
|
||||||
|
ACCESS_TOKEN = "ACCESS"
|
||||||
|
|
||||||
|
|
||||||
|
class Durable(SQLModel):
|
||||||
|
deleted: bool = Field(
|
||||||
|
default=False,
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
description="Indicates whether the record is marked as deleted.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Organization(Durable, table=True):
|
||||||
|
id: uuid.UUID | None = Field(
|
||||||
|
default_factory=uuid.uuid4,
|
||||||
|
primary_key=True,
|
||||||
|
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||||
|
)
|
||||||
|
name: str = Field(
|
||||||
|
index=True,
|
||||||
|
unique=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The unique name of the organization.",
|
||||||
|
)
|
||||||
|
openalex_institution_id: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
index=True,
|
||||||
|
description="The OpenAlex ID of the institution associated with the organization.",
|
||||||
|
)
|
||||||
|
|
||||||
|
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||||
|
|
||||||
|
|
||||||
|
class Account(Durable, table=True):
|
||||||
|
id: uuid.UUID | None = Field(
|
||||||
|
default_factory=uuid.uuid4,
|
||||||
|
primary_key=True,
|
||||||
|
description="Unique identifier for the account. Generated automatically if not provided.",
|
||||||
|
)
|
||||||
|
email: str = Field(
|
||||||
|
index=True,
|
||||||
|
unique=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The email address associated with the account.",
|
||||||
|
)
|
||||||
|
name: str = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The name of the account holder.",
|
||||||
|
)
|
||||||
|
openalex_person_id: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
index=True,
|
||||||
|
description="The OpenAlex ID of the person associated with the account.",
|
||||||
|
)
|
||||||
|
epoch: int = Field(
|
||||||
|
default=0,
|
||||||
|
nullable=False,
|
||||||
|
description="The epoch value for the account. Used for versioning of tokens.",
|
||||||
|
)
|
||||||
|
password_hash: str = Field(
|
||||||
|
index=False,
|
||||||
|
nullable=False,
|
||||||
|
description="The hashed password for the account using Argon2id algorithm.",
|
||||||
|
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
|
||||||
|
)
|
||||||
|
|
||||||
|
organization_id: uuid.UUID = Field(
|
||||||
|
foreign_key="organization.id",
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the organization strictly associated with this account.",
|
||||||
|
)
|
||||||
|
role: UserRole = Field(
|
||||||
|
default=UserRole.USER,
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The specific role this account holds within its organization.",
|
||||||
|
)
|
||||||
|
|
||||||
|
organization: Organization = Relationship(back_populates="accounts")
|
||||||
|
|
||||||
|
|
||||||
|
class Secret(SQLModel, table=True):
|
||||||
|
id: uuid.UUID | None = Field(
|
||||||
|
default_factory=uuid.uuid4,
|
||||||
|
primary_key=True,
|
||||||
|
description="Unique identifier for the secret. Generated automatically if not provided.",
|
||||||
|
)
|
||||||
|
account_id: uuid.UUID = Field(
|
||||||
|
foreign_key="account.id",
|
||||||
|
unique=True, # Ensure that each account can have only one associated secret
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the account associated with this secret.",
|
||||||
|
)
|
||||||
|
secret_value: str = Field(
|
||||||
|
index=False,
|
||||||
|
nullable=False,
|
||||||
|
description="The actual secret value. This should be stored securely and encrypted.",
|
||||||
|
)
|
||||||
|
expires_at: datetime = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The timestamp indicating when the secret will expire.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Token(BaseModel):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
description="The type of the token (ID, Refresh, or Access).",
|
||||||
|
)
|
||||||
|
real_account_id: uuid.UUID = Field(
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the real account associated with this token.",
|
||||||
|
)
|
||||||
|
expires_at: datetime = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The timestamp indicating when the token will expire.",
|
||||||
|
)
|
||||||
|
epoch: int = Field(
|
||||||
|
default=0,
|
||||||
|
nullable=False,
|
||||||
|
description="The epoch value for the token. Used for versioning of tokens.",
|
||||||
|
)
|
||||||
|
user_fingerprint_hash: str = Field(
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||||
|
)
|
||||||
|
raw_token: str = Field(
|
||||||
|
index=False,
|
||||||
|
nullable=False,
|
||||||
|
description="The raw token string.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class IdToken(Token):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
default=TokenType.ID_TOKEN,
|
||||||
|
const=True,
|
||||||
|
description="The type of the token, which is always ID_TOKEN for this class.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AccessToken(Token):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
default=TokenType.ACCESS_TOKEN,
|
||||||
|
const=True,
|
||||||
|
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
||||||
|
)
|
||||||
|
effective_account_id: uuid.UUID = Field(
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
||||||
|
)
|
||||||
|
effective_role: UserRole = Field(
|
||||||
|
default=UserRole.USER,
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The specific role this access token grants within its organization.",
|
||||||
|
)
|
||||||
|
effective_organization_id: uuid.UUID = Field(
|
||||||
|
nullable=False,
|
||||||
|
description="The unique identifier of the organization associated with this access token.",
|
||||||
|
)
|
||||||
|
|
||||||
|
def is_impersonating(self) -> bool:
|
||||||
|
"""Determine if the access token is being used for impersonation.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
|
||||||
|
"""
|
||||||
|
return self.effective_account_id != self.real_account_id
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshToken(AccessToken):
|
||||||
|
token_type: TokenType = Field(
|
||||||
|
default=TokenType.REFRESH_TOKEN,
|
||||||
|
const=True,
|
||||||
|
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class LoginResponse(BaseModel):
|
||||||
|
id_token: IdToken = Field(description="The ID token issued upon successful login.")
|
||||||
|
|
||||||
|
|
||||||
|
class AccessResponse(BaseModel):
|
||||||
|
access_token: AccessToken = Field(
|
||||||
|
description="The access token issued upon successful authentication."
|
||||||
|
)
|
||||||
|
refresh_token: RefreshToken = Field(
|
||||||
|
description="The refresh token issued alongside the access token for obtaining new access tokens."
|
||||||
|
)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Annotated
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends, Response, status
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from inse.tags import Tags
|
||||||
|
|
||||||
|
import inse.auth.service as auth_service
|
||||||
|
from inse.database import SessionDep, get_session
|
||||||
|
from inse.auth.model import (
|
||||||
|
AccessResponse,
|
||||||
|
AccessToken,
|
||||||
|
IdToken,
|
||||||
|
LoginResponse,
|
||||||
|
RefreshToken,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
async def health_check():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/request-otk",
|
||||||
|
summary="Request One-Time Key",
|
||||||
|
description="Request a one-time key (OTK) for authentication using email and password.",
|
||||||
|
operation_id="requestOtk",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def request_otk(
|
||||||
|
session: SessionDep,
|
||||||
|
email: Annotated[str, Body(description="User's email address")],
|
||||||
|
password: Annotated[str, Body(description="User's password")],
|
||||||
|
):
|
||||||
|
return auth_service.request_otk(session=session, email=email, password=password)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/login",
|
||||||
|
summary="Login with One-Time Key",
|
||||||
|
description="Login using a one-time key (OTK) sent to the user's email.",
|
||||||
|
operation_id="login",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Login successful."}},
|
||||||
|
)
|
||||||
|
async def login(
|
||||||
|
session: SessionDep,
|
||||||
|
response: Response,
|
||||||
|
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||||
|
email_code: Annotated[
|
||||||
|
str, Body(embed=True, description="One-time code sent to user's email")
|
||||||
|
],
|
||||||
|
) -> LoginResponse:
|
||||||
|
return auth_service.login(
|
||||||
|
session=session, response=response, account_id=account_id, email_code=email_code
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/access",
|
||||||
|
summary="Get Access Token",
|
||||||
|
description="Retrieve an access token for the authenticated user.",
|
||||||
|
operation_id="getAccessToken",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def get_action_tokens(
|
||||||
|
response: Response,
|
||||||
|
session: SessionDep,
|
||||||
|
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||||
|
effective_account_id: Annotated[
|
||||||
|
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||||
|
],
|
||||||
|
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||||
|
) -> AccessResponse:
|
||||||
|
logger.debug(
|
||||||
|
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||||
|
real_account_id,
|
||||||
|
effective_account_id,
|
||||||
|
id_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
return auth_service.get_access_token(
|
||||||
|
response=response,
|
||||||
|
session=session,
|
||||||
|
real_account_id=real_account_id,
|
||||||
|
effective_account_id=effective_account_id,
|
||||||
|
id_token=id_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/refresh",
|
||||||
|
summary="Refresh Access Token",
|
||||||
|
description="Refresh the access token using a valid refresh token.",
|
||||||
|
operation_id="refreshAccessToken",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def refresh_access_token(
|
||||||
|
refresh_token: Annotated[
|
||||||
|
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||||
|
],
|
||||||
|
) -> AccessToken:
|
||||||
|
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/logout",
|
||||||
|
summary="Logout",
|
||||||
|
description="Logout the authenticated user.",
|
||||||
|
operation_id="logout",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
|
||||||
|
)
|
||||||
|
async def logout(
|
||||||
|
session: Annotated[Session, Depends(get_session)],
|
||||||
|
access_token: Annotated[
|
||||||
|
AccessToken,
|
||||||
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
|
],
|
||||||
|
):
|
||||||
|
return auth_service.logout(session=session, access_token=access_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/change-password",
|
||||||
|
summary="Change Password",
|
||||||
|
description="Change the user's password and invalidate existing tokens.",
|
||||||
|
operation_id="changePassword",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
|
||||||
|
)
|
||||||
|
async def change_password(
|
||||||
|
session: Annotated[Session, Depends(get_session)],
|
||||||
|
current_password: Annotated[
|
||||||
|
str,
|
||||||
|
Body(description="Current password"),
|
||||||
|
],
|
||||||
|
new_password: Annotated[
|
||||||
|
str,
|
||||||
|
Body(description="New password", min_length=8),
|
||||||
|
],
|
||||||
|
access_token: Annotated[
|
||||||
|
AccessToken,
|
||||||
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
|
],
|
||||||
|
):
|
||||||
|
return auth_service.change_password(
|
||||||
|
session=session,
|
||||||
|
access_token=access_token,
|
||||||
|
current_password=current_password,
|
||||||
|
new_password=new_password,
|
||||||
|
)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Annotated
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends, Response, status
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from inse.tags import Tags
|
||||||
|
|
||||||
|
import inse.auth.service as auth_service
|
||||||
|
from inse.database import SessionDep, get_session
|
||||||
|
from inse.auth.model import (
|
||||||
|
AccessResponse,
|
||||||
|
AccessToken,
|
||||||
|
IdToken,
|
||||||
|
LoginResponse,
|
||||||
|
RefreshToken,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
async def health_check():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/request-otk",
|
||||||
|
summary="Request One-Time Key",
|
||||||
|
description="Request a one-time key (OTK) for authentication using email and password.",
|
||||||
|
operation_id="requestOtk",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def request_otk(
|
||||||
|
session: SessionDep,
|
||||||
|
email: Annotated[str, Body(description="User's email address")],
|
||||||
|
password: Annotated[str, Body(description="User's password")],
|
||||||
|
):
|
||||||
|
return auth_service.request_otk(session=session, email=email, password=password)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/login",
|
||||||
|
summary="Login with One-Time Key",
|
||||||
|
description="Login using a one-time key (OTK) sent to the user's email.",
|
||||||
|
operation_id="login",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Login successful."}},
|
||||||
|
)
|
||||||
|
async def login(
|
||||||
|
session: SessionDep,
|
||||||
|
response: Response,
|
||||||
|
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||||
|
email_code: Annotated[
|
||||||
|
str, Body(embed=True, description="One-time code sent to user's email")
|
||||||
|
],
|
||||||
|
) -> LoginResponse:
|
||||||
|
return auth_service.login(
|
||||||
|
session=session, response=response, account_id=account_id, email_code=email_code
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/access",
|
||||||
|
summary="Get Access Token",
|
||||||
|
description="Retrieve an access token for the authenticated user.",
|
||||||
|
operation_id="getAccessToken",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def get_action_tokens(
|
||||||
|
response: Response,
|
||||||
|
session: SessionDep,
|
||||||
|
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||||
|
effective_account_id: Annotated[
|
||||||
|
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||||
|
],
|
||||||
|
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||||
|
) -> AccessResponse:
|
||||||
|
logger.debug(
|
||||||
|
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||||
|
real_account_id,
|
||||||
|
effective_account_id,
|
||||||
|
id_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
return auth_service.get_access_token(
|
||||||
|
response=response,
|
||||||
|
session=session,
|
||||||
|
real_account_id=real_account_id,
|
||||||
|
effective_account_id=effective_account_id,
|
||||||
|
id_token=id_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/refresh",
|
||||||
|
summary="Refresh Access Token",
|
||||||
|
description="Refresh the access token using a valid refresh token.",
|
||||||
|
operation_id="refreshAccessToken",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def refresh_access_token(
|
||||||
|
refresh_token: Annotated[
|
||||||
|
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||||
|
],
|
||||||
|
) -> AccessToken:
|
||||||
|
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/logout",
|
||||||
|
summary="Logout",
|
||||||
|
description="Logout the authenticated user.",
|
||||||
|
operation_id="logout",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
|
||||||
|
)
|
||||||
|
async def logout(
|
||||||
|
session: Annotated[Session, Depends(get_session)],
|
||||||
|
access_token: Annotated[
|
||||||
|
AccessToken,
|
||||||
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
|
],
|
||||||
|
):
|
||||||
|
return auth_service.logout(session=session, access_token=access_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/change-password",
|
||||||
|
summary="Change Password",
|
||||||
|
description="Change the user's password and invalidate existing tokens.",
|
||||||
|
operation_id="changePassword",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
|
||||||
|
)
|
||||||
|
async def change_password(
|
||||||
|
session: Annotated[Session, Depends(get_session)],
|
||||||
|
current_password: Annotated[
|
||||||
|
str,
|
||||||
|
Body(description="Current password"),
|
||||||
|
],
|
||||||
|
new_password: Annotated[
|
||||||
|
str,
|
||||||
|
Body(description="New password", min_length=8),
|
||||||
|
],
|
||||||
|
access_token: Annotated[
|
||||||
|
AccessToken,
|
||||||
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
|
],
|
||||||
|
):
|
||||||
|
return auth_service.change_password(
|
||||||
|
session=session,
|
||||||
|
access_token=access_token,
|
||||||
|
current_password=current_password,
|
||||||
|
new_password=new_password,
|
||||||
|
)
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,517 @@
|
|||||||
|
import inse.config as config_module
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import Session, SQLModel, create_engine, select
|
||||||
|
|
||||||
|
|
||||||
|
from fastapi import Response, HTTPException
|
||||||
|
import datetime as _dt
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from inse.auth import service as auth_service
|
||||||
|
from inse.auth.model import (
|
||||||
|
Account,
|
||||||
|
Organization,
|
||||||
|
Secret,
|
||||||
|
IdToken,
|
||||||
|
AccessToken,
|
||||||
|
RefreshToken,
|
||||||
|
UserRole,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def settings_backup():
|
||||||
|
orig = config_module.get_settings()
|
||||||
|
backup = config_module.Settings(**orig.model_dump())
|
||||||
|
yield backup
|
||||||
|
for k, v in backup.model_dump().items():
|
||||||
|
setattr(config_module.settings, k, v)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def in_memory_session():
|
||||||
|
engine = create_engine(
|
||||||
|
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
SQLModel.metadata.create_all(engine)
|
||||||
|
with Session(engine) as session:
|
||||||
|
yield session
|
||||||
|
|
||||||
|
|
||||||
|
def create_org_and_account(
|
||||||
|
session: Session, email: str, password: str, role=UserRole.USER
|
||||||
|
):
|
||||||
|
org = Organization(name=f"Test Org {email}")
|
||||||
|
session.add(org)
|
||||||
|
session.flush()
|
||||||
|
assert org.id is not None
|
||||||
|
pwd_hash = auth_service._hash_password(password)
|
||||||
|
acc = Account(
|
||||||
|
email=email,
|
||||||
|
name="Tester",
|
||||||
|
organization_id=org.id,
|
||||||
|
password_hash=pwd_hash,
|
||||||
|
role=role,
|
||||||
|
)
|
||||||
|
session.add(acc)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(acc)
|
||||||
|
return org, acc
|
||||||
|
|
||||||
|
|
||||||
|
def test_hash_and_verify_password():
|
||||||
|
pw = "s3cret-password"
|
||||||
|
h = auth_service._hash_password(pw)
|
||||||
|
assert auth_service._verify_password(pw, h) is True
|
||||||
|
assert auth_service._verify_password("wrong", h) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "test-hmac-key"
|
||||||
|
config_module.settings.token_issuer_id = "test-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "user@example.com"
|
||||||
|
password = "hunter2"
|
||||||
|
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
resp = auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
assert resp["status"] == "ok"
|
||||||
|
assert resp["account_id"] == str(acc.id)
|
||||||
|
|
||||||
|
secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert secret is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
|
||||||
|
login_result = auth_service.login(
|
||||||
|
in_memory_session, response, acc.id, secret.secret_value
|
||||||
|
)
|
||||||
|
assert isinstance(login_result.id_token, IdToken)
|
||||||
|
assert login_result.id_token.real_account_id == acc.id
|
||||||
|
assert login_result.id_token.user_fingerprint_hash is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "another-key"
|
||||||
|
config_module.settings.token_issuer_id = "issuer-2"
|
||||||
|
|
||||||
|
email = "fp@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
assert isinstance(id_token, IdToken)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
assert cookie_header is not None
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0]
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
|
||||||
|
payload = auth_service._verify_fp_token(
|
||||||
|
request=req,
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
||||||
|
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({}),
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "flow-key"
|
||||||
|
config_module.settings.token_issuer_id = "flow-issuer"
|
||||||
|
|
||||||
|
email = "flow@example.com"
|
||||||
|
password = "pwflow"
|
||||||
|
org, acc = create_org_and_account(
|
||||||
|
in_memory_session, email, password, role=UserRole.ADMIN
|
||||||
|
)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
access_response = auth_service.get_access_token(
|
||||||
|
response, in_memory_session, id_token, acc.id
|
||||||
|
)
|
||||||
|
assert isinstance(access_response.access_token, AccessToken)
|
||||||
|
assert isinstance(access_response.refresh_token, RefreshToken)
|
||||||
|
|
||||||
|
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
|
||||||
|
assert isinstance(refreshed, AccessToken)
|
||||||
|
assert refreshed.real_account_id == access_response.access_token.real_account_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_and_change_password(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "logout-key"
|
||||||
|
config_module.settings.token_issuer_id = "logout-issuer"
|
||||||
|
|
||||||
|
email = "logout@example.com"
|
||||||
|
password = "oldpw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
access_resp = auth_service.get_access_token(
|
||||||
|
response, in_memory_session, id_token, acc.id
|
||||||
|
)
|
||||||
|
|
||||||
|
before_epoch = acc.epoch
|
||||||
|
out = auth_service.logout(in_memory_session, access_resp.access_token)
|
||||||
|
assert out["status"] == "ok"
|
||||||
|
in_memory_session.refresh(acc)
|
||||||
|
assert acc.epoch == before_epoch + 1
|
||||||
|
|
||||||
|
new_pw = "newpw123"
|
||||||
|
acc.password_hash = auth_service._hash_password(password)
|
||||||
|
in_memory_session.add(acc)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
change_out = auth_service.change_password(
|
||||||
|
in_memory_session, access_resp.access_token, password, new_pw
|
||||||
|
)
|
||||||
|
assert change_out["status"] == "ok"
|
||||||
|
in_memory_session.refresh(acc)
|
||||||
|
assert auth_service._verify_password(new_pw, acc.password_hash)
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
|
||||||
|
email = "nope@example.com"
|
||||||
|
password = "rightpw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "expired-key"
|
||||||
|
config_module.settings.token_issuer_id = "expired-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "expired@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||||
|
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.login(in_memory_session, Response(), acc.id, "000000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "cookie-key"
|
||||||
|
config_module.settings.token_issuer_id = "cookie-issuer"
|
||||||
|
|
||||||
|
email = "cookie@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_epoch_mismatch(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "epoch-key"
|
||||||
|
config_module.settings.token_issuer_id = "epoch-issuer"
|
||||||
|
|
||||||
|
email = "epoch@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
acc.epoch += 1
|
||||||
|
in_memory_session.add(acc)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_token_signature_raises(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "sig-key"
|
||||||
|
config_module.settings.token_issuer_id = "sig-issuer"
|
||||||
|
|
||||||
|
email = "sig@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
bad_token = id_token.raw_token + "x"
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=bad_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_impersonation_rules(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "imp-key"
|
||||||
|
config_module.settings.token_issuer_id = "imp-issuer"
|
||||||
|
|
||||||
|
org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw")
|
||||||
|
assert real_acc.id is not None
|
||||||
|
org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw")
|
||||||
|
assert eff_acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.get_access_token(
|
||||||
|
response,
|
||||||
|
in_memory_session,
|
||||||
|
id_token,
|
||||||
|
real_acc.id,
|
||||||
|
effective_account_id=eff_acc.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
real_acc.role = UserRole.SUPER_ADMIN
|
||||||
|
in_memory_session.add(real_acc)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
access_resp = auth_service.get_access_token(
|
||||||
|
response,
|
||||||
|
in_memory_session,
|
||||||
|
id_token,
|
||||||
|
real_acc.id,
|
||||||
|
effective_account_id=eff_acc.id,
|
||||||
|
)
|
||||||
|
assert isinstance(access_resp.access_token, AccessToken)
|
||||||
|
|
||||||
|
|
||||||
|
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "regen-key"
|
||||||
|
config_module.settings.token_issuer_id = "regen-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "regen@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
secret1 = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert secret1 is not None
|
||||||
|
first_value = secret1.secret_value
|
||||||
|
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
secret2 = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
assert secret2 is not None
|
||||||
|
assert first_value != secret2.secret_value
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.login(in_memory_session, Response(), acc.id, first_value)
|
||||||
|
|
||||||
|
login_res = auth_service.login(
|
||||||
|
in_memory_session, Response(), acc.id, secret2.secret_value
|
||||||
|
)
|
||||||
|
assert isinstance(login_res.id_token, IdToken)
|
||||||
|
|
||||||
|
|
||||||
|
def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "del-key"
|
||||||
|
config_module.settings.token_issuer_id = "del-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "single@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert secret is not None
|
||||||
|
|
||||||
|
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||||
|
post = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert post is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_access_token_fp_mismatch(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "act-key"
|
||||||
|
config_module.settings.token_issuer_id = "act-issuer"
|
||||||
|
|
||||||
|
email = "act@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
raw = auth_service._set_act_fp_cookie(response)
|
||||||
|
|
||||||
|
access_token = auth_service._build_access_token(
|
||||||
|
real_account_id=acc.id,
|
||||||
|
effective_account_id=acc.id,
|
||||||
|
effective_role=acc.role,
|
||||||
|
effective_organization_id=acc.organization_id,
|
||||||
|
epoch=acc.epoch,
|
||||||
|
user_fingerprint_hash=raw,
|
||||||
|
)
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
|
||||||
|
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
|
||||||
|
token=access_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "exp-key"
|
||||||
|
config_module.settings.token_issuer_id = "exp-issuer"
|
||||||
|
|
||||||
|
email = "exp@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
cookie_raw = auth_service._set_id_fp_cookie(response)
|
||||||
|
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||||
|
payload = {
|
||||||
|
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||||
|
auth_service.EPOCH_KEY: acc.epoch,
|
||||||
|
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
|
||||||
|
}
|
||||||
|
bad_token = auth_service._build_token(
|
||||||
|
payload=payload,
|
||||||
|
expiration_datetime=past,
|
||||||
|
token_type=auth_service.TokenType.ID_TOKEN,
|
||||||
|
)
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq(
|
||||||
|
{
|
||||||
|
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
|
||||||
|
.split("=")[1]
|
||||||
|
.split(";")[0]
|
||||||
|
}
|
||||||
|
), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=bad_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_hmac_key_raises_value_error(settings_backup):
|
||||||
|
orig = config_module.get_settings()
|
||||||
|
saved = orig.token_hmac_key
|
||||||
|
config_module.settings.token_hmac_key = None
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
auth_service._build_token(
|
||||||
|
payload={},
|
||||||
|
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
|
||||||
|
token_type=auth_service.TokenType.ID_TOKEN,
|
||||||
|
)
|
||||||
|
config_module.settings.token_hmac_key = saved
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_account_epoch_not_found(in_memory_session):
|
||||||
|
random_id = uuid.uuid4()
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||||
@@ -0,0 +1,517 @@
|
|||||||
|
import inse.config as config_module
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import Session, SQLModel, create_engine, select
|
||||||
|
|
||||||
|
|
||||||
|
from fastapi import Response, HTTPException
|
||||||
|
import datetime as _dt
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from inse.auth import service as auth_service
|
||||||
|
from inse.auth.model import (
|
||||||
|
Account,
|
||||||
|
Organization,
|
||||||
|
Secret,
|
||||||
|
IdToken,
|
||||||
|
AccessToken,
|
||||||
|
RefreshToken,
|
||||||
|
UserRole,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def settings_backup():
|
||||||
|
orig = config_module.get_settings()
|
||||||
|
backup = config_module.Settings(**orig.model_dump())
|
||||||
|
yield backup
|
||||||
|
for k, v in backup.model_dump().items():
|
||||||
|
setattr(config_module.settings, k, v)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def in_memory_session():
|
||||||
|
engine = create_engine(
|
||||||
|
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
SQLModel.metadata.create_all(engine)
|
||||||
|
with Session(engine) as session:
|
||||||
|
yield session
|
||||||
|
|
||||||
|
|
||||||
|
def create_org_and_account(
|
||||||
|
session: Session, email: str, password: str, role=UserRole.USER
|
||||||
|
):
|
||||||
|
org = Organization(name=f"Test Org {email}")
|
||||||
|
session.add(org)
|
||||||
|
session.flush()
|
||||||
|
assert org.id is not None
|
||||||
|
pwd_hash = auth_service._hash_password(password)
|
||||||
|
acc = Account(
|
||||||
|
email=email,
|
||||||
|
name="Tester",
|
||||||
|
organization_id=org.id,
|
||||||
|
password_hash=pwd_hash,
|
||||||
|
role=role,
|
||||||
|
)
|
||||||
|
session.add(acc)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(acc)
|
||||||
|
return org, acc
|
||||||
|
|
||||||
|
|
||||||
|
def test_hash_and_verify_password():
|
||||||
|
pw = "s3cret-password"
|
||||||
|
h = auth_service._hash_password(pw)
|
||||||
|
assert auth_service._verify_password(pw, h) is True
|
||||||
|
assert auth_service._verify_password("wrong", h) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "test-hmac-key"
|
||||||
|
config_module.settings.token_issuer_id = "test-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "user@example.com"
|
||||||
|
password = "hunter2"
|
||||||
|
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
resp = auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
assert resp["status"] == "ok"
|
||||||
|
assert resp["account_id"] == str(acc.id)
|
||||||
|
|
||||||
|
secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert secret is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
|
||||||
|
login_result = auth_service.login(
|
||||||
|
in_memory_session, response, acc.id, secret.secret_value
|
||||||
|
)
|
||||||
|
assert isinstance(login_result.id_token, IdToken)
|
||||||
|
assert login_result.id_token.real_account_id == acc.id
|
||||||
|
assert login_result.id_token.user_fingerprint_hash is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "another-key"
|
||||||
|
config_module.settings.token_issuer_id = "issuer-2"
|
||||||
|
|
||||||
|
email = "fp@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
assert isinstance(id_token, IdToken)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
assert cookie_header is not None
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0]
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
|
||||||
|
payload = auth_service._verify_fp_token(
|
||||||
|
request=req,
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
||||||
|
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({}),
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "flow-key"
|
||||||
|
config_module.settings.token_issuer_id = "flow-issuer"
|
||||||
|
|
||||||
|
email = "flow@example.com"
|
||||||
|
password = "pwflow"
|
||||||
|
org, acc = create_org_and_account(
|
||||||
|
in_memory_session, email, password, role=UserRole.ADMIN
|
||||||
|
)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
access_response = auth_service.get_access_token(
|
||||||
|
response, in_memory_session, id_token, acc.id
|
||||||
|
)
|
||||||
|
assert isinstance(access_response.access_token, AccessToken)
|
||||||
|
assert isinstance(access_response.refresh_token, RefreshToken)
|
||||||
|
|
||||||
|
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
|
||||||
|
assert isinstance(refreshed, AccessToken)
|
||||||
|
assert refreshed.real_account_id == access_response.access_token.real_account_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_and_change_password(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "logout-key"
|
||||||
|
config_module.settings.token_issuer_id = "logout-issuer"
|
||||||
|
|
||||||
|
email = "logout@example.com"
|
||||||
|
password = "oldpw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
access_resp = auth_service.get_access_token(
|
||||||
|
response, in_memory_session, id_token, acc.id
|
||||||
|
)
|
||||||
|
|
||||||
|
before_epoch = acc.epoch
|
||||||
|
out = auth_service.logout(in_memory_session, access_resp.access_token)
|
||||||
|
assert out["status"] == "ok"
|
||||||
|
in_memory_session.refresh(acc)
|
||||||
|
assert acc.epoch == before_epoch + 1
|
||||||
|
|
||||||
|
new_pw = "newpw123"
|
||||||
|
acc.password_hash = auth_service._hash_password(password)
|
||||||
|
in_memory_session.add(acc)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
change_out = auth_service.change_password(
|
||||||
|
in_memory_session, access_resp.access_token, password, new_pw
|
||||||
|
)
|
||||||
|
assert change_out["status"] == "ok"
|
||||||
|
in_memory_session.refresh(acc)
|
||||||
|
assert auth_service._verify_password(new_pw, acc.password_hash)
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
|
||||||
|
email = "nope@example.com"
|
||||||
|
password = "rightpw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "expired-key"
|
||||||
|
config_module.settings.token_issuer_id = "expired-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "expired@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||||
|
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.login(in_memory_session, Response(), acc.id, "000000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "cookie-key"
|
||||||
|
config_module.settings.token_issuer_id = "cookie-issuer"
|
||||||
|
|
||||||
|
email = "cookie@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_epoch_mismatch(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "epoch-key"
|
||||||
|
config_module.settings.token_issuer_id = "epoch-issuer"
|
||||||
|
|
||||||
|
email = "epoch@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
acc.epoch += 1
|
||||||
|
in_memory_session.add(acc)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=id_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_token_signature_raises(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "sig-key"
|
||||||
|
config_module.settings.token_issuer_id = "sig-issuer"
|
||||||
|
|
||||||
|
email = "sig@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||||
|
|
||||||
|
cookie_header = None
|
||||||
|
for header, value in response.headers.items():
|
||||||
|
if header.lower() == "set-cookie":
|
||||||
|
cookie_header = value
|
||||||
|
break
|
||||||
|
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
bad_token = id_token.raw_token + "x"
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=bad_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_impersonation_rules(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "imp-key"
|
||||||
|
config_module.settings.token_issuer_id = "imp-issuer"
|
||||||
|
|
||||||
|
org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw")
|
||||||
|
assert real_acc.id is not None
|
||||||
|
org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw")
|
||||||
|
assert eff_acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.get_access_token(
|
||||||
|
response,
|
||||||
|
in_memory_session,
|
||||||
|
id_token,
|
||||||
|
real_acc.id,
|
||||||
|
effective_account_id=eff_acc.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
real_acc.role = UserRole.SUPER_ADMIN
|
||||||
|
in_memory_session.add(real_acc)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
access_resp = auth_service.get_access_token(
|
||||||
|
response,
|
||||||
|
in_memory_session,
|
||||||
|
id_token,
|
||||||
|
real_acc.id,
|
||||||
|
effective_account_id=eff_acc.id,
|
||||||
|
)
|
||||||
|
assert isinstance(access_resp.access_token, AccessToken)
|
||||||
|
|
||||||
|
|
||||||
|
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "regen-key"
|
||||||
|
config_module.settings.token_issuer_id = "regen-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "regen@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
secret1 = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert secret1 is not None
|
||||||
|
first_value = secret1.secret_value
|
||||||
|
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
secret2 = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
assert secret2 is not None
|
||||||
|
assert first_value != secret2.secret_value
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.login(in_memory_session, Response(), acc.id, first_value)
|
||||||
|
|
||||||
|
login_res = auth_service.login(
|
||||||
|
in_memory_session, Response(), acc.id, secret2.secret_value
|
||||||
|
)
|
||||||
|
assert isinstance(login_res.id_token, IdToken)
|
||||||
|
|
||||||
|
|
||||||
|
def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "del-key"
|
||||||
|
config_module.settings.token_issuer_id = "del-issuer"
|
||||||
|
config_module.settings.skip_otk_validation = False
|
||||||
|
|
||||||
|
email = "single@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert secret is not None
|
||||||
|
|
||||||
|
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||||
|
post = in_memory_session.exec(
|
||||||
|
select(Secret).where(Secret.account_id == acc.id)
|
||||||
|
).first()
|
||||||
|
assert post is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_access_token_fp_mismatch(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "act-key"
|
||||||
|
config_module.settings.token_issuer_id = "act-issuer"
|
||||||
|
|
||||||
|
email = "act@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
raw = auth_service._set_act_fp_cookie(response)
|
||||||
|
|
||||||
|
access_token = auth_service._build_access_token(
|
||||||
|
real_account_id=acc.id,
|
||||||
|
effective_account_id=acc.id,
|
||||||
|
effective_role=acc.role,
|
||||||
|
effective_organization_id=acc.organization_id,
|
||||||
|
epoch=acc.epoch,
|
||||||
|
user_fingerprint_hash=raw,
|
||||||
|
)
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
|
||||||
|
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
|
||||||
|
token=access_token.raw_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
||||||
|
config_module.settings.token_hmac_key = "exp-key"
|
||||||
|
config_module.settings.token_issuer_id = "exp-issuer"
|
||||||
|
|
||||||
|
email = "exp@example.com"
|
||||||
|
password = "pw"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
response = Response()
|
||||||
|
cookie_raw = auth_service._set_id_fp_cookie(response)
|
||||||
|
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||||
|
payload = {
|
||||||
|
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||||
|
auth_service.EPOCH_KEY: acc.epoch,
|
||||||
|
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
|
||||||
|
}
|
||||||
|
bad_token = auth_service._build_token(
|
||||||
|
payload=payload,
|
||||||
|
expiration_datetime=past,
|
||||||
|
token_type=auth_service.TokenType.ID_TOKEN,
|
||||||
|
)
|
||||||
|
|
||||||
|
class DummyReq:
|
||||||
|
def __init__(self, cookies):
|
||||||
|
self.cookies = cookies
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service._verify_fp_token(
|
||||||
|
request=DummyReq(
|
||||||
|
{
|
||||||
|
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
|
||||||
|
.split("=")[1]
|
||||||
|
.split(";")[0]
|
||||||
|
}
|
||||||
|
), # type: ignore
|
||||||
|
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||||
|
token=bad_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_hmac_key_raises_value_error(settings_backup):
|
||||||
|
orig = config_module.get_settings()
|
||||||
|
saved = orig.token_hmac_key
|
||||||
|
config_module.settings.token_hmac_key = None
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
auth_service._build_token(
|
||||||
|
payload={},
|
||||||
|
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
|
||||||
|
token_type=auth_service.TokenType.ID_TOKEN,
|
||||||
|
)
|
||||||
|
config_module.settings.token_hmac_key = saved
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_account_epoch_not_found(in_memory_session):
|
||||||
|
random_id = uuid.uuid4()
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
|
|
||||||
|
|
||||||
@@ -16,18 +14,10 @@ from inse.exceptions import MissingApiKeyError
|
|||||||
class CompanyConnectionsSearchClient:
|
class CompanyConnectionsSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
openalex_index: str = "openalex-authors",
|
openalex_index: str = "openalex-authors",
|
||||||
handelsregister_index: str = "handelsregister",
|
handelsregister_index: str = "handelsregister",
|
||||||
timeout: float = 30.0,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (
|
|
||||||
base_url
|
|
||||||
or config.settings.elasticsearch_url
|
|
||||||
or ""
|
|
||||||
).rstrip("/")
|
|
||||||
self.api_key = (
|
self.api_key = (
|
||||||
api_key
|
api_key
|
||||||
if api_key is not None
|
if api_key is not None
|
||||||
@@ -35,8 +25,6 @@ class CompanyConnectionsSearchClient:
|
|||||||
)
|
)
|
||||||
self.openalex_index = openalex_index
|
self.openalex_index = openalex_index
|
||||||
self.handelsregister_index = handelsregister_index
|
self.handelsregister_index = handelsregister_index
|
||||||
self.timeout = timeout
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def openalex_doc_id(author_id: str) -> str:
|
def openalex_doc_id(author_id: str) -> str:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ that can be adjusted via environment variables.
|
|||||||
|
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, List, Literal, Optional
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
@@ -30,23 +30,20 @@ class Settings(BaseSettings):
|
|||||||
openalex_works_search_index: str = "openalex-works*"
|
openalex_works_search_index: str = "openalex-works*"
|
||||||
openalex_works_search_timeout_seconds: float = 30.0
|
openalex_works_search_timeout_seconds: float = 30.0
|
||||||
# OpenAlex public API config
|
# OpenAlex public API config
|
||||||
openalex_api_base_url: str = "https://api.openalex.org"
|
|
||||||
openalex_api_key: Optional[str] = None
|
openalex_api_key: Optional[str] = None
|
||||||
openalex_api_timeout_seconds: float = 30.0
|
openalex_api_timeout_seconds: float = 30.0
|
||||||
|
|
||||||
|
|
||||||
# Patent Elasticsearch config
|
# Patent Elasticsearch config
|
||||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||||
patent_elasticsearch_api_key: Optional[str] = None
|
patent_elasticsearch_api_key: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
# LLM config
|
# LLM config
|
||||||
llm_api_url: Optional[str] = None
|
llm_api_url: Optional[str] = None
|
||||||
llm_api_key: Optional[str] = None
|
llm_api_key: Optional[str] = None
|
||||||
llm_model: Optional[str] = None
|
llm_model: Optional[str] = None
|
||||||
|
|
||||||
# Sentence Transformers config
|
# Sentence Transformers config
|
||||||
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
|
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
|
||||||
|
|
||||||
# Elasticsearch config
|
# Elasticsearch config
|
||||||
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
||||||
@@ -64,6 +61,21 @@ class Settings(BaseSettings):
|
|||||||
|
|
||||||
logging_level: str = "DEBUG"
|
logging_level: str = "DEBUG"
|
||||||
|
|
||||||
|
environment: Literal["dev", "prod"] = "dev"
|
||||||
|
|
||||||
|
token_issuer_id: Optional[str] = None
|
||||||
|
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()
|
settings = Settings()
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +1,33 @@
|
|||||||
#!/usr/bin/env python
|
from typing import Annotated
|
||||||
# -*- 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
|
|
||||||
|
|
||||||
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:
|
from inse import config
|
||||||
schema.Base.metadata.create_all(engine)
|
|
||||||
|
|
||||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
settings = config.get_settings()
|
||||||
|
|
||||||
def get():
|
connect_args = {"check_same_thread": False}
|
||||||
''' Returns a database connection and closes it when done. '''
|
engine = create_engine(
|
||||||
db = SessionLocal()
|
url=settings.database_url,
|
||||||
try:
|
echo=settings.database_debug,
|
||||||
yield db
|
connect_args=connect_args,
|
||||||
finally:
|
)
|
||||||
db.close()
|
|
||||||
|
|
||||||
|
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)]
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
class NotFoundException(Exception):
|
class NotFoundException(Exception):
|
||||||
|
"""Exception raised when a requested resource is not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
Exception (_type_): Base exception class.
|
||||||
|
"""
|
||||||
def __init__(self, message: str):
|
def __init__(self, message: str):
|
||||||
super().__init__(message)
|
super().__init__(message)
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,6 @@
|
|||||||
"""
|
"""
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESCluster
|
from inse.model import ESCluster
|
||||||
@@ -18,17 +16,11 @@ from inse.exceptions import MissingApiKeyError
|
|||||||
class FundedPublicationsSearchClient:
|
class FundedPublicationsSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
|
||||||
index: str | None = None,
|
index: str | None = None,
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
timeout: float | None = None,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
|
|
||||||
self.index = index or config.settings.openalex_works_search_index
|
self.index = index or config.settings.openalex_works_search_index
|
||||||
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
||||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def indexed_author_id(author_id: str) -> str:
|
def indexed_author_id(author_id: str) -> str:
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import logging
|
|||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
import httpx
|
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||||
|
|
||||||
@@ -60,34 +59,17 @@ async def list_institutions(
|
|||||||
|
|
||||||
openalex_client = client or OpenAlexInstitutionsClient()
|
openalex_client = client or OpenAlexInstitutionsClient()
|
||||||
|
|
||||||
try:
|
data = await openalex_client.list_institutions(
|
||||||
data = await openalex_client.list_institutions(
|
search=search,
|
||||||
search=search,
|
filter=filter,
|
||||||
filter=filter,
|
sort=sort,
|
||||||
sort=sort,
|
group_by=group_by,
|
||||||
group_by=group_by,
|
per_page=per_page,
|
||||||
per_page=per_page,
|
page=page,
|
||||||
page=page,
|
cursor=cursor,
|
||||||
cursor=cursor,
|
sample=sample,
|
||||||
sample=sample,
|
select=select,
|
||||||
select=select,
|
)
|
||||||
)
|
|
||||||
except httpx.HTTPStatusError as exc:
|
|
||||||
status_code = exc.response.status_code
|
|
||||||
detail = "OpenAlex institutions request failed."
|
|
||||||
try:
|
|
||||||
error_body = exc.response.json()
|
|
||||||
detail = error_body.get("message") or error_body.get("error") or detail
|
|
||||||
except ValueError:
|
|
||||||
if exc.response.text:
|
|
||||||
detail = exc.response.text
|
|
||||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
|
||||||
except httpx.HTTPError as exc:
|
|
||||||
logger.exception("OpenAlex institutions request failed.")
|
|
||||||
raise UpstreamAPIException(
|
|
||||||
message="OpenAlex institutions request failed.",
|
|
||||||
status_code=502,
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
normalized_data = _normalize_institutions_response(data)
|
normalized_data = _normalize_institutions_response(data)
|
||||||
|
|||||||
@@ -1,36 +1,18 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""Elasticsearch client for OpenAlex institutions."""
|
||||||
HTTP client for OpenAlex institutions.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.model import ESCluster, ESIndex
|
||||||
from .. import config
|
|
||||||
|
|
||||||
|
|
||||||
class OpenAlexInstitutionsClient:
|
class OpenAlexInstitutionsClient:
|
||||||
def __init__(
|
def __init__(self, index: str | ESIndex = ESIndex.OPENALEX_INSTITUTIONS):
|
||||||
self,
|
self.index = index
|
||||||
base_url: str | None = None,
|
|
||||||
api_key: str | None = None,
|
|
||||||
timeout: float | None = None,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
|
||||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
|
||||||
self.api_key = (
|
|
||||||
api_key if api_key is not None else config.settings.openalex_api_key
|
|
||||||
)
|
|
||||||
self.timeout = (
|
|
||||||
timeout
|
|
||||||
if timeout is not None
|
|
||||||
else config.settings.openalex_api_timeout_seconds
|
|
||||||
)
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def list_institutions_params(
|
def list_institutions_query(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
@@ -43,60 +25,144 @@ class OpenAlexInstitutionsClient:
|
|||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
params: dict[str, Any] = {"per_page": per_page}
|
must: list[dict[str, Any]] = []
|
||||||
|
|
||||||
if search:
|
if search:
|
||||||
params["search"] = search
|
must.append(
|
||||||
if filter:
|
{
|
||||||
params["filter"] = filter
|
"multi_match": {
|
||||||
if sort:
|
"query": search,
|
||||||
params["sort"] = sort
|
"fields": [
|
||||||
if group_by:
|
"display_name^3",
|
||||||
params["group_by"] = group_by
|
"display_name_alternatives^2",
|
||||||
if cursor:
|
"display_name_acronyms^2",
|
||||||
params["cursor"] = cursor
|
],
|
||||||
elif page is not None:
|
}
|
||||||
params["page"] = page
|
}
|
||||||
if sample is not None:
|
|
||||||
params["sample"] = sample
|
|
||||||
if select:
|
|
||||||
params["select"] = select
|
|
||||||
if self.api_key:
|
|
||||||
params["api_key"] = self.api_key
|
|
||||||
|
|
||||||
return params
|
|
||||||
|
|
||||||
async def list_institutions(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
search: str | None = None,
|
|
||||||
filter: str | None = None,
|
|
||||||
sort: str | None = None,
|
|
||||||
group_by: str | None = None,
|
|
||||||
per_page: int = 25,
|
|
||||||
page: int | None = 1,
|
|
||||||
cursor: str | None = None,
|
|
||||||
sample: int | None = None,
|
|
||||||
select: str | None = None,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
async with httpx.AsyncClient(
|
|
||||||
base_url=self.base_url,
|
|
||||||
timeout=self.timeout,
|
|
||||||
transport=self.transport,
|
|
||||||
) as client:
|
|
||||||
response = await client.get(
|
|
||||||
"/institutions",
|
|
||||||
params=self.list_institutions_params(
|
|
||||||
search=search,
|
|
||||||
filter=filter,
|
|
||||||
sort=sort,
|
|
||||||
group_by=group_by,
|
|
||||||
per_page=per_page,
|
|
||||||
page=page,
|
|
||||||
cursor=cursor,
|
|
||||||
sample=sample,
|
|
||||||
select=select,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"must": must or [{"match_all": {}}],
|
||||||
|
"filter": self._filters(filter),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sample is not None:
|
||||||
|
query = {
|
||||||
|
"function_score": {
|
||||||
|
"query": query,
|
||||||
|
"random_score": {"seed": sample},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body: dict[str, Any] = {
|
||||||
|
"query": query,
|
||||||
|
"from": max((page or 1) - 1, 0) * per_page,
|
||||||
|
"size": per_page,
|
||||||
|
"track_total_hits": True,
|
||||||
|
}
|
||||||
|
if select:
|
||||||
|
body["_source"] = [
|
||||||
|
field.strip() for field in select.split(",") if field.strip()
|
||||||
|
]
|
||||||
|
if sort:
|
||||||
|
body["sort"] = self._sort(sort)
|
||||||
|
if cursor and cursor != "*":
|
||||||
|
body["search_after"] = cursor.split(",")
|
||||||
|
body.pop("from", None)
|
||||||
|
if group_by:
|
||||||
|
body["aggs"] = {
|
||||||
|
"group_by": {
|
||||||
|
"terms": {
|
||||||
|
"field": self._keyword_field(group_by),
|
||||||
|
"size": per_page,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
|
||||||
|
async def list_institutions(self, **kwargs: Any) -> dict[str, Any]:
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=self.index,
|
||||||
|
body=self.list_institutions_query(**kwargs),
|
||||||
|
cluster=ESCluster.NES,
|
||||||
|
)
|
||||||
|
hits_block = response.get("hits", {})
|
||||||
|
hits = hits_block.get("hits", [])
|
||||||
|
total_value = hits_block.get("total", 0)
|
||||||
|
total = (
|
||||||
|
total_value.get("value", 0)
|
||||||
|
if isinstance(total_value, dict)
|
||||||
|
else total_value
|
||||||
|
)
|
||||||
|
result: dict[str, Any] = {
|
||||||
|
"meta": {
|
||||||
|
"count": total,
|
||||||
|
"page": kwargs.get("page", 1),
|
||||||
|
"per_page": kwargs.get("per_page", 25),
|
||||||
|
"next_cursor": self._next_cursor(hits),
|
||||||
|
},
|
||||||
|
"results": [hit.get("_source", {}) for hit in hits],
|
||||||
|
}
|
||||||
|
|
||||||
|
buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets")
|
||||||
|
if buckets is not None:
|
||||||
|
result["group_by"] = [
|
||||||
|
{
|
||||||
|
"key": bucket.get("key"),
|
||||||
|
"key_display_name": bucket.get(
|
||||||
|
"key_as_string", bucket.get("key")
|
||||||
|
),
|
||||||
|
"count": bucket.get("doc_count"),
|
||||||
|
}
|
||||||
|
for bucket in buckets
|
||||||
|
]
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _filters(value: str | None) -> list[dict[str, Any]]:
|
||||||
|
clauses: list[dict[str, Any]] = []
|
||||||
|
for item in (value or "").split(","):
|
||||||
|
if not item or ":" not in item:
|
||||||
|
continue
|
||||||
|
field, raw_value = item.split(":", 1)
|
||||||
|
field = field.strip()
|
||||||
|
raw_value = raw_value.strip()
|
||||||
|
if raw_value.startswith((">", "<")):
|
||||||
|
operator = "gt" if raw_value[0] == ">" else "lt"
|
||||||
|
clauses.append({"range": {field: {operator: raw_value[1:]}}})
|
||||||
|
else:
|
||||||
|
clauses.append(
|
||||||
|
{"term": {OpenAlexInstitutionsClient._keyword_field(field): raw_value}}
|
||||||
|
)
|
||||||
|
return clauses
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _sort(value: str) -> list[dict[str, Any]]:
|
||||||
|
result = []
|
||||||
|
for item in value.split(","):
|
||||||
|
field, _, direction = item.partition(":")
|
||||||
|
result.append(
|
||||||
|
{
|
||||||
|
OpenAlexInstitutionsClient._sortable_field(field.strip()): {
|
||||||
|
"order": direction or "desc",
|
||||||
|
"missing": "_last",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _keyword_field(field: str) -> str:
|
||||||
|
if field in {"id", "ror", "display_name"}:
|
||||||
|
return f"{field}.keyword"
|
||||||
|
return field
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _sortable_field(field: str) -> str:
|
||||||
|
return "display_name.keyword" if field == "display_name" else field
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _next_cursor(hits: list[dict[str, Any]]) -> str | None:
|
||||||
|
if not hits or not hits[-1].get("sort"):
|
||||||
|
return None
|
||||||
|
return ",".join(str(value) for value in hits[-1]["sort"])
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
from inse.exceptions import BadRequestException
|
|
||||||
|
|
||||||
|
from inse.exceptions import BadRequestException
|
||||||
from inse.institutions import logic
|
from inse.institutions import logic
|
||||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -11,166 +9,72 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
class StubInstitutionsClient:
|
||||||
async def test_list_institutions_maps_openalex_response_to_model():
|
def __init__(self, response):
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
self.response = response
|
||||||
return httpx.Response(
|
self.kwargs = None
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"id": "https://openalex.org/I123",
|
|
||||||
"ror": "https://ror.org/04mz5ra38",
|
|
||||||
"display_name": "University of Duisburg-Essen",
|
|
||||||
"country_code": "DE",
|
|
||||||
"type": "education",
|
|
||||||
"homepage_url": "https://www.uni-due.de",
|
|
||||||
"image_url": "https://example.org/image.jpg",
|
|
||||||
"image_thumbnail_url": "https://example.org/thumb.jpg",
|
|
||||||
"display_name_acronyms": ["UDE"],
|
|
||||||
"display_name_alternatives": ["Universitaet Duisburg-Essen"],
|
|
||||||
"works_count": 123,
|
|
||||||
"cited_by_count": 456,
|
|
||||||
"summary_stats": {
|
|
||||||
"2yr_mean_citedness": 1.5,
|
|
||||||
"h_index": 42,
|
|
||||||
"i10_index": 99,
|
|
||||||
},
|
|
||||||
"geo": {
|
|
||||||
"city": "Duisburg",
|
|
||||||
"geonames_city_id": "2934691",
|
|
||||||
"region": "North Rhine-Westphalia",
|
|
||||||
"country_code": "DE",
|
|
||||||
"country": "Germany",
|
|
||||||
"latitude": 51.4344,
|
|
||||||
"longitude": 6.7623,
|
|
||||||
},
|
|
||||||
"lineage": ["https://openalex.org/I123"],
|
|
||||||
"ids": {
|
|
||||||
"openalex": "https://openalex.org/I123",
|
|
||||||
"ror": "https://ror.org/04mz5ra38",
|
|
||||||
"mag": 123,
|
|
||||||
"grid": "grid.12345.6",
|
|
||||||
"wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen",
|
|
||||||
"wikidata": "https://www.wikidata.org/wiki/Q317070",
|
|
||||||
},
|
|
||||||
"counts_by_year": [
|
|
||||||
{
|
|
||||||
"year": 2024,
|
|
||||||
"works_count": 12,
|
|
||||||
"cited_by_count": 34,
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123",
|
|
||||||
"created_date": "2023-12-25",
|
|
||||||
"updated_date": "2023-11-07T05:31:56Z",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"group_by": [
|
|
||||||
{
|
|
||||||
"key": "DE",
|
|
||||||
"key_display_name": "Germany",
|
|
||||||
"count": 1,
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
client = OpenAlexInstitutionsClient(
|
async def list_institutions(self, **kwargs):
|
||||||
api_key="test-key",
|
self.kwargs = kwargs
|
||||||
transport=httpx.MockTransport(handler),
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_list_institutions_maps_elasticsearch_response_to_model():
|
||||||
|
client = StubInstitutionsClient(
|
||||||
|
{
|
||||||
|
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"id": "https://openalex.org/I123",
|
||||||
|
"ror": "https://ror.org/012345678",
|
||||||
|
"display_name": "Example University",
|
||||||
|
"country_code": "DE",
|
||||||
|
"type": "education",
|
||||||
|
"works_count": 123,
|
||||||
|
"cited_by_count": 456,
|
||||||
|
"geo": {"city": "Essen", "country": "Germany"},
|
||||||
|
"ids": {"openalex": "https://openalex.org/I123"},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_institutions(search="Duisburg Essen", client=client)
|
result = await logic.list_institutions(search="Example", client=client)
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.meta.count == 1
|
||||||
institution = result.results[0]
|
assert result.results[0].display_name == "Example University"
|
||||||
assert institution.display_name == "University of Duisburg-Essen"
|
assert result.results[0].geo.city == "Essen"
|
||||||
assert institution.summary_stats.h_index == 42
|
assert client.kwargs["search"] == "Example"
|
||||||
assert institution.geo.country == "Germany"
|
|
||||||
assert institution.ids.mag == 123
|
|
||||||
assert institution.counts_by_year[0].year == 2024
|
|
||||||
assert result.group_by[0].key_display_name == "Germany"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_institutions_rejects_sample_with_sort():
|
async def test_list_institutions_rejects_sample_with_sort():
|
||||||
with pytest.raises(BadRequestException) as exc_info:
|
with pytest.raises(BadRequestException):
|
||||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
async def test_list_institutions_normalizes_elasticsearch_values():
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
client = StubInstitutionsClient(
|
||||||
return httpx.Response(
|
{
|
||||||
200,
|
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||||
json={
|
"results": [
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
{
|
||||||
"results": [
|
"id": 123,
|
||||||
{
|
"display_name": 456,
|
||||||
"id": 123,
|
"type": "unknown-type",
|
||||||
"ror": 456,
|
"works_count": "12.0",
|
||||||
"display_name": "Example Institute",
|
"ids": {"openalex": 123, "mag": "123"},
|
||||||
"country_code": 789,
|
}
|
||||||
"type": "unknown-openalex-type",
|
],
|
||||||
"display_name_acronyms": ["EI", 123],
|
}
|
||||||
"display_name_alternatives": "not-a-list",
|
|
||||||
"works_count": "12",
|
|
||||||
"cited_by_count": "34.0",
|
|
||||||
"summary_stats": {
|
|
||||||
"2yr_mean_citedness": "1.25",
|
|
||||||
"h_index": "10.0",
|
|
||||||
"i10_index": True,
|
|
||||||
},
|
|
||||||
"geo": {
|
|
||||||
"city": 123,
|
|
||||||
"geonames_city_id": 12345,
|
|
||||||
"latitude": "51.4",
|
|
||||||
"longitude": "6",
|
|
||||||
},
|
|
||||||
"ids": {"openalex": 123, "mag": "123"},
|
|
||||||
"counts_by_year": [
|
|
||||||
{
|
|
||||||
"year": "2024",
|
|
||||||
"works_count": "12.0",
|
|
||||||
"cited_by_count": False,
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"created_date": "2023-12-25T10:11:12Z",
|
|
||||||
"updated_date": "2023-12-25",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"group_by": [{"key": True, "count": 1}],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
client = OpenAlexInstitutionsClient(
|
|
||||||
api_key="test-key",
|
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_institutions(client=client)
|
result = await logic.list_institutions(client=client)
|
||||||
|
|
||||||
assert result.results[0].id == "123"
|
assert result.results[0].id == "123"
|
||||||
assert result.results[0].ror == "456"
|
assert result.results[0].display_name == "456"
|
||||||
assert result.results[0].country_code == "789"
|
|
||||||
assert result.results[0].type is None
|
assert result.results[0].type is None
|
||||||
assert result.results[0].display_name_acronyms == ["EI", "123"]
|
|
||||||
assert result.results[0].display_name_alternatives is None
|
|
||||||
assert result.results[0].works_count == 12
|
assert result.results[0].works_count == 12
|
||||||
assert result.results[0].cited_by_count == 34
|
|
||||||
assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25
|
|
||||||
assert result.results[0].summary_stats.h_index == 10
|
|
||||||
assert result.results[0].summary_stats.i10_index is None
|
|
||||||
assert result.results[0].geo.city == "123"
|
|
||||||
assert result.results[0].geo.geonames_city_id == "12345"
|
|
||||||
assert result.results[0].geo.latitude == 51.4
|
|
||||||
assert result.results[0].geo.longitude == 6
|
|
||||||
assert result.results[0].ids.openalex == "123"
|
|
||||||
assert result.results[0].ids.mag == 123
|
assert result.results[0].ids.mag == 123
|
||||||
assert result.results[0].counts_by_year[0].year == 2024
|
|
||||||
assert result.results[0].counts_by_year[0].works_count == 12
|
|
||||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
|
||||||
assert result.group_by[0].key == "true"
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import httpx
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from inse.model import ESCluster, ESIndex
|
||||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||||
|
|
||||||
|
|
||||||
@@ -9,69 +11,47 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
def test_list_institutions_params_include_openalex_query_parameters():
|
def test_list_institutions_query_builds_elasticsearch_query():
|
||||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
body = OpenAlexInstitutionsClient().list_institutions_query(
|
||||||
|
|
||||||
params = client.list_institutions_params(
|
|
||||||
search="Duisburg Essen",
|
search="Duisburg Essen",
|
||||||
filter="country_code:DE,type:education",
|
filter="country_code:DE,type:education,works_count:>1000",
|
||||||
sort="works_count:desc",
|
sort="works_count:desc",
|
||||||
group_by="country_code",
|
|
||||||
per_page=10,
|
per_page=10,
|
||||||
page=2,
|
page=2,
|
||||||
select="id,display_name",
|
select="id,display_name",
|
||||||
)
|
)
|
||||||
|
|
||||||
assert params == {
|
assert body["from"] == 10
|
||||||
"search": "Duisburg Essen",
|
assert body["size"] == 10
|
||||||
"filter": "country_code:DE,type:education",
|
assert body["_source"] == ["id", "display_name"]
|
||||||
"sort": "works_count:desc",
|
assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "Duisburg Essen"
|
||||||
"group_by": "country_code",
|
assert {"term": {"country_code": "DE"}} in body["query"]["bool"]["filter"]
|
||||||
"per_page": 10,
|
assert {"term": {"type": "education"}} in body["query"]["bool"]["filter"]
|
||||||
"page": 2,
|
assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"]
|
||||||
"select": "id,display_name",
|
assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}]
|
||||||
"api_key": "test-key",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_list_institutions_params_prefers_cursor_over_page():
|
|
||||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
|
||||||
|
|
||||||
params = client.list_institutions_params(cursor="*", page=3)
|
|
||||||
|
|
||||||
assert params["cursor"] == "*"
|
|
||||||
assert "page" not in params
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_institutions_calls_openalex_institutions_endpoint():
|
async def test_list_institutions_calls_elasticsearch_and_maps_hits():
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
response = {
|
||||||
assert request.method == "GET"
|
"hits": {
|
||||||
assert request.url.path == "/institutions"
|
"total": {"value": 1},
|
||||||
assert request.url.params["search"] == "Duisburg Essen"
|
"hits": [
|
||||||
assert request.url.params["api_key"] == "test-key"
|
{
|
||||||
return httpx.Response(
|
"_source": {
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"id": "https://openalex.org/I123",
|
"id": "https://openalex.org/I123",
|
||||||
"display_name": "University of Duisburg-Essen",
|
"display_name": "Example University",
|
||||||
"country_code": "DE",
|
|
||||||
"type": "education",
|
|
||||||
}
|
}
|
||||||
],
|
}
|
||||||
},
|
],
|
||||||
)
|
}
|
||||||
|
}
|
||||||
client = OpenAlexInstitutionsClient(
|
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search:
|
||||||
base_url="https://api.openalex.org",
|
search.return_value = response
|
||||||
api_key="test-key",
|
result = await OpenAlexInstitutionsClient().list_institutions(search="Example")
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
|
||||||
|
|
||||||
result = await client.list_institutions(search="Duisburg Essen")
|
|
||||||
|
|
||||||
|
search.assert_awaited_once()
|
||||||
|
assert search.await_args.kwargs["index"] == ESIndex.OPENALEX_INSTITUTIONS
|
||||||
|
assert search.await_args.kwargs["cluster"] == ESCluster.NES
|
||||||
assert result["meta"]["count"] == 1
|
assert result["meta"]["count"] == 1
|
||||||
assert result["results"][0]["display_name"] == "University of Duisburg-Essen"
|
assert result["results"][0]["display_name"] == "Example University"
|
||||||
|
|||||||
@@ -6,17 +6,9 @@ web service.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import List
|
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 logging
|
||||||
import httpx
|
|
||||||
import json
|
import json
|
||||||
from . import schema
|
|
||||||
from . import model
|
|
||||||
from . import config
|
from . import config
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
|
|
||||||
@@ -30,68 +22,13 @@ from inse.models.openalex.topic_domain import TopicDomain
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
topic_cache_filename: str = "topic_hierarchy_cache.json"
|
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:
|
def _load_topic_cache() -> dict:
|
||||||
"""Loads the topic hierarchy cache from a JSON file."""
|
"""Loads the topic hierarchy cache from a JSON file."""
|
||||||
import os
|
import os
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cache_path = "/data/" + topic_cache_filename
|
cache_path = "/data/" + topic_cache_filename
|
||||||
if not os.path.exists(cache_path):
|
if not os.path.exists(cache_path):
|
||||||
@@ -218,6 +155,7 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
|
|||||||
|
|
||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
def get_topic_hierarchy() -> dict:
|
def get_topic_hierarchy() -> dict:
|
||||||
"""
|
"""
|
||||||
Builds and returns a hierarchical tree structure of topics:
|
Builds and returns a hierarchical tree structure of topics:
|
||||||
@@ -242,10 +180,7 @@ def get_topic_hierarchy() -> dict:
|
|||||||
if subfield not in tree[domain][field]:
|
if subfield not in tree[domain][field]:
|
||||||
tree[domain][field][subfield] = []
|
tree[domain][field][subfield] = []
|
||||||
|
|
||||||
tree[domain][field][subfield].append({
|
tree[domain][field][subfield].append({"id": topic_id, "name": topic_name})
|
||||||
"id": topic_id,
|
|
||||||
"name": topic_name
|
|
||||||
})
|
|
||||||
|
|
||||||
formatted_domains = []
|
formatted_domains = []
|
||||||
for d_name, d_fields in tree.items():
|
for d_name, d_fields in tree.items():
|
||||||
@@ -254,20 +189,11 @@ def get_topic_hierarchy() -> dict:
|
|||||||
formatted_subfields = []
|
formatted_subfields = []
|
||||||
for sf_name, sf_topics in f_subfields.items():
|
for sf_name, sf_topics in f_subfields.items():
|
||||||
sf_topics.sort(key=lambda x: x["name"])
|
sf_topics.sort(key=lambda x: x["name"])
|
||||||
formatted_subfields.append({
|
formatted_subfields.append({"name": sf_name, "topics": sf_topics})
|
||||||
"name": sf_name,
|
|
||||||
"topics": sf_topics
|
|
||||||
})
|
|
||||||
formatted_subfields.sort(key=lambda x: x["name"])
|
formatted_subfields.sort(key=lambda x: x["name"])
|
||||||
formatted_fields.append({
|
formatted_fields.append({"name": f_name, "subfields": formatted_subfields})
|
||||||
"name": f_name,
|
|
||||||
"subfields": formatted_subfields
|
|
||||||
})
|
|
||||||
formatted_fields.sort(key=lambda x: x["name"])
|
formatted_fields.sort(key=lambda x: x["name"])
|
||||||
formatted_domains.append({
|
formatted_domains.append({"name": d_name, "fields": formatted_fields})
|
||||||
"name": d_name,
|
|
||||||
"fields": formatted_fields
|
|
||||||
})
|
|
||||||
formatted_domains.sort(key=lambda x: x["name"])
|
formatted_domains.sort(key=lambda x: x["name"])
|
||||||
|
|
||||||
return {"domains": formatted_domains}
|
return {"domains": formatted_domains}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ for fastapi that loads the service and the
|
|||||||
webapp.
|
webapp.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from contextlib import asynccontextmanager, contextmanager
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
@@ -24,21 +25,25 @@ from inse.exceptions import (
|
|||||||
from inse.funders.service import router as funders_service_router
|
from inse.funders.service import router as funders_service_router
|
||||||
from inse.projects.router import router as projects_router
|
from inse.projects.router import router as projects_router
|
||||||
from inse.university_ranking.router import router as university_ranking_router
|
from inse.university_ranking.router import router as university_ranking_router
|
||||||
|
|
||||||
# caching
|
# caching
|
||||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||||
from inse.persons.service import router as persons_service_router
|
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.topics.service import router as topics_service_router
|
||||||
from inse.works.service import router as works_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.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.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
|
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 . import config
|
||||||
from .account.service import router as account_router
|
|
||||||
from .service import router as service_router
|
from .service import router as service_router
|
||||||
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
|
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
|
||||||
|
|
||||||
@@ -48,12 +53,24 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
settings = config.get_settings()
|
settings = config.get_settings()
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
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...")
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
redoc_url=None,
|
redoc_url=None,
|
||||||
title="Innovation Search Engine API",
|
title="Innovation Search Engine API",
|
||||||
description="API for the Innovation Search Engine (INSE) application.",
|
description="API for the Innovation Search Engine (INSE) application.",
|
||||||
version="0.1.0",
|
version="0.1.0",
|
||||||
servers=settings.servers,
|
servers=settings.servers,
|
||||||
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
app.include_router(collaboration_network_router)
|
app.include_router(collaboration_network_router)
|
||||||
app.include_router(institutions_router)
|
app.include_router(institutions_router)
|
||||||
@@ -63,13 +80,17 @@ app.include_router(persons_service_router)
|
|||||||
app.include_router(funders_service_router)
|
app.include_router(funders_service_router)
|
||||||
app.include_router(news_service_router)
|
app.include_router(news_service_router)
|
||||||
app.include_router(company_connections_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(patents_service_router)
|
||||||
app.include_router(university_ranking_router)
|
app.include_router(university_ranking_router)
|
||||||
app.include_router(projects_router)
|
app.include_router(projects_router)
|
||||||
app.include_router(patents_all_router)
|
app.include_router(patents_all_router)
|
||||||
|
|
||||||
|
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(
|
app.add_middleware(
|
||||||
ETagCacheMiddleware,
|
ETagCacheMiddleware,
|
||||||
ttl=300, # 5 minutes expiration time
|
ttl=300, # 5 minutes expiration time
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
# middleware/etag_cache.py
|
# middleware/etag_cache.py
|
||||||
import hashlib, json, time
|
import hashlib
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
from starlette.responses import Response
|
from starlette.responses import Response
|
||||||
|
|
||||||
|
|
||||||
class ETagCacheMiddleware(BaseHTTPMiddleware):
|
class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||||
def __init__(self, app, ttl: int = 60):
|
def __init__(self, app, ttl: int = 60):
|
||||||
super().__init__(app)
|
super().__init__(app)
|
||||||
@@ -14,10 +18,19 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
|||||||
# Include query params and relevant headers in the key
|
# Include query params and relevant headers in the key
|
||||||
return f"{request.url.path}?{request.url.query}"
|
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):
|
async def dispatch(self, request: Request, call_next):
|
||||||
if request.method != "GET":
|
if request.method != "GET":
|
||||||
return await call_next(request)
|
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)
|
key = self._cache_key(request)
|
||||||
entry = self.cache.get(key)
|
entry = self.cache.get(key)
|
||||||
client_etag = request.headers.get("if-none-match")
|
client_etag = request.headers.get("if-none-match")
|
||||||
@@ -25,28 +38,37 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
|||||||
# Cache hit + not expired
|
# Cache hit + not expired
|
||||||
if entry and time.time() < entry["expires"]:
|
if entry and time.time() < entry["expires"]:
|
||||||
if client_etag == entry["etag"]:
|
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
|
# 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(
|
return Response(
|
||||||
content=entry["body"],
|
content=entry["body"],
|
||||||
media_type="application/json",
|
headers=headers,
|
||||||
headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Cache miss or expired → hit the actual route
|
# Cache miss or expired → hit the actual route
|
||||||
response = await call_next(request)
|
response = await call_next(request)
|
||||||
body = b"".join([chunk async for chunk in response.body_iterator])
|
body = b"".join([chunk async for chunk in response.body_iterator])
|
||||||
etag = f'"{hashlib.md5(body).hexdigest()}"'
|
etag = f'"{hashlib.md5(body).hexdigest()}"'
|
||||||
|
content_type = self._content_type(response)
|
||||||
|
|
||||||
self.cache[key] = {
|
self.cache[key] = {
|
||||||
"body": body,
|
"body": body,
|
||||||
"etag": etag,
|
"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(
|
return Response(
|
||||||
content=body,
|
content=body,
|
||||||
status_code=response.status_code,
|
status_code=response.status_code,
|
||||||
media_type="application/json",
|
headers=headers,
|
||||||
headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
|
||||||
)
|
)
|
||||||
@@ -8,41 +8,20 @@ our api using pydantic.
|
|||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from pydantic import ConfigDict
|
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
from typing import List
|
from typing import List
|
||||||
from typing import TypeVar
|
from typing import TypeVar
|
||||||
from typing import Generic
|
from typing import Generic
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
T = TypeVar("T", bound=BaseModel)
|
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]):
|
class Page(BaseModel, Generic[T]):
|
||||||
elements: List[T] = Field(default=[], description="The elements of the page.")
|
elements: List[T] = Field(default=[], description="The elements of the page.")
|
||||||
offset: int = Field(default=0, description="The page offset in elements.")
|
offset: int = Field(default=0, description="The page number. (0-based)")
|
||||||
total: int = Field(default=0, description="The total number of elements.")
|
|
||||||
size: int = Field(default=20, description="The page size in elements.")
|
size: int = Field(default=20, description="The page size in elements.")
|
||||||
|
total: int = Field(default=0, description="The total number of elements.")
|
||||||
|
|
||||||
class ItemPage(Page[Item]):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class ESCluster(StrEnum):
|
class ESCluster(StrEnum):
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Organization management API."""
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Organization management API."""
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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"
|
||||||
@@ -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"
|
||||||
@@ -5,8 +5,6 @@
|
|||||||
"""
|
"""
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from inse.exceptions import MissingApiKeyError
|
from inse.exceptions import MissingApiKeyError
|
||||||
|
|
||||||
@@ -20,15 +18,9 @@ USPTO_INDEX = "uspto_patents_3.0"
|
|||||||
class AllPatentsSearchClient:
|
class AllPatentsSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
timeout: float = 30.0,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
|
||||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||||
self.timeout = timeout
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def _headers(self) -> dict[str, str]:
|
def _headers(self) -> dict[str, str]:
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
|
|||||||
@@ -6,7 +6,6 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESCluster, ESIndex
|
from inse.model import ESCluster, ESIndex
|
||||||
import httpx
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from .. import config
|
from .. import config
|
||||||
from .name_matching import search_name_variants
|
from .name_matching import search_name_variants
|
||||||
@@ -33,15 +32,9 @@ from inse.exceptions import MissingApiKeyError
|
|||||||
class PatentSearchClient:
|
class PatentSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
timeout: float = 30.0,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
|
||||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||||
self.timeout = timeout
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def _headers(self) -> dict[str, str]:
|
def _headers(self) -> dict[str, str]:
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from . import model
|
from . import model
|
||||||
from inse.exceptions import MissingApiKeyError
|
from inse.exceptions import MissingApiKeyError
|
||||||
@@ -32,15 +30,9 @@ _LEVELS: tuple[tuple[str, str, str], ...] = (
|
|||||||
class IpcSearchClient:
|
class IpcSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
timeout: float = 30.0,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
|
||||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||||
self.timeout = timeout
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def _headers(self) -> dict[str, str]:
|
def _headers(self) -> dict[str, str]:
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
|
|||||||
@@ -6,7 +6,6 @@
|
|||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from ..persons import logic as person_logic
|
from ..persons import logic as person_logic
|
||||||
from ..models.openalex.author import Author
|
from ..models.openalex.author import Author
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from . import model
|
|||||||
from typing import Annotated, Optional
|
from typing import Annotated, Optional
|
||||||
from fastapi import Path
|
from fastapi import Path
|
||||||
from fastapi import Query
|
from fastapi import Query
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||||
|
|
||||||
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||||
@@ -14,36 +15,35 @@ patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
|||||||
@router.get(
|
@router.get(
|
||||||
"/{author_id}/patents",
|
"/{author_id}/patents",
|
||||||
operation_id="getPatentsByAuthor",
|
operation_id="getPatentsByAuthor",
|
||||||
response_model=model.PatentsByAuthorResponse,
|
|
||||||
summary="Get patents matched to an author by name.",
|
summary="Get patents matched to an author by name.",
|
||||||
)
|
)
|
||||||
async def get_patents_by_author(author_id: str):
|
async def get_patents_by_author(author_id: str) -> model.PatentsByAuthorResponse:
|
||||||
return await logic.get_patents_by_author_id(author_id)
|
return await logic.get_patents_by_author_id(author_id)
|
||||||
|
|
||||||
|
|
||||||
@patents_router.get(
|
@patents_router.get(
|
||||||
"/patents/{identifier}",
|
"/patents/{identifier}",
|
||||||
operation_id="getPatentByIdOrTitle",
|
operation_id="getPatentByIdOrTitle",
|
||||||
response_model=model.PatentEntry | None,
|
|
||||||
summary="Returns one publication by OpenAlex ID or DOI.",
|
summary="Returns one publication by OpenAlex ID or DOI.",
|
||||||
)
|
)
|
||||||
async def get_patent_by_identifier(
|
async def get_patent_by_identifier(
|
||||||
identifier: Annotated[
|
identifier: Annotated[str, Path(description="")],
|
||||||
str, Path(description="")
|
|
||||||
],
|
|
||||||
prefix: Annotated[
|
prefix: Annotated[
|
||||||
Optional[str], Query(description="Application Prefix (EP or US)")
|
Optional[str], Query(description="Application Prefix (EP or US)")
|
||||||
] = "",
|
] = "",
|
||||||
title: Annotated[
|
title: Annotated[
|
||||||
Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
|
Optional[str],
|
||||||
|
Query(
|
||||||
|
description="Do we want to fallback to title search if ID and DOI dont work?"
|
||||||
|
),
|
||||||
] = "",
|
] = "",
|
||||||
):
|
) -> model.PatentEntry | None:
|
||||||
return await logic.get_patent(patent_id=identifier,prefix=prefix,title=title)
|
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title)
|
||||||
|
|
||||||
|
|
||||||
@patents_router.get(
|
@patents_router.get(
|
||||||
"/patents",
|
"/patents",
|
||||||
operation_id="getAllPatents",
|
operation_id="getAllPatents",
|
||||||
response_model=model.AllPatentsResponse,
|
|
||||||
summary="Get all patents with pagination and search.",
|
summary="Get all patents with pagination and search.",
|
||||||
)
|
)
|
||||||
async def get_all_patents(
|
async def get_all_patents(
|
||||||
@@ -53,7 +53,7 @@ async def get_all_patents(
|
|||||||
source: str | None = None,
|
source: str | None = None,
|
||||||
sort_by: str = "date",
|
sort_by: str = "date",
|
||||||
sort_direction: str = "desc",
|
sort_direction: str = "desc",
|
||||||
):
|
) -> model.AllPatentsResponse:
|
||||||
return await logic.get_all_patents(
|
return await logic.get_all_patents(
|
||||||
page=page,
|
page=page,
|
||||||
size=size,
|
size=size,
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import time
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional, Callable, Any, List
|
from typing import Optional, Callable, Any, List
|
||||||
import hashlib
|
import hashlib
|
||||||
import httpx
|
|
||||||
from inse.exceptions import (
|
from inse.exceptions import (
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
ElasticsearchException,
|
ElasticsearchException,
|
||||||
@@ -25,14 +24,12 @@ from .. import util
|
|||||||
from ..integrations import llm
|
from ..integrations import llm
|
||||||
from inse.models.openalex.author import Author
|
from inse.models.openalex.author import Author
|
||||||
from inse.models.openalex.authors_list_response import AuthorsListResponse
|
from inse.models.openalex.authors_list_response import AuthorsListResponse
|
||||||
from inse import util
|
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.models.openalex.meta import Meta
|
from inse.models.openalex.meta import Meta
|
||||||
from inse.persons.query_builder import build_authors_search_rescored
|
from inse.persons.query_builder import build_authors_search_rescored
|
||||||
from inse.persons.model import (
|
from inse.persons.model import (
|
||||||
CustomAuthor,
|
CustomAuthor,
|
||||||
CustomAuthorsListResponse,
|
CustomAuthorsListResponse,
|
||||||
PersonSearchRequest,
|
|
||||||
CareerMetrics,
|
CareerMetrics,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -46,11 +43,7 @@ async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
|||||||
"query": {
|
"query": {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": [
|
"must": [
|
||||||
{
|
{"match_phrase": {"display_name": display_name}},
|
||||||
"match_phrase": {
|
|
||||||
"display_name": display_name
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"nested": {
|
"nested": {
|
||||||
"path": "affiliations",
|
"path": "affiliations",
|
||||||
@@ -455,7 +448,7 @@ async def get_person_by_id(
|
|||||||
elapsed_time = time.time() - start_time
|
elapsed_time = time.time() - start_time
|
||||||
|
|
||||||
logger.info(
|
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(
|
custom_author = CustomAuthor(
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||||
|
|
||||||
import httpx
|
|
||||||
import urllib
|
import urllib
|
||||||
from inse.config import get_settings
|
from inse.config import get_settings
|
||||||
from inse.models.bund_project import BundProject
|
from inse.models.bund_project import BundProject
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
from functools import lru_cache
|
|
||||||
import logging
|
import logging
|
||||||
from typing import Annotated, Optional, Set
|
from typing import Annotated, Optional, Set
|
||||||
|
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ async def get_bund_projects_by_institution_id(
|
|||||||
f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}"
|
f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}"
|
||||||
)
|
)
|
||||||
institution_aliases = (
|
institution_aliases = (
|
||||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
filtering_properties.raw_oa_institution_id
|
filtering_properties.raw_oa_institution_id
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -129,7 +129,7 @@ async def get_cordis_eu_projects_by_institution_id(
|
|||||||
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
|
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
|
||||||
)
|
)
|
||||||
institution_aliases = (
|
institution_aliases = (
|
||||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
projects_filtering_properties.raw_oa_institution_id
|
projects_filtering_properties.raw_oa_institution_id
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -182,7 +182,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
|||||||
raw_oa_institution_id: str,
|
raw_oa_institution_id: str,
|
||||||
) -> InstitutionFunderSummary:
|
) -> InstitutionFunderSummary:
|
||||||
institution_aliases = (
|
institution_aliases = (
|
||||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
raw_oa_institution_id
|
raw_oa_institution_id
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -212,7 +212,7 @@ async def get_institution_bund_projects_funding_over_time(
|
|||||||
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
|
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
|
||||||
)
|
)
|
||||||
institution_aliases = (
|
institution_aliases = (
|
||||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
raw_oa_institution_id
|
raw_oa_institution_id
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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})"
|
|
||||||
@@ -1,84 +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 typing import Union
|
|
||||||
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
|
|
||||||
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.")
|
|
||||||
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(credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), db: Session = Depends(database.get)) -> 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
|
|
||||||
@@ -6,28 +6,13 @@ service.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from typing import Annotated, List, Optional
|
from typing import Annotated, List
|
||||||
from fastapi import FastAPI
|
|
||||||
from fastapi import Depends
|
|
||||||
from fastapi import Path
|
|
||||||
from fastapi import Query
|
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 inse.config import get_settings
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
|
||||||
from . import model
|
|
||||||
from . import logic
|
from . import logic
|
||||||
from . import schema
|
|
||||||
from . import database
|
|
||||||
from . import security
|
|
||||||
from . import util
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -42,126 +27,6 @@ router = APIRouter(
|
|||||||
responses={404: {"description": "Not found"}},
|
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
|
### topics
|
||||||
# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing)
|
# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing)
|
||||||
@@ -209,6 +74,7 @@ def count_topic_hierarchy(
|
|||||||
):
|
):
|
||||||
return logic.count_topic_hierarchy(topic_names)
|
return logic.count_topic_hierarchy(topic_names)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/topics/hierarchy",
|
"/topics/hierarchy",
|
||||||
operation_id="getTopicHierarchy",
|
operation_id="getTopicHierarchy",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from enum import Enum
|
from enum import StrEnum
|
||||||
|
|
||||||
|
|
||||||
class Tags(Enum):
|
class Tags(StrEnum):
|
||||||
PERSON = "Person"
|
PERSON = "Person"
|
||||||
PERSON_NETWORK = "Person Network"
|
PERSON_NETWORK = "Person Network"
|
||||||
INSTITUTIONS = "Institutions"
|
INSTITUTIONS = "Institutions"
|
||||||
@@ -9,3 +9,6 @@ class Tags(Enum):
|
|||||||
WORKS = "Works"
|
WORKS = "Works"
|
||||||
NEWS = "News"
|
NEWS = "News"
|
||||||
PROJECTS = "Projects"
|
PROJECTS = "Projects"
|
||||||
|
AUTH = "Auth"
|
||||||
|
ACCOUNT = "Account"
|
||||||
|
ORGANIZATION = "Organization"
|
||||||
|
|||||||
@@ -3,13 +3,17 @@
|
|||||||
"""
|
"""
|
||||||
Business logic for OpenAlex topics.
|
Business logic for OpenAlex topics.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException
|
from inse.exceptions import (
|
||||||
|
UpstreamAPIException,
|
||||||
|
BadRequestException,
|
||||||
|
ElasticsearchException,
|
||||||
|
)
|
||||||
|
|
||||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||||
@@ -17,6 +21,7 @@ from inse.models.openalex.autocomplete_response_results_inner import (
|
|||||||
AutocompleteResponseResultsInner,
|
AutocompleteResponseResultsInner,
|
||||||
)
|
)
|
||||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||||
|
from inse.model import ESCluster
|
||||||
from .search_client import OpenAlexTopicsClient
|
from .search_client import OpenAlexTopicsClient
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -40,34 +45,17 @@ async def list_topics(
|
|||||||
|
|
||||||
openalex_client = client or OpenAlexTopicsClient()
|
openalex_client = client or OpenAlexTopicsClient()
|
||||||
|
|
||||||
try:
|
data = await openalex_client.list_topics(
|
||||||
data = await openalex_client.list_topics(
|
search=search,
|
||||||
search=search,
|
filter=filter,
|
||||||
filter=filter,
|
sort=sort,
|
||||||
sort=sort,
|
group_by=group_by,
|
||||||
group_by=group_by,
|
per_page=per_page,
|
||||||
per_page=per_page,
|
page=page,
|
||||||
page=page,
|
cursor=cursor,
|
||||||
cursor=cursor,
|
sample=sample,
|
||||||
sample=sample,
|
select=select,
|
||||||
select=select,
|
)
|
||||||
)
|
|
||||||
except httpx.HTTPStatusError as exc:
|
|
||||||
status_code = exc.response.status_code
|
|
||||||
detail = "OpenAlex topics request failed."
|
|
||||||
try:
|
|
||||||
error_body = exc.response.json()
|
|
||||||
detail = error_body.get("message") or error_body.get("error") or detail
|
|
||||||
except ValueError:
|
|
||||||
if exc.response.text:
|
|
||||||
detail = exc.response.text
|
|
||||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
|
||||||
except httpx.HTTPError as exc:
|
|
||||||
logger.exception("OpenAlex topics request failed.")
|
|
||||||
raise UpstreamAPIException(
|
|
||||||
message="OpenAlex topics request failed.",
|
|
||||||
status_code=502,
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
normalized_data = _normalize_topics_response(data)
|
normalized_data = _normalize_topics_response(data)
|
||||||
@@ -151,7 +139,13 @@ def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
meta = normalized.get("meta")
|
meta = normalized.get("meta")
|
||||||
if isinstance(meta, dict):
|
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[field] = _int_or_none(meta.get(field))
|
||||||
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
|
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
|
||||||
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
|
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
|
||||||
@@ -251,8 +245,11 @@ def _datetime_str_or_none(value: Any) -> str | None:
|
|||||||
return f"{text}T00:00:00Z"
|
return f"{text}T00:00:00Z"
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
# Configuration for vector search similarity thresholds and boosts
|
# Configuration for vector search similarity thresholds and boosts
|
||||||
SIMILARITY_THRESHOLD = 0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
SIMILARITY_THRESHOLD = (
|
||||||
|
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||||
|
)
|
||||||
BOOST_LEXICAL = 1.0
|
BOOST_LEXICAL = 1.0
|
||||||
# higher values for semantic weights, because cosine similarity is between 0 and 1
|
# higher values for semantic weights, because cosine similarity is between 0 and 1
|
||||||
BOOST_DISPLAY_NAME_VECTOR = 30.0
|
BOOST_DISPLAY_NAME_VECTOR = 30.0
|
||||||
@@ -262,6 +259,7 @@ BOOST_KEYWORD_VECTORS = 25.0
|
|||||||
K = 500
|
K = 500
|
||||||
NUM_CANDIDATES = 500
|
NUM_CANDIDATES = 500
|
||||||
|
|
||||||
|
|
||||||
async def vector_search_topics(
|
async def vector_search_topics(
|
||||||
*,
|
*,
|
||||||
query: str,
|
query: str,
|
||||||
@@ -277,7 +275,9 @@ async def vector_search_topics(
|
|||||||
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("Failed to load elasticsearch integration.")
|
logger.exception("Failed to load elasticsearch integration.")
|
||||||
raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc
|
raise ElasticsearchException(
|
||||||
|
f"Failed to load elasticsearch integration: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
# 1. Vectorize query
|
# 1. Vectorize query
|
||||||
try:
|
try:
|
||||||
@@ -292,68 +292,72 @@ async def vector_search_topics(
|
|||||||
|
|
||||||
# Lexical multi_match search (only in hybrid mode)
|
# Lexical multi_match search (only in hybrid mode)
|
||||||
if search_type == "hybrid":
|
if search_type == "hybrid":
|
||||||
should_clauses.append({
|
should_clauses.append(
|
||||||
"multi_match": {
|
{
|
||||||
"query": query,
|
"multi_match": {
|
||||||
"fields": [
|
"query": query,
|
||||||
"display_name^3",
|
"fields": ["display_name^3", "keywords^2"],
|
||||||
"keywords^2"
|
"boost": BOOST_LEXICAL,
|
||||||
],
|
}
|
||||||
"boost": BOOST_LEXICAL
|
|
||||||
}
|
}
|
||||||
})
|
)
|
||||||
|
|
||||||
# Semantic KNN clauses
|
# Semantic KNN clauses
|
||||||
should_clauses.extend([
|
should_clauses.extend(
|
||||||
{
|
[
|
||||||
"knn": {
|
{
|
||||||
"field": "display_name_vector",
|
"knn": {
|
||||||
"query_vector": query_vector,
|
"field": "display_name_vector",
|
||||||
"similarity": SIMILARITY_THRESHOLD,
|
"query_vector": query_vector,
|
||||||
"boost": BOOST_DISPLAY_NAME_VECTOR,
|
"similarity": SIMILARITY_THRESHOLD,
|
||||||
"k": K,
|
"boost": BOOST_DISPLAY_NAME_VECTOR,
|
||||||
"num_candidates": NUM_CANDIDATES
|
"k": K,
|
||||||
}
|
"num_candidates": NUM_CANDIDATES,
|
||||||
},
|
}
|
||||||
{
|
},
|
||||||
"nested": {
|
{
|
||||||
"path": "keyword_vectors",
|
"nested": {
|
||||||
"query": {
|
"path": "keyword_vectors",
|
||||||
"knn": {
|
"query": {
|
||||||
"field": "keyword_vectors.vector",
|
"knn": {
|
||||||
"query_vector": query_vector,
|
"field": "keyword_vectors.vector",
|
||||||
"similarity": SIMILARITY_THRESHOLD,
|
"query_vector": query_vector,
|
||||||
"k": K,
|
"similarity": SIMILARITY_THRESHOLD,
|
||||||
"num_candidates": NUM_CANDIDATES
|
"k": K,
|
||||||
}
|
"num_candidates": NUM_CANDIDATES,
|
||||||
},
|
}
|
||||||
"score_mode": "max",
|
},
|
||||||
"boost": BOOST_KEYWORD_VECTORS
|
"score_mode": "max",
|
||||||
}
|
"boost": BOOST_KEYWORD_VECTORS,
|
||||||
}
|
}
|
||||||
])
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
body = {
|
body = {
|
||||||
"query": {
|
"query": {"bool": {"should": should_clauses}},
|
||||||
"bool": {
|
|
||||||
"should": should_clauses
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"_source": {
|
"_source": {
|
||||||
"excludes": ["display_name_vector", "keyword_vectors", "works_api_url", "updated_date", "created_date", "_index" ] # remove unrequired fields
|
"excludes": [
|
||||||
|
"display_name_vector",
|
||||||
|
"keyword_vectors",
|
||||||
|
"works_api_url",
|
||||||
|
"updated_date",
|
||||||
|
"created_date",
|
||||||
|
"_index",
|
||||||
|
] # remove unrequired fields
|
||||||
},
|
},
|
||||||
"size": limit
|
"size": limit,
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
raw_results = await elasticsearch.search(
|
raw_results = await elasticsearch.search(
|
||||||
index="topicvectors",
|
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||||
body=body,
|
|
||||||
cluster="nes"
|
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||||
raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc
|
raise ElasticsearchException(
|
||||||
|
f"Unexpected vector search failure: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
# 3. Format result
|
# 3. Format result
|
||||||
hits = raw_results.get("hits", {}).get("hits", [])
|
hits = raw_results.get("hits", {}).get("hits", [])
|
||||||
@@ -361,19 +365,13 @@ async def vector_search_topics(
|
|||||||
total = len(hits)
|
total = len(hits)
|
||||||
results = [hit.get("_source", {}) for hit in hits]
|
results = [hit.get("_source", {}) for hit in hits]
|
||||||
|
|
||||||
data = {
|
data = {"meta": {"count": total, "page": 1, "per_page": limit}, "results": results}
|
||||||
"meta": {
|
|
||||||
"count": total,
|
|
||||||
"page": 1,
|
|
||||||
"per_page": limit
|
|
||||||
},
|
|
||||||
"results": results
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
normalized_data = _normalize_topics_response(data)
|
normalized_data = _normalize_topics_response(data)
|
||||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||||
except ValidationError as exc:
|
except ValidationError as exc:
|
||||||
logger.exception("Vector search response could not be parsed.")
|
logger.exception("Vector search response could not be parsed.")
|
||||||
raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc
|
raise ElasticsearchException(
|
||||||
|
f"Vector search response could not be parsed: {exc}"
|
||||||
|
) from exc
|
||||||
|
|||||||
@@ -1,33 +1,18 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""Elasticsearch client for OpenAlex topics."""
|
||||||
HTTP client for OpenAlex topics.
|
|
||||||
"""
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.model import ESCluster
|
||||||
from .. import config
|
|
||||||
|
|
||||||
|
|
||||||
class OpenAlexTopicsClient:
|
class OpenAlexTopicsClient:
|
||||||
def __init__(
|
def __init__(self, index: str = "topicvectors"):
|
||||||
self,
|
self.index = index
|
||||||
base_url: str | None = None,
|
|
||||||
api_key: str | None = None,
|
|
||||||
timeout: float | None = None,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
|
||||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
|
||||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
|
||||||
self.timeout = (
|
|
||||||
timeout
|
|
||||||
if timeout is not None
|
|
||||||
else config.settings.openalex_api_timeout_seconds
|
|
||||||
)
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def list_topics_params(
|
def list_topics_query(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
@@ -40,60 +25,118 @@ class OpenAlexTopicsClient:
|
|||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
params: dict[str, Any] = {"per_page": per_page}
|
filters = self._filters(filter)
|
||||||
|
must: list[dict[str, Any]] = []
|
||||||
if search:
|
if search:
|
||||||
params["search"] = search
|
must.append(
|
||||||
if filter:
|
{
|
||||||
params["filter"] = filter
|
"multi_match": {
|
||||||
if sort:
|
"query": search,
|
||||||
params["sort"] = sort
|
"fields": ["display_name^3", "keywords^2", "description"],
|
||||||
if group_by:
|
}
|
||||||
params["group_by"] = group_by
|
}
|
||||||
if cursor:
|
|
||||||
params["cursor"] = cursor
|
|
||||||
elif page is not None:
|
|
||||||
params["page"] = page
|
|
||||||
if sample is not None:
|
|
||||||
params["sample"] = sample
|
|
||||||
if select:
|
|
||||||
params["select"] = select
|
|
||||||
if self.api_key:
|
|
||||||
params["api_key"] = self.api_key
|
|
||||||
|
|
||||||
return params
|
|
||||||
|
|
||||||
async def list_topics(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
search: str | None = None,
|
|
||||||
filter: str | None = None,
|
|
||||||
sort: str | None = None,
|
|
||||||
group_by: str | None = None,
|
|
||||||
per_page: int = 25,
|
|
||||||
page: int | None = 1,
|
|
||||||
cursor: str | None = None,
|
|
||||||
sample: int | None = None,
|
|
||||||
select: str | None = None,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
async with httpx.AsyncClient(
|
|
||||||
base_url=self.base_url,
|
|
||||||
timeout=self.timeout,
|
|
||||||
transport=self.transport,
|
|
||||||
) as client:
|
|
||||||
response = await client.get(
|
|
||||||
"/topics",
|
|
||||||
params=self.list_topics_params(
|
|
||||||
search=search,
|
|
||||||
filter=filter,
|
|
||||||
sort=sort,
|
|
||||||
group_by=group_by,
|
|
||||||
per_page=per_page,
|
|
||||||
page=page,
|
|
||||||
cursor=cursor,
|
|
||||||
sample=sample,
|
|
||||||
select=select,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"must": must or [{"match_all": {}}],
|
||||||
|
"filter": filters,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sample is not None:
|
||||||
|
query = {"function_score": {"query": query, "random_score": {"seed": sample}}}
|
||||||
|
|
||||||
|
body: dict[str, Any] = {
|
||||||
|
"query": query,
|
||||||
|
"from": max((page or 1) - 1, 0) * per_page,
|
||||||
|
"size": per_page,
|
||||||
|
"track_total_hits": True,
|
||||||
|
"_source": (
|
||||||
|
[field.strip() for field in select.split(",") if field.strip()]
|
||||||
|
if select
|
||||||
|
else {"excludes": ["display_name_vector", "keyword_vectors"]}
|
||||||
|
),
|
||||||
|
}
|
||||||
|
if sort:
|
||||||
|
body["sort"] = self._sort(sort)
|
||||||
|
if cursor and cursor != "*":
|
||||||
|
body["search_after"] = cursor.split(",")
|
||||||
|
body.pop("from", None)
|
||||||
|
if group_by:
|
||||||
|
body["aggs"] = {
|
||||||
|
"group_by": {
|
||||||
|
"terms": {"field": self._keyword_field(group_by), "size": per_page}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
|
||||||
|
async def list_topics(self, **kwargs: Any) -> dict[str, Any]:
|
||||||
|
body = self.list_topics_query(**kwargs)
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=self.index,
|
||||||
|
body=body,
|
||||||
|
cluster=ESCluster.NES,
|
||||||
|
)
|
||||||
|
hits_block = response.get("hits", {})
|
||||||
|
hits = hits_block.get("hits", [])
|
||||||
|
total_value = hits_block.get("total", 0)
|
||||||
|
total = total_value.get("value", 0) if isinstance(total_value, dict) else total_value
|
||||||
|
per_page = kwargs.get("per_page", 25)
|
||||||
|
page = kwargs.get("page", 1)
|
||||||
|
|
||||||
|
result: dict[str, Any] = {
|
||||||
|
"meta": {
|
||||||
|
"count": total,
|
||||||
|
"page": page,
|
||||||
|
"per_page": per_page,
|
||||||
|
"next_cursor": self._next_cursor(hits),
|
||||||
|
},
|
||||||
|
"results": [hit.get("_source", {}) for hit in hits],
|
||||||
|
}
|
||||||
|
buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets")
|
||||||
|
if buckets is not None:
|
||||||
|
result["group_by"] = [
|
||||||
|
{
|
||||||
|
"key": bucket.get("key"),
|
||||||
|
"key_display_name": bucket.get("key_as_string", bucket.get("key")),
|
||||||
|
"count": bucket.get("doc_count"),
|
||||||
|
}
|
||||||
|
for bucket in buckets
|
||||||
|
]
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _filters(value: str | None) -> list[dict[str, Any]]:
|
||||||
|
clauses: list[dict[str, Any]] = []
|
||||||
|
for item in (value or "").split(","):
|
||||||
|
if not item or ":" not in item:
|
||||||
|
continue
|
||||||
|
field, raw_value = item.split(":", 1)
|
||||||
|
field = OpenAlexTopicsClient._keyword_field(field.strip())
|
||||||
|
raw_value = raw_value.strip()
|
||||||
|
if raw_value.startswith((">", "<")):
|
||||||
|
operator = "gt" if raw_value[0] == ">" else "lt"
|
||||||
|
clauses.append({"range": {field.removesuffix(".keyword"): {operator: raw_value[1:]}}})
|
||||||
|
else:
|
||||||
|
clauses.append({"term": {field: raw_value}})
|
||||||
|
return clauses
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _sort(value: str) -> list[dict[str, Any]]:
|
||||||
|
result = []
|
||||||
|
for item in value.split(","):
|
||||||
|
field, _, direction = item.partition(":")
|
||||||
|
result.append({field.strip(): {"order": direction or "desc", "missing": "_last"}})
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _keyword_field(field: str) -> str:
|
||||||
|
if field in {"id", "display_name", "domain.id", "field.id", "subfield.id"}:
|
||||||
|
return f"{field}.keyword"
|
||||||
|
return field
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _next_cursor(hits: list[dict[str, Any]]) -> str | None:
|
||||||
|
if not hits or not hits[-1].get("sort"):
|
||||||
|
return None
|
||||||
|
return ",".join(str(value) for value in hits[-1]["sort"])
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
from inse.exceptions import BadRequestException
|
|
||||||
|
|
||||||
|
from inse.exceptions import BadRequestException
|
||||||
from inse.topics import logic
|
from inse.topics import logic
|
||||||
from inse.topics.search_client import OpenAlexTopicsClient
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -11,183 +9,71 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
class StubTopicsClient:
|
||||||
async def test_list_topics_maps_openalex_response_to_model():
|
def __init__(self, response):
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
self.response = response
|
||||||
return httpx.Response(
|
self.kwargs = None
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"id": "https://openalex.org/T12419",
|
|
||||||
"display_name": "Machine learning",
|
|
||||||
"description": "Methods that learn from data.",
|
|
||||||
"keywords": ["machine learning", "classification"],
|
|
||||||
"subfield": {
|
|
||||||
"id": "https://openalex.org/subfields/1702",
|
|
||||||
"display_name": "Artificial Intelligence",
|
|
||||||
},
|
|
||||||
"field": {
|
|
||||||
"id": "https://openalex.org/fields/17",
|
|
||||||
"display_name": "Computer Science",
|
|
||||||
},
|
|
||||||
"domain": {
|
|
||||||
"id": "https://openalex.org/domains/4",
|
|
||||||
"display_name": "Physical Sciences",
|
|
||||||
},
|
|
||||||
"works_count": 123,
|
|
||||||
"cited_by_count": 456,
|
|
||||||
"ids": {
|
|
||||||
"openalex": "https://openalex.org/T12419",
|
|
||||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
|
||||||
},
|
|
||||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
|
||||||
"created_date": "2023-12-25",
|
|
||||||
"updated_date": "2023-11-07T05:31:56Z",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"group_by": [
|
|
||||||
{
|
|
||||||
"key": "https://openalex.org/domains/4",
|
|
||||||
"key_display_name": "Physical Sciences",
|
|
||||||
"count": 1,
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
async def list_topics(self, **kwargs):
|
||||||
api_key="test-key",
|
self.kwargs = kwargs
|
||||||
transport=httpx.MockTransport(handler),
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||||
|
client = StubTopicsClient(
|
||||||
|
{
|
||||||
|
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"id": "https://openalex.org/T12419",
|
||||||
|
"display_name": "Machine learning",
|
||||||
|
"field": {"display_name": "Computer Science"},
|
||||||
|
"subfield": {"display_name": "Artificial Intelligence"},
|
||||||
|
"domain": {"display_name": "Physical Sciences"},
|
||||||
|
"works_count": 123,
|
||||||
|
"cited_by_count": 456,
|
||||||
|
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_topics(search="machine learning", client=client)
|
result = await logic.list_topics(search="machine learning", client=client)
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.meta.count == 1
|
||||||
topic = result.results[0]
|
assert result.results[0].var_field.display_name == "Computer Science"
|
||||||
assert topic.display_name == "Machine learning"
|
assert client.kwargs["search"] == "machine learning"
|
||||||
assert topic.var_field.display_name == "Computer Science"
|
|
||||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
|
||||||
assert topic.domain.display_name == "Physical Sciences"
|
|
||||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
|
||||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_rejects_sample_with_sort():
|
async def test_list_topics_rejects_sample_with_sort():
|
||||||
with pytest.raises(BadRequestException) as exc_info:
|
with pytest.raises(BadRequestException):
|
||||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
|
||||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
|
||||||
return httpx.Response(
|
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"id": 123,
|
|
||||||
"display_name": 456,
|
|
||||||
"description": True,
|
|
||||||
"keywords": ["topic", 123],
|
|
||||||
"subfield": {"id": 1, "display_name": 2},
|
|
||||||
"field": {"id": 3, "display_name": 4},
|
|
||||||
"domain": {"id": 5, "display_name": 6},
|
|
||||||
"works_count": "12.0",
|
|
||||||
"cited_by_count": False,
|
|
||||||
"ids": {"openalex": 123, "wikipedia": 456},
|
|
||||||
"created_date": "2023-12-25T10:11:12Z",
|
|
||||||
"updated_date": "2023-12-25",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"group_by": [{"key": True, "count": "1"}],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
|
||||||
api_key="test-key",
|
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
|
||||||
|
|
||||||
result = await logic.list_topics(client=client)
|
|
||||||
|
|
||||||
topic = result.results[0]
|
|
||||||
assert topic.id == "123"
|
|
||||||
assert topic.display_name == "456"
|
|
||||||
assert topic.description == "true"
|
|
||||||
assert topic.keywords == ["topic", "123"]
|
|
||||||
assert topic.works_count == 12
|
|
||||||
assert topic.cited_by_count is None
|
|
||||||
assert topic.var_field.id == "3"
|
|
||||||
assert topic.domain.display_name == "6"
|
|
||||||
assert topic.ids.wikipedia == "456"
|
|
||||||
assert topic.created_date.isoformat() == "2023-12-25"
|
|
||||||
assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00"
|
|
||||||
assert result.group_by[0].key == "true"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_autocomplete_topics_returns_frontend_options():
|
async def test_autocomplete_topics_returns_frontend_options():
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
client = StubTopicsClient(
|
||||||
assert request.url.params["search"] == "machine learning"
|
{
|
||||||
assert request.url.params["filter"] == (
|
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||||
"domain.id:https://openalex.org/domains/4,"
|
"results": [
|
||||||
"field.id:https://openalex.org/fields/17,"
|
{
|
||||||
"subfield.id:https://openalex.org/subfields/1702"
|
"id": "https://openalex.org/T12419",
|
||||||
)
|
"display_name": "Machine learning",
|
||||||
assert request.url.params["sort"] == "works_count:desc"
|
"field": {"display_name": "Computer Science"},
|
||||||
assert request.url.params["per_page"] == "5"
|
"subfield": {"display_name": "Artificial Intelligence"},
|
||||||
assert request.url.params["select"] == (
|
"domain": {"display_name": "Physical Sciences"},
|
||||||
"id,display_name,description,keywords,subfield,field,domain,"
|
"works_count": 123,
|
||||||
"works_count,cited_by_count,ids"
|
"cited_by_count": 456,
|
||||||
)
|
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||||
return httpx.Response(
|
}
|
||||||
200,
|
],
|
||||||
json={
|
}
|
||||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"id": "https://openalex.org/T12419",
|
|
||||||
"display_name": "Machine learning",
|
|
||||||
"description": "Methods that learn from data.",
|
|
||||||
"field": {"display_name": "Computer Science"},
|
|
||||||
"subfield": {"display_name": "Artificial Intelligence"},
|
|
||||||
"domain": {"display_name": "Physical Sciences"},
|
|
||||||
"works_count": 123,
|
|
||||||
"cited_by_count": 456,
|
|
||||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
|
||||||
api_key="test-key",
|
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.autocomplete_topics(
|
result = await logic.autocomplete_topics(query="machine learning", limit=5, client=client)
|
||||||
query="machine learning",
|
|
||||||
domain_id="https://openalex.org/domains/4",
|
|
||||||
field_id="https://openalex.org/fields/17",
|
|
||||||
subfield_id="https://openalex.org/subfields/1702",
|
|
||||||
limit=5,
|
|
||||||
client=client,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.results[0].hint == "Computer Science · Artificial Intelligence · Physical Sciences"
|
||||||
assert result.meta.db_response_time_ms == 12
|
assert result.results[0].entity_type == "topic"
|
||||||
assert len(result.results) == 1
|
assert client.kwargs["sort"] == "works_count:desc"
|
||||||
option = result.results[0]
|
|
||||||
assert option.id == "https://openalex.org/T12419"
|
|
||||||
assert option.display_name == "Machine learning"
|
|
||||||
assert option.hint == (
|
|
||||||
"Computer Science · Artificial Intelligence · Physical Sciences"
|
|
||||||
)
|
|
||||||
assert option.works_count == 123
|
|
||||||
assert option.cited_by_count == 456
|
|
||||||
assert option.entity_type == "topic"
|
|
||||||
assert option.external_id == "https://openalex.org/T12419"
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import httpx
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from inse.model import ESCluster
|
||||||
from inse.topics.search_client import OpenAlexTopicsClient
|
from inse.topics.search_client import OpenAlexTopicsClient
|
||||||
|
|
||||||
|
|
||||||
@@ -9,67 +11,39 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
def test_list_topics_params_include_openalex_query_parameters():
|
def test_list_topics_query_builds_elasticsearch_query():
|
||||||
client = OpenAlexTopicsClient(api_key="test-key")
|
body = OpenAlexTopicsClient().list_topics_query(
|
||||||
|
|
||||||
params = client.list_topics_params(
|
|
||||||
search="machine learning",
|
search="machine learning",
|
||||||
filter="domain.id:4,works_count:>1000",
|
filter="domain.id:https://openalex.org/domains/4,works_count:>1000",
|
||||||
sort="works_count:desc",
|
sort="works_count:desc",
|
||||||
group_by="domain.id",
|
|
||||||
per_page=10,
|
per_page=10,
|
||||||
page=2,
|
page=2,
|
||||||
select="id,display_name",
|
select="id,display_name",
|
||||||
)
|
)
|
||||||
|
|
||||||
assert params == {
|
assert body["from"] == 10
|
||||||
"search": "machine learning",
|
assert body["size"] == 10
|
||||||
"filter": "domain.id:4,works_count:>1000",
|
assert body["_source"] == ["id", "display_name"]
|
||||||
"sort": "works_count:desc",
|
assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "machine learning"
|
||||||
"group_by": "domain.id",
|
assert {"term": {"domain.id.keyword": "https://openalex.org/domains/4"}} in body["query"]["bool"]["filter"]
|
||||||
"per_page": 10,
|
assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"]
|
||||||
"page": 2,
|
assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}]
|
||||||
"select": "id,display_name",
|
|
||||||
"api_key": "test-key",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_list_topics_params_prefers_cursor_over_page():
|
|
||||||
client = OpenAlexTopicsClient(api_key="test-key")
|
|
||||||
|
|
||||||
params = client.list_topics_params(cursor="*", page=3)
|
|
||||||
|
|
||||||
assert params["cursor"] == "*"
|
|
||||||
assert "page" not in params
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
async def test_list_topics_calls_elasticsearch_and_maps_hits():
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
response = {
|
||||||
assert request.method == "GET"
|
"hits": {
|
||||||
assert request.url.path == "/topics"
|
"total": {"value": 1},
|
||||||
assert request.url.params["search"] == "machine learning"
|
"hits": [{"_source": {"id": "T1", "display_name": "Machine learning"}}],
|
||||||
assert request.url.params["api_key"] == "test-key"
|
}
|
||||||
return httpx.Response(
|
}
|
||||||
200,
|
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search:
|
||||||
json={
|
search.return_value = response
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
result = await OpenAlexTopicsClient(index="topicvectors").list_topics(search="machine")
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"id": "https://openalex.org/T12419",
|
|
||||||
"display_name": "Machine learning",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
|
||||||
base_url="https://api.openalex.org",
|
|
||||||
api_key="test-key",
|
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
|
||||||
|
|
||||||
result = await client.list_topics(search="machine learning")
|
|
||||||
|
|
||||||
|
search.assert_awaited_once()
|
||||||
|
assert search.await_args.kwargs["index"] == "topicvectors"
|
||||||
|
assert search.await_args.kwargs["cluster"] == ESCluster.NES
|
||||||
assert result["meta"]["count"] == 1
|
assert result["meta"]["count"] == 1
|
||||||
assert result["results"][0]["display_name"] == "Machine learning"
|
assert result["results"][0]["display_name"] == "Machine learning"
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import logging
|
|||||||
from time import time
|
from time import time
|
||||||
from typing import Any, List
|
from typing import Any, List
|
||||||
|
|
||||||
import httpx
|
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from starlette.status import HTTP_404_NOT_FOUND
|
from starlette.status import HTTP_404_NOT_FOUND
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
import urllib
|
import urllib
|
||||||
from .. import config
|
from .. import config
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
@@ -19,17 +18,11 @@ logger = logging.getLogger(__name__)
|
|||||||
class OpenAlexWorksSearchClient:
|
class OpenAlexWorksSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
|
||||||
index: str | None = None,
|
index: str | None = None,
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
timeout: float | None = None,
|
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
|
|
||||||
self.index = index or config.settings.openalex_works_search_index
|
self.index = index or config.settings.openalex_works_search_index
|
||||||
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
||||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
|
|
||||||
def author_works_query(
|
def author_works_query(
|
||||||
|
|||||||
@@ -7,13 +7,11 @@ REST API for publication works.
|
|||||||
from typing import Annotated, Optional
|
from typing import Annotated, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
from fastapi import Depends
|
|
||||||
from fastapi import Path
|
from fastapi import Path
|
||||||
from fastapi import Query
|
from fastapi import Query
|
||||||
|
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
|
|
||||||
from .. import security
|
|
||||||
from . import logic
|
from . import logic
|
||||||
from inse.models.openalex.work_page import WorkPage
|
from inse.models.openalex.work_page import WorkPage
|
||||||
from inse.models.openalex.work import Work
|
from inse.models.openalex.work import Work
|
||||||
@@ -56,9 +54,6 @@ async def get_author_works(
|
|||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||||
] = None,
|
] = None,
|
||||||
principal: security.Principal = Depends(
|
|
||||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
|
||||||
),
|
|
||||||
):
|
):
|
||||||
return await logic.get_author_works(
|
return await logic.get_author_works(
|
||||||
author_id,
|
author_id,
|
||||||
@@ -72,35 +67,47 @@ async def get_author_works(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{author_id}/all",
|
@router.get(
|
||||||
operation_id="getAllAuthorWorks",
|
"/{author_id}/all",
|
||||||
response_model=WorksListResponse,
|
operation_id="getAllAuthorWorks",
|
||||||
summary="Returns all works for an author.")
|
response_model=WorksListResponse,
|
||||||
|
summary="Returns all works for an author.",
|
||||||
|
)
|
||||||
async def get_all_author_works(
|
async def get_all_author_works(
|
||||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
author_id: Annotated[
|
||||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
str, Path(description="The author id, for example A5023888391.")
|
||||||
|
],
|
||||||
):
|
):
|
||||||
return await logic.get_all_author_works(author_id)
|
return await logic.get_all_author_works(author_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{author_id}/primary-topic-counts",
|
@router.get(
|
||||||
operation_id="getPrimaryTopicCountsByAuthor",
|
"/{author_id}/primary-topic-counts",
|
||||||
response_model=list[TopicCount],
|
operation_id="getPrimaryTopicCountsByAuthor",
|
||||||
summary="Returns work counts per primary topic for an author.")
|
response_model=list[TopicCount],
|
||||||
|
summary="Returns work counts per primary topic for an author.",
|
||||||
|
)
|
||||||
async def get_primary_topic_counts(
|
async def get_primary_topic_counts(
|
||||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
author_id: Annotated[
|
||||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
str, Path(description="The author id, for example A5023888391.")
|
||||||
|
],
|
||||||
):
|
):
|
||||||
return await logic.get_primary_topic_counts(author_id)
|
return await logic.get_primary_topic_counts(author_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{author_id}/topics-by-time",
|
@router.get(
|
||||||
operation_id="getTopicsByTimeByAuthor",
|
"/{author_id}/topics-by-time",
|
||||||
response_model=TopicsByTime,
|
operation_id="getTopicsByTimeByAuthor",
|
||||||
summary="Returns topics grouped by publication year for an author.")
|
response_model=TopicsByTime,
|
||||||
|
summary="Returns topics grouped by publication year for an author.",
|
||||||
|
)
|
||||||
async def get_topics_by_time_by_author(
|
async def get_topics_by_time_by_author(
|
||||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
author_id: Annotated[
|
||||||
max_topics_per_year: Annotated[int, Query(description="The maximum number of topics per year.", ge=1, le=20)] = 3,
|
str, Path(description="The author id, for example A5023888391.")
|
||||||
|
],
|
||||||
|
max_topics_per_year: Annotated[
|
||||||
|
int, Query(description="The maximum number of topics per year.", ge=1, le=20)
|
||||||
|
] = 3,
|
||||||
target_publications: Annotated[
|
target_publications: Annotated[
|
||||||
int,
|
int,
|
||||||
Query(
|
Query(
|
||||||
@@ -112,7 +119,6 @@ async def get_topics_by_time_by_author(
|
|||||||
bool,
|
bool,
|
||||||
Query(description="If true, all publications are used for the timeline."),
|
Query(description="If true, all publications are used for the timeline."),
|
||||||
] = False,
|
] = False,
|
||||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
|
||||||
):
|
):
|
||||||
return await logic.get_topics_by_time_by_author(
|
return await logic.get_topics_by_time_by_author(
|
||||||
author_id,
|
author_id,
|
||||||
@@ -130,13 +136,16 @@ async def get_topics_by_time_by_author(
|
|||||||
)
|
)
|
||||||
async def get_work_by_identifier(
|
async def get_work_by_identifier(
|
||||||
identifier: Annotated[
|
identifier: Annotated[
|
||||||
str, Path(description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.")
|
str,
|
||||||
|
Path(
|
||||||
|
description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication."
|
||||||
|
),
|
||||||
],
|
],
|
||||||
title: Annotated[
|
title: Annotated[
|
||||||
Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
|
Optional[str],
|
||||||
|
Query(
|
||||||
|
description="Do we want to fallback to title search if ID and DOI dont work?"
|
||||||
|
),
|
||||||
] = "",
|
] = "",
|
||||||
principal: security.Principal = Depends(
|
|
||||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
|
||||||
),
|
|
||||||
):
|
):
|
||||||
return await logic.get_work(identifier,title=title)
|
return await logic.get_work(identifier, title=title)
|
||||||
|
|||||||
@@ -1,176 +1,94 @@
|
|||||||
import json
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
from fastapi import HTTPException
|
|
||||||
|
|
||||||
from inse.works import logic
|
from inse.works import logic
|
||||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
|
||||||
|
|
||||||
|
|
||||||
# @pytest.fixture
|
@pytest.fixture
|
||||||
# def anyio_backend():
|
def anyio_backend():
|
||||||
# return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
# @pytest.mark.anyio
|
def work_hit(identifier: str, title: str) -> dict:
|
||||||
# async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
return {
|
||||||
# def handler(request: httpx.Request) -> httpx.Response:
|
"_source": {
|
||||||
# return httpx.Response(
|
"id": f"https://openalex.org/{identifier}",
|
||||||
# 200,
|
"doi": f"https://doi.org/10.1234/{identifier.lower()}",
|
||||||
# json={
|
"title": title,
|
||||||
# "hits": {
|
"display_name": title,
|
||||||
# "total": {"value": 1},
|
"type": "article",
|
||||||
# "hits": [
|
"language": "en",
|
||||||
# {
|
"publication_year": 2024,
|
||||||
# "_source": {
|
"publication_date": "2024-01-01",
|
||||||
# "id": "https://openalex.org/W2741809807",
|
"cited_by_count": 42,
|
||||||
# "doi": "https://doi.org/10.7717/peerj.4375",
|
"topics": [
|
||||||
# "display_name": "Example work",
|
{
|
||||||
# "type": "article",
|
"id": "https://openalex.org/T10102",
|
||||||
# "language": "en",
|
"display_name": "Machine learning",
|
||||||
# "publication_year": 2023,
|
"score": 0.91,
|
||||||
# "cited_by_count": 42,
|
}
|
||||||
# "topics": [
|
],
|
||||||
# {
|
"authorships": [
|
||||||
# "id": "https://openalex.org/T10102",
|
{
|
||||||
# "display_name": "Machine learning",
|
"author": {
|
||||||
# "score": 0.91,
|
"id": "https://openalex.org/A5023888391",
|
||||||
# }
|
"display_name": "Example Author",
|
||||||
# ],
|
}
|
||||||
# "primary_location": {
|
}
|
||||||
# "source": {
|
],
|
||||||
# "id": "https://openalex.org/S123",
|
}
|
||||||
# "display_name": "Example Source",
|
}
|
||||||
# "issn": None,
|
|
||||||
# }
|
|
||||||
# },
|
|
||||||
# "authorships": [
|
|
||||||
# {
|
|
||||||
# "author": {
|
|
||||||
# "id": "https://openalex.org/A5023888391",
|
|
||||||
# "display_name": "Example Author",
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# ],
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# ],
|
|
||||||
# },
|
|
||||||
# },
|
|
||||||
# )
|
|
||||||
|
|
||||||
# client = OpenAlexWorksSearchClient(
|
|
||||||
# base_url="https://project.nes.uni-due.de/elastic",
|
|
||||||
# api_key="test-key",
|
|
||||||
# transport=httpx.MockTransport(handler),
|
|
||||||
# )
|
|
||||||
|
|
||||||
# page = await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
|
||||||
|
|
||||||
# assert page.total == 1
|
|
||||||
# assert page.elements[0].doi == "https://doi.org/10.7717/peerj.4375"
|
|
||||||
# assert page.elements[0].title == "Example work"
|
|
||||||
# assert page.elements[0].type == "article"
|
|
||||||
# assert page.elements[0].language == "en"
|
|
||||||
# assert page.elements[0].publication_year == 2023
|
|
||||||
# assert page.elements[0].cited_by_count == 42
|
|
||||||
# assert page.elements[0].topics == ["Machine learning"]
|
|
||||||
|
|
||||||
|
|
||||||
# @pytest.mark.anyio
|
class StubWorksSearchClient:
|
||||||
# async def test_get_all_author_works_collects_all_pages():
|
def __init__(self, pages: list[list[dict]], total: int):
|
||||||
# requested_pages = []
|
self.pages = pages
|
||||||
|
self.total = total
|
||||||
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
# def handler(request: httpx.Request) -> httpx.Response:
|
async def search_author_works(self, author_id, page, size, **filters):
|
||||||
# payload = json_from_request(request)
|
self.calls.append(
|
||||||
# requested_pages.append(payload["from"] // payload["size"] + 1)
|
{
|
||||||
# page = requested_pages[-1]
|
"author_id": author_id,
|
||||||
# hits = [
|
"page": page,
|
||||||
# {
|
"size": size,
|
||||||
# "_source": {
|
**filters,
|
||||||
# "id": f"https://openalex.org/W{page}",
|
}
|
||||||
# "doi": f"https://doi.org/10.1234/example-{page}",
|
)
|
||||||
# "title": f"Example work {page}",
|
hits = self.pages[page - 1] if page <= len(self.pages) else []
|
||||||
# "display_name": f"Example work {page}",
|
return {"hits": {"total": {"value": self.total}, "hits": hits}}
|
||||||
# "type": "article",
|
|
||||||
# "language": "en",
|
|
||||||
# "publication_year": 2024,
|
|
||||||
# "publication_date": "2024-01-01",
|
|
||||||
# "cited_by_count": page,
|
|
||||||
# "primary_location": {
|
|
||||||
# "is_oa": True,
|
|
||||||
# "source": {
|
|
||||||
# "id": "https://openalex.org/S123",
|
|
||||||
# "display_name": "Example Source",
|
|
||||||
# },
|
|
||||||
# },
|
|
||||||
# "authorships": [
|
|
||||||
# {
|
|
||||||
# "author": {
|
|
||||||
# "id": "https://openalex.org/A5023888391",
|
|
||||||
# "display_name": "Example Author",
|
|
||||||
# },
|
|
||||||
# },
|
|
||||||
# ],
|
|
||||||
# "topics": [],
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# ]
|
|
||||||
# return httpx.Response(
|
|
||||||
# 200,
|
|
||||||
# json={
|
|
||||||
# "hits": {
|
|
||||||
# "total": {"value": 2},
|
|
||||||
# "hits": hits,
|
|
||||||
# },
|
|
||||||
# },
|
|
||||||
# )
|
|
||||||
|
|
||||||
# client = OpenAlexWorksSearchClient(
|
|
||||||
# base_url="https://project.nes.uni-due.de/elastic",
|
|
||||||
# api_key="test-key",
|
|
||||||
# transport=httpx.MockTransport(handler),
|
|
||||||
# )
|
|
||||||
|
|
||||||
# works = await logic.get_all_author_works("A5023888391", client=client)
|
|
||||||
|
|
||||||
# assert requested_pages == [1, 2]
|
|
||||||
# assert works.total == 2
|
|
||||||
# assert [work.title for work in works.elements] == ["Example work 1", "Example work 2"]
|
|
||||||
# assert works.elements[0].id == "https://openalex.org/W1"
|
|
||||||
# assert works.elements[0].display_name == "Example work 1"
|
|
||||||
# assert works.elements[0].publication_date == "2024-01-01"
|
|
||||||
# assert works.elements[0].primary_location.is_oa is True
|
|
||||||
# assert works.elements[0].authorships[0].author.id == "https://openalex.org/A5023888391"
|
|
||||||
|
|
||||||
|
|
||||||
# @pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
# async def test_get_author_works_maps_missing_api_key_to_service_unavailable():
|
async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||||
# client = OpenAlexWorksSearchClient(api_key="")
|
client = StubWorksSearchClient(
|
||||||
|
pages=[[work_hit("W2741809807", "Example work")]],
|
||||||
|
total=1,
|
||||||
|
)
|
||||||
|
|
||||||
# with pytest.raises(HTTPException) as exc:
|
page = await logic.get_author_works(
|
||||||
# await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
"A5023888391",
|
||||||
|
page=1,
|
||||||
|
size=20,
|
||||||
|
publication_year=[2024],
|
||||||
|
client=client,
|
||||||
|
)
|
||||||
|
|
||||||
# assert exc.value.status_code == 503
|
assert page.total == 1
|
||||||
|
assert page.last_page is True
|
||||||
|
assert page.elements[0].title == "Example work"
|
||||||
|
assert page.elements[0].doi == "https://doi.org/10.1234/w2741809807"
|
||||||
|
assert client.calls[0]["publication_year"] == [2024]
|
||||||
|
|
||||||
|
|
||||||
# @pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
# async def test_get_author_works_maps_elasticsearch_errors_to_bad_gateway():
|
async def test_get_all_author_works_collects_all_elasticsearch_pages():
|
||||||
# def handler(request: httpx.Request) -> httpx.Response:
|
first_page = [work_hit(f"W{number}", f"Example work {number}") for number in range(100)]
|
||||||
# return httpx.Response(500, json={"error": "upstream failed"})
|
second_page = [work_hit("W100", "Example work 100")]
|
||||||
|
client = StubWorksSearchClient(pages=[first_page, second_page], total=101)
|
||||||
|
|
||||||
# client = OpenAlexWorksSearchClient(
|
response = await logic.get_all_author_works("A5023888391", client=client)
|
||||||
# base_url="https://project.nes.uni-due.de/elastic",
|
|
||||||
# api_key="test-key",
|
|
||||||
# transport=httpx.MockTransport(handler),
|
|
||||||
# )
|
|
||||||
|
|
||||||
# with pytest.raises(HTTPException) as exc:
|
assert response.meta.count == 101
|
||||||
# await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
assert len(response.results) == 101
|
||||||
|
assert response.results[-1].title == "Example work 100"
|
||||||
# assert exc.value.status_code == 502
|
assert [call["page"] for call in client.calls] == [1, 2]
|
||||||
|
|
||||||
|
|
||||||
# def json_from_request(request: httpx.Request) -> dict:
|
|
||||||
# return json.loads(request.content.decode("utf-8"))
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import json
|
import json
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from inse.exceptions import MissingApiKeyError
|
from inse.exceptions import MissingApiKeyError
|
||||||
|
|||||||
Generated
+68
-6
@@ -2,8 +2,10 @@ version = 1
|
|||||||
revision = 3
|
revision = 3
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
resolution-markers = [
|
resolution-markers = [
|
||||||
"sys_platform != 'darwin'",
|
"python_full_version >= '3.14' and 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'",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "certifi"
|
name = "certifi"
|
||||||
version = "2026.5.20"
|
version = "2026.5.20"
|
||||||
@@ -1083,6 +1128,7 @@ name = "service"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = { virtual = "." }
|
source = { virtual = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
{ name = "argon2-cffi" },
|
||||||
{ name = "cryptography" },
|
{ name = "cryptography" },
|
||||||
{ name = "dotenv" },
|
{ name = "dotenv" },
|
||||||
{ name = "fastapi" },
|
{ name = "fastapi" },
|
||||||
@@ -1095,7 +1141,7 @@ dependencies = [
|
|||||||
{ name = "python-multipart" },
|
{ name = "python-multipart" },
|
||||||
{ name = "pyyaml" },
|
{ name = "pyyaml" },
|
||||||
{ name = "sentence-transformers" },
|
{ 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", 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 = "torch", version = "2.12.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'darwin'" },
|
||||||
{ name = "uvicorn" },
|
{ name = "uvicorn" },
|
||||||
@@ -1103,6 +1149,7 @@ dependencies = [
|
|||||||
|
|
||||||
[package.metadata]
|
[package.metadata]
|
||||||
requires-dist = [
|
requires-dist = [
|
||||||
|
{ name = "argon2-cffi", specifier = "~=25.1.0" },
|
||||||
{ name = "cryptography", specifier = "~=42.0.0" },
|
{ name = "cryptography", specifier = "~=42.0.0" },
|
||||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||||
@@ -1115,7 +1162,7 @@ requires-dist = [
|
|||||||
{ name = "python-multipart", specifier = "~=0.0.19" },
|
{ name = "python-multipart", specifier = "~=0.0.19" },
|
||||||
{ name = "pyyaml", specifier = "~=6.0.1" },
|
{ name = "pyyaml", specifier = "~=6.0.1" },
|
||||||
{ name = "sentence-transformers", specifier = "~=5.5.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 = "torch", index = "https://download.pytorch.org/whl/cpu" },
|
||||||
{ name = "uvicorn", specifier = "~=0.29.0" },
|
{ name = "uvicorn", specifier = "~=0.29.0" },
|
||||||
]
|
]
|
||||||
@@ -1188,6 +1235,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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "starlette"
|
name = "starlette"
|
||||||
version = "0.46.2"
|
version = "0.46.2"
|
||||||
@@ -1252,7 +1312,8 @@ name = "torch"
|
|||||||
version = "2.12.0"
|
version = "2.12.0"
|
||||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||||
resolution-markers = [
|
resolution-markers = [
|
||||||
"sys_platform == 'darwin'",
|
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||||
|
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||||
]
|
]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "filelock", marker = "sys_platform == 'darwin'" },
|
{ name = "filelock", marker = "sys_platform == 'darwin'" },
|
||||||
@@ -1276,7 +1337,8 @@ name = "torch"
|
|||||||
version = "2.12.0+cpu"
|
version = "2.12.0+cpu"
|
||||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||||
resolution-markers = [
|
resolution-markers = [
|
||||||
"sys_platform != 'darwin'",
|
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||||
|
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||||
]
|
]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "filelock", marker = "sys_platform != 'darwin'" },
|
{ name = "filelock", marker = "sys_platform != 'darwin'" },
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
"start": "ng serve",
|
"start": "ng serve --proxy-config src/proxy.conf.json",
|
||||||
"build": "ng build",
|
"build": "ng build",
|
||||||
"generate:api": "openapi-generator-cli generate --generator-key inse-service",
|
"generate:api": "openapi-generator-cli generate --generator-key inse-service",
|
||||||
"watch": "ng build --watch --configuration development",
|
"watch": "ng build --watch --configuration development",
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ README.md
|
|||||||
api.base.service.ts
|
api.base.service.ts
|
||||||
api.module.ts
|
api.module.ts
|
||||||
api/api.ts
|
api/api.ts
|
||||||
|
api/auth.service.ts
|
||||||
api/companyConnections.service.ts
|
api/companyConnections.service.ts
|
||||||
api/funding.service.ts
|
api/funding.service.ts
|
||||||
api/iNSEAccountService.service.ts
|
|
||||||
api/iNSEService.service.ts
|
api/iNSEService.service.ts
|
||||||
api/institutions.service.ts
|
api/institutions.service.ts
|
||||||
api/items.service.ts
|
|
||||||
api/news.service.ts
|
api/news.service.ts
|
||||||
|
api/organization.service.ts
|
||||||
api/patents.service.ts
|
api/patents.service.ts
|
||||||
api/personNetwork.service.ts
|
api/personNetwork.service.ts
|
||||||
api/persons.service.ts
|
api/persons.service.ts
|
||||||
@@ -21,10 +21,11 @@ configuration.ts
|
|||||||
encoder.ts
|
encoder.ts
|
||||||
git_push.sh
|
git_push.sh
|
||||||
index.ts
|
index.ts
|
||||||
model/accessGrant.ts
|
model/accessResponse.ts
|
||||||
|
model/accessToken.ts
|
||||||
|
model/accountPage.ts
|
||||||
|
model/accountProfile.ts
|
||||||
model/allPatentsResponse.ts
|
model/allPatentsResponse.ts
|
||||||
model/authAccount.ts
|
|
||||||
model/authScope.ts
|
|
||||||
model/author.ts
|
model/author.ts
|
||||||
model/authorAffiliationsInner.ts
|
model/authorAffiliationsInner.ts
|
||||||
model/authorCountsByYearInner.ts
|
model/authorCountsByYearInner.ts
|
||||||
@@ -40,7 +41,10 @@ model/autocompleteResponse.ts
|
|||||||
model/autocompleteResponseMeta.ts
|
model/autocompleteResponseMeta.ts
|
||||||
model/autocompleteResponseResultsInner.ts
|
model/autocompleteResponseResultsInner.ts
|
||||||
model/award.ts
|
model/award.ts
|
||||||
model/bodyCreateUser.ts
|
model/bodyChangePassword.ts
|
||||||
|
model/bodyGetAccessToken.ts
|
||||||
|
model/bodyLogin.ts
|
||||||
|
model/bodyRequestOtk.ts
|
||||||
model/bundProject.ts
|
model/bundProject.ts
|
||||||
model/bundProjectDetails.ts
|
model/bundProjectDetails.ts
|
||||||
model/bundProjectPage.ts
|
model/bundProjectPage.ts
|
||||||
@@ -53,6 +57,8 @@ model/companyConnectionsResponse.ts
|
|||||||
model/cordisEuProject.ts
|
model/cordisEuProject.ts
|
||||||
model/cordisEuProjectPage.ts
|
model/cordisEuProjectPage.ts
|
||||||
model/costUsd.ts
|
model/costUsd.ts
|
||||||
|
model/createAccountRequest.ts
|
||||||
|
model/createOrganizationRequest.ts
|
||||||
model/customAuthor.ts
|
model/customAuthor.ts
|
||||||
model/customAuthorsListResponse.ts
|
model/customAuthorsListResponse.ts
|
||||||
model/dehydratedAuthor.ts
|
model/dehydratedAuthor.ts
|
||||||
@@ -103,7 +109,9 @@ model/hEUReportSummary.ts
|
|||||||
model/hEUTopic.ts
|
model/hEUTopic.ts
|
||||||
model/hEUWebLink.ts
|
model/hEUWebLink.ts
|
||||||
model/hTTPValidationError.ts
|
model/hTTPValidationError.ts
|
||||||
model/identityGrant.ts
|
model/idToken.ts
|
||||||
|
model/inseAccountManagementModelOrganizationProfile.ts
|
||||||
|
model/inseOrganizationManagementModelOrganizationProfile.ts
|
||||||
model/institution.ts
|
model/institution.ts
|
||||||
model/institutionFunderSummary.ts
|
model/institutionFunderSummary.ts
|
||||||
model/institutionGeo.ts
|
model/institutionGeo.ts
|
||||||
@@ -113,12 +121,10 @@ model/institutionNetworkNode.ts
|
|||||||
model/institutionPage.ts
|
model/institutionPage.ts
|
||||||
model/institutionsListResponse.ts
|
model/institutionsListResponse.ts
|
||||||
model/ipcClassification.ts
|
model/ipcClassification.ts
|
||||||
model/item.ts
|
|
||||||
model/itemCreate.ts
|
|
||||||
model/itemPage.ts
|
|
||||||
model/keywords.ts
|
model/keywords.ts
|
||||||
model/latitude.ts
|
model/latitude.ts
|
||||||
model/location.ts
|
model/location.ts
|
||||||
|
model/loginResponse.ts
|
||||||
model/longitude.ts
|
model/longitude.ts
|
||||||
model/matchedOfficer.ts
|
model/matchedOfficer.ts
|
||||||
model/mentionedPerson.ts
|
model/mentionedPerson.ts
|
||||||
@@ -129,6 +135,7 @@ model/newsArticle.ts
|
|||||||
model/newsArticleDetail.ts
|
model/newsArticleDetail.ts
|
||||||
model/newsPage.ts
|
model/newsPage.ts
|
||||||
model/openAccess.ts
|
model/openAccess.ts
|
||||||
|
model/organizationPage.ts
|
||||||
model/patentEntry.ts
|
model/patentEntry.ts
|
||||||
model/patentsByAuthorResponse.ts
|
model/patentsByAuthorResponse.ts
|
||||||
model/personBio.ts
|
model/personBio.ts
|
||||||
@@ -139,8 +146,10 @@ model/publicationDetailByFunder.ts
|
|||||||
model/publicationIdsByAuthorPosition.ts
|
model/publicationIdsByAuthorPosition.ts
|
||||||
model/publicationsByAuthorResponse.ts
|
model/publicationsByAuthorResponse.ts
|
||||||
model/rankingResponse.ts
|
model/rankingResponse.ts
|
||||||
|
model/refreshToken.ts
|
||||||
model/score.ts
|
model/score.ts
|
||||||
model/sortDirection.ts
|
model/sortDirection.ts
|
||||||
|
model/tokenType.ts
|
||||||
model/topic.ts
|
model/topic.ts
|
||||||
model/topicCount.ts
|
model/topicCount.ts
|
||||||
model/topicDomain.ts
|
model/topicDomain.ts
|
||||||
@@ -153,7 +162,9 @@ model/topicsByYear.ts
|
|||||||
model/topicsListResponse.ts
|
model/topicsListResponse.ts
|
||||||
model/universityRanking.ts
|
model/universityRanking.ts
|
||||||
model/universityTopicData.ts
|
model/universityTopicData.ts
|
||||||
model/user.ts
|
model/updateAccountRequest.ts
|
||||||
|
model/updateOrganizationRequest.ts
|
||||||
|
model/userRole.ts
|
||||||
model/validationError.ts
|
model/validationError.ts
|
||||||
model/validationErrorLocInner.ts
|
model/validationErrorLocInner.ts
|
||||||
model/value.ts
|
model/value.ts
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ In your project:
|
|||||||
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 <https://github.com/angular/angular-cli/issues/8284> for a solution / workaround.
|
Please refer to this issue <https://github.com/angular/angular-cli/issues/8284> for a solution / workaround.
|
||||||
Published packages are not effected by this issue.
|
Published packages are not effected by this issue.
|
||||||
|
|
||||||
@@ -58,22 +58,22 @@ Published packages are not effected by this issue.
|
|||||||
In your Angular project:
|
In your Angular project:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
|
||||||
import { ApplicationConfig } from '@angular/core';
|
import { ApplicationConfig } from '@angular/core';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { provideApi } from '';
|
import { provideApi } from '';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
// ...
|
// ...
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
provideApi(),
|
provideApi()
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
**NOTE**
|
**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:
|
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
|
```typescript
|
||||||
import { ApiModule } from '';
|
import { ApiModule } from '';
|
||||||
```
|
```
|
||||||
@@ -86,11 +86,11 @@ import { provideHttpClient } from '@angular/common/http';
|
|||||||
import { provideApi } from '';
|
import { provideApi } from '';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
// ...
|
// ...
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
provideApi('http://localhost:9999'),
|
provideApi('http://localhost:9999')
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -101,15 +101,15 @@ import { provideHttpClient } from '@angular/common/http';
|
|||||||
import { provideApi } from '';
|
import { provideApi } from '';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
// ...
|
// ...
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
provideApi({
|
provideApi({
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
username: 'user',
|
username: 'user',
|
||||||
password: 'password',
|
password: 'password'
|
||||||
}),
|
})
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -120,22 +120,21 @@ import { provideHttpClient } from '@angular/common/http';
|
|||||||
import { provideApi, Configuration } from '';
|
import { provideApi, Configuration } from '';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
// ...
|
// ...
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
{
|
{
|
||||||
provide: Configuration,
|
provide: Configuration,
|
||||||
useFactory: (authService: AuthService) =>
|
useFactory: (authService: AuthService) => new Configuration({
|
||||||
new Configuration({
|
basePath: 'http://localhost:9999',
|
||||||
basePath: 'http://localhost:9999',
|
withCredentials: true,
|
||||||
withCredentials: true,
|
username: authService.getUsername(),
|
||||||
username: authService.getUsername(),
|
password: authService.getPassword(),
|
||||||
password: authService.getPassword(),
|
}),
|
||||||
}),
|
deps: [AuthService],
|
||||||
deps: [AuthService],
|
multi: false
|
||||||
multi: false,
|
}
|
||||||
},
|
],
|
||||||
],
|
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -152,12 +151,12 @@ import { HttpClientModule } from '@angular/common/http';
|
|||||||
import { environment } from '../environments/environment';
|
import { environment } from '../environments/environment';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
// ...
|
// ...
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
provideUserApi(environment.basePath),
|
provideUserApi(environment.basePath),
|
||||||
provideAdminApi(environment.basePath),
|
provideAdminApi(environment.basePath),
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -177,8 +176,8 @@ Example value for use in your Configuration-Provider:
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
new Configuration({
|
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
|
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
|
||||||
|
|||||||
@@ -7,103 +7,77 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
import {
|
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
|
||||||
HttpHeaders,
|
|
||||||
HttpParams,
|
|
||||||
HttpParameterCodec,
|
|
||||||
} from '@angular/common/http';
|
|
||||||
import { CustomHttpParameterCodec } from './encoder';
|
import { CustomHttpParameterCodec } from './encoder';
|
||||||
import { Configuration } from './configuration';
|
import { Configuration } from './configuration';
|
||||||
|
|
||||||
export class BaseService {
|
export class BaseService {
|
||||||
protected basePath = 'http://localhost:8000';
|
protected basePath = 'http://localhost:8000';
|
||||||
public defaultHeaders = new HttpHeaders();
|
public defaultHeaders = new HttpHeaders();
|
||||||
public configuration: Configuration;
|
public configuration: Configuration;
|
||||||
public encoder: HttpParameterCodec;
|
public encoder: HttpParameterCodec;
|
||||||
|
|
||||||
constructor(basePath?: string | string[], configuration?: Configuration) {
|
constructor(basePath?: string|string[], configuration?: Configuration) {
|
||||||
this.configuration = configuration || new Configuration();
|
this.configuration = configuration || new Configuration();
|
||||||
if (typeof this.configuration.basePath !== 'string') {
|
if (typeof this.configuration.basePath !== 'string') {
|
||||||
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
|
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
|
||||||
if (firstBasePath != undefined) {
|
if (firstBasePath != undefined) {
|
||||||
basePath = firstBasePath;
|
basePath = firstBasePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof basePath !== 'string') {
|
if (typeof basePath !== 'string') {
|
||||||
basePath = this.basePath;
|
basePath = this.basePath;
|
||||||
}
|
}
|
||||||
this.configuration.basePath = 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<string, any>).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 {
|
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
|
||||||
Object.keys(value).forEach((k) => {
|
}
|
||||||
const paramKey = key ? `${key}.${k}` : k;
|
|
||||||
httpParams = this.addToHttpParamsRecursive(
|
protected canConsumeForm(consumes: string[]): boolean {
|
||||||
httpParams,
|
return consumes.indexOf('multipart/form-data') !== -1;
|
||||||
value[k],
|
}
|
||||||
paramKey,
|
|
||||||
);
|
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 httpParams;
|
return this.addToHttpParamsRecursive(httpParams, value, isDeep ? key : undefined, isDeep);
|
||||||
} else if (key != null) {
|
}
|
||||||
return httpParams.append(key, value);
|
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<string, any>).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');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,30 @@
|
|||||||
import {
|
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
|
||||||
NgModule,
|
|
||||||
ModuleWithProviders,
|
|
||||||
SkipSelf,
|
|
||||||
Optional,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { Configuration } from './configuration';
|
import { Configuration } from './configuration';
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
|
||||||
|
|
||||||
@NgModule({
|
@NgModule({
|
||||||
imports: [],
|
imports: [],
|
||||||
declarations: [],
|
declarations: [],
|
||||||
exports: [],
|
exports: [],
|
||||||
providers: [],
|
providers: []
|
||||||
})
|
})
|
||||||
export class ApiModule {
|
export class ApiModule {
|
||||||
public static forRoot(
|
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
|
||||||
configurationFactory: () => Configuration,
|
return {
|
||||||
): ModuleWithProviders<ApiModule> {
|
ngModule: ApiModule,
|
||||||
return {
|
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
|
||||||
ngModule: ApiModule,
|
};
|
||||||
providers: [{ provide: Configuration, useFactory: configurationFactory }],
|
}
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(
|
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
|
||||||
@Optional() @SkipSelf() parentModule: ApiModule,
|
@Optional() http: HttpClient) {
|
||||||
@Optional() http: HttpClient,
|
if (parentModule) {
|
||||||
) {
|
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
|
||||||
if (parentModule) {
|
}
|
||||||
throw new Error(
|
if (!http) {
|
||||||
'ApiModule is already loaded. Import in your base AppModule only.',
|
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',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
|
export * from './auth.service';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
export * from './companyConnections.service';
|
export * from './companyConnections.service';
|
||||||
import { CompanyConnectionsService } from './companyConnections.service';
|
import { CompanyConnectionsService } from './companyConnections.service';
|
||||||
export * from './funding.service';
|
export * from './funding.service';
|
||||||
import { FundingService } from './funding.service';
|
import { FundingService } from './funding.service';
|
||||||
export * from './iNSEAccountService.service';
|
|
||||||
import { INSEAccountServiceService } from './iNSEAccountService.service';
|
|
||||||
export * from './iNSEService.service';
|
export * from './iNSEService.service';
|
||||||
import { INSEServiceService } from './iNSEService.service';
|
import { INSEServiceService } from './iNSEService.service';
|
||||||
export * from './institutions.service';
|
export * from './institutions.service';
|
||||||
import { InstitutionsService } from './institutions.service';
|
import { InstitutionsService } from './institutions.service';
|
||||||
export * from './items.service';
|
|
||||||
import { ItemsService } from './items.service';
|
|
||||||
export * from './news.service';
|
export * from './news.service';
|
||||||
import { NewsService } from './news.service';
|
import { NewsService } from './news.service';
|
||||||
|
export * from './organization.service';
|
||||||
|
import { OrganizationService } from './organization.service';
|
||||||
export * from './patents.service';
|
export * from './patents.service';
|
||||||
import { PatentsService } from './patents.service';
|
import { PatentsService } from './patents.service';
|
||||||
export * from './personNetwork.service';
|
export * from './personNetwork.service';
|
||||||
@@ -24,18 +24,4 @@ export * from './topics.service';
|
|||||||
import { TopicsService } from './topics.service';
|
import { TopicsService } from './topics.service';
|
||||||
export * from './works.service';
|
export * from './works.service';
|
||||||
import { WorksService } from './works.service';
|
import { WorksService } from './works.service';
|
||||||
export const APIS = [
|
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||||
CompanyConnectionsService,
|
|
||||||
FundingService,
|
|
||||||
INSEAccountServiceService,
|
|
||||||
INSEServiceService,
|
|
||||||
InstitutionsService,
|
|
||||||
ItemsService,
|
|
||||||
NewsService,
|
|
||||||
PatentsService,
|
|
||||||
PersonNetworkService,
|
|
||||||
PersonsService,
|
|
||||||
ProjectsService,
|
|
||||||
TopicsService,
|
|
||||||
WorksService,
|
|
||||||
];
|
|
||||||
|
|||||||
@@ -0,0 +1,871 @@
|
|||||||
|
/**
|
||||||
|
* Innovation Search Engine API
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||||
|
* https://openapi-generator.tech
|
||||||
|
* Do not edit the class manually.
|
||||||
|
*/
|
||||||
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccessResponse } from '../model/accessResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccessToken } from '../model/accessToken';
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccountPage } from '../model/accountPage';
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccountProfile } from '../model/accountProfile';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyChangePassword } from '../model/bodyChangePassword';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyGetAccessToken } from '../model/bodyGetAccessToken';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyLogin } from '../model/bodyLogin';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||||
|
// @ts-ignore
|
||||||
|
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||||
|
// @ts-ignore
|
||||||
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
// @ts-ignore
|
||||||
|
import { LoginResponse } from '../model/loginResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { OrganizationProfile } from '../model/organizationProfile';
|
||||||
|
// @ts-ignore
|
||||||
|
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
|
import { Configuration } from '../configuration';
|
||||||
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class AuthService extends BaseService {
|
||||||
|
|
||||||
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
|
super(basePath, configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change Password
|
||||||
|
* Change the user\'s password and invalidate existing tokens.
|
||||||
|
* @endpoint post /api/auth/v2/change-password
|
||||||
|
* @param bodyChangePassword
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyChangePassword,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create Account
|
||||||
|
* @endpoint post /api/accounts
|
||||||
|
* @param createAccountRequest
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<AccountProfile>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: createAccountRequest,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<any>('delete', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get Access Token
|
||||||
|
* Retrieve an access token for the authenticated user.
|
||||||
|
* @endpoint post /api/auth/v2/access
|
||||||
|
* @param bodyGetAccessToken
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
||||||
|
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/access`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<AccessResponse>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyGetAccessToken,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get Current Account
|
||||||
|
* @endpoint get /api/accounts/me
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
|
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
|
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
|
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<AccountProfile>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/health`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List Organizations
|
||||||
|
* @endpoint get /api/accounts/organizations
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<OrganizationProfile>>;
|
||||||
|
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<OrganizationProfile>>>;
|
||||||
|
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<OrganizationProfile>>>;
|
||||||
|
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
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<Array<OrganizationProfile>>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<AccountPage>;
|
||||||
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||||
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||||
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>page, 'page');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>pageSize, 'page_size');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>offset, 'offset');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>search, 'search');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>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<AccountPage>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>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<LoginResponse>;
|
||||||
|
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<LoginResponse>>;
|
||||||
|
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<LoginResponse>>;
|
||||||
|
public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<LoginResponse>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyLogin,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<AccessToken>;
|
||||||
|
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||||
|
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||||
|
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<AccessToken>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||||
|
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||||
|
}
|
||||||
|
|
||||||
|
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<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyRequestOtk,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update Account
|
||||||
|
* @endpoint put /api/accounts/{account_id}
|
||||||
|
* @param accountId
|
||||||
|
* @param updateAccountRequest
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<AccountProfile>('put', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: updateAccountRequest,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,871 @@
|
|||||||
|
/**
|
||||||
|
* Innovation Search Engine API
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||||
|
* https://openapi-generator.tech
|
||||||
|
* Do not edit the class manually.
|
||||||
|
*/
|
||||||
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccessResponse } from '../model/accessResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccessToken } from '../model/accessToken';
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccountPage } from '../model/accountPage';
|
||||||
|
// @ts-ignore
|
||||||
|
import { AccountProfile } from '../model/accountProfile';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyChangePassword } from '../model/bodyChangePassword';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyGetAccessToken } from '../model/bodyGetAccessToken';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyLogin } from '../model/bodyLogin';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||||
|
// @ts-ignore
|
||||||
|
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||||
|
// @ts-ignore
|
||||||
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
// @ts-ignore
|
||||||
|
import { InseAccountManagementModelOrganizationProfile } from '../model/inseAccountManagementModelOrganizationProfile';
|
||||||
|
// @ts-ignore
|
||||||
|
import { LoginResponse } from '../model/loginResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
|
import { Configuration } from '../configuration';
|
||||||
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class AuthService extends BaseService {
|
||||||
|
|
||||||
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
|
super(basePath, configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change Password
|
||||||
|
* Change the user\'s password and invalidate existing tokens.
|
||||||
|
* @endpoint post /api/auth/v2/change-password
|
||||||
|
* @param bodyChangePassword
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyChangePassword,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create Account
|
||||||
|
* @endpoint post /api/accounts
|
||||||
|
* @param createAccountRequest
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
|
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<AccountProfile>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: createAccountRequest,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<any>('delete', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get Access Token
|
||||||
|
* Retrieve an access token for the authenticated user.
|
||||||
|
* @endpoint post /api/auth/v2/access
|
||||||
|
* @param bodyGetAccessToken
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||||
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
||||||
|
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/access`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<AccessResponse>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyGetAccessToken,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get Current Account
|
||||||
|
* @endpoint get /api/accounts/me
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
|
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
|
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
|
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<AccountProfile>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/health`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List Organizations
|
||||||
|
* @endpoint get /api/accounts/organizations
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
|
||||||
|
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||||
|
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||||
|
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<Array<InseAccountManagementModelOrganizationProfile>>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<AccountPage>;
|
||||||
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||||
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||||
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>page, 'page');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>pageSize, 'page_size');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>offset, 'offset');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>search, 'search');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>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<AccountPage>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>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<LoginResponse>;
|
||||||
|
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<LoginResponse>>;
|
||||||
|
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<LoginResponse>>;
|
||||||
|
public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<LoginResponse>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyLogin,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<AccessToken>;
|
||||||
|
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||||
|
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||||
|
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
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<AccessToken>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||||
|
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||||
|
}
|
||||||
|
|
||||||
|
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<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyRequestOtk,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update Account
|
||||||
|
* @endpoint put /api/accounts/{account_id}
|
||||||
|
* @param accountId
|
||||||
|
* @param updateAccountRequest
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<AccountProfile>('put', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: updateAccountRequest,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -9,18 +9,12 @@
|
|||||||
*/
|
*/
|
||||||
/* tslint:disable:no-unused-variable member-ordering */
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
import { Inject, Injectable, Optional } from '@angular/core';
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
import {
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
HttpClient,
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
HttpHeaders,
|
} from '@angular/common/http';
|
||||||
HttpParams,
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
HttpResponse,
|
import { Observable } from 'rxjs';
|
||||||
HttpEvent,
|
|
||||||
HttpParameterCodec,
|
|
||||||
HttpContext,
|
|
||||||
} from '@angular/common/http';
|
|
||||||
import { CustomHttpParameterCodec } from '../encoder';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse';
|
import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse';
|
||||||
@@ -28,121 +22,74 @@ import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'
|
|||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
import { Configuration } from '../configuration';
|
import { Configuration } from '../configuration';
|
||||||
import { BaseService } from '../api.base.service';
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class CompanyConnectionsService extends BaseService {
|
export class CompanyConnectionsService extends BaseService {
|
||||||
constructor(
|
|
||||||
protected httpClient: HttpClient,
|
|
||||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
|
||||||
@Optional() configuration?: Configuration,
|
|
||||||
) {
|
|
||||||
super(basePath, configuration);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
* Get possible company connections by OpenAlex author ID.
|
super(basePath, configuration);
|
||||||
* @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<CompanyConnectionsResponse>;
|
|
||||||
public getCompanyConnectionsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<CompanyConnectionsResponse>>;
|
|
||||||
public getCompanyConnectionsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<CompanyConnectionsResponse>>;
|
|
||||||
public getCompanyConnectionsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (authorId === null || authorId === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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<CompanyConnectionsResponse>;
|
||||||
|
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CompanyConnectionsResponse>>;
|
||||||
|
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CompanyConnectionsResponse>>;
|
||||||
|
public getCompanyConnectionsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (authorId === null || authorId === undefined) {
|
||||||
|
throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.');
|
||||||
|
}
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
let localVarHeaders = this.defaultHeaders;
|
||||||
options?.httpHeaderAccept ??
|
|
||||||
this.configuration.selectHeaderAccept(['application/json']);
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
'application/json'
|
||||||
localVarHeaders = localVarHeaders.set(
|
]);
|
||||||
'Accept',
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
localVarHttpHeaderAcceptSelected,
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
);
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/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<CompanyConnectionsResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<CompanyConnectionsResponse>(
|
|
||||||
'get',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,18 +9,12 @@
|
|||||||
*/
|
*/
|
||||||
/* tslint:disable:no-unused-variable member-ordering */
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
import { Inject, Injectable, Optional } from '@angular/core';
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
import {
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
HttpClient,
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
HttpHeaders,
|
} from '@angular/common/http';
|
||||||
HttpParams,
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
HttpResponse,
|
import { Observable } from 'rxjs';
|
||||||
HttpEvent,
|
|
||||||
HttpParameterCodec,
|
|
||||||
HttpContext,
|
|
||||||
} from '@angular/common/http';
|
|
||||||
import { CustomHttpParameterCodec } from '../encoder';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse';
|
import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse';
|
||||||
@@ -30,246 +24,138 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
|||||||
import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse';
|
import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
import { Configuration } from '../configuration';
|
import { Configuration } from '../configuration';
|
||||||
import { BaseService } from '../api.base.service';
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class FundingService extends BaseService {
|
export class FundingService extends BaseService {
|
||||||
constructor(
|
|
||||||
protected httpClient: HttpClient,
|
|
||||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
|
||||||
@Optional() configuration?: Configuration,
|
|
||||||
) {
|
|
||||||
super(basePath, configuration);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
* Get funding organizations by author.
|
super(basePath, configuration);
|
||||||
* @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<FundersByAuthorResponse>;
|
|
||||||
public getFundersByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<FundersByAuthorResponse>>;
|
|
||||||
public getFundersByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<FundersByAuthorResponse>>;
|
|
||||||
public getFundersByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (authorId === null || authorId === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter authorId was null or undefined when calling getFundersByAuthor.',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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<FundersByAuthorResponse>;
|
||||||
|
public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<FundersByAuthorResponse>>;
|
||||||
|
public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<FundersByAuthorResponse>>;
|
||||||
|
public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (authorId === null || authorId === undefined) {
|
||||||
|
throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.');
|
||||||
|
}
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
let localVarHeaders = this.defaultHeaders;
|
||||||
options?.httpHeaderAccept ??
|
|
||||||
this.configuration.selectHeaderAccept(['application/json']);
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
'application/json'
|
||||||
localVarHeaders = localVarHeaders.set(
|
]);
|
||||||
'Accept',
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
localVarHttpHeaderAcceptSelected,
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
);
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/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<FundersByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<PublicationsByAuthorResponse>;
|
||||||
|
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PublicationsByAuthorResponse>>;
|
||||||
|
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PublicationsByAuthorResponse>>;
|
||||||
|
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (authorId === null || authorId === undefined) {
|
||||||
|
throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.');
|
||||||
|
}
|
||||||
|
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>page, 'page');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>pageSize, 'page_size');
|
||||||
|
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
let localVarHeaders = this.defaultHeaders;
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
responseType_ = 'text';
|
'application/json'
|
||||||
} else if (
|
]);
|
||||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
) {
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
responseType_ = 'json';
|
}
|
||||||
} else {
|
|
||||||
responseType_ = 'blob';
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
}
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/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<PublicationsByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarPath = `/api/inse-service/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<FundersByAuthorResponse>(
|
|
||||||
'get',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
responseType: <any>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<PublicationsByAuthorResponse>;
|
|
||||||
public getPublicationsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
page?: number,
|
|
||||||
pageSize?: number,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<PublicationsByAuthorResponse>>;
|
|
||||||
public getPublicationsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
page?: number,
|
|
||||||
pageSize?: number,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<PublicationsByAuthorResponse>>;
|
|
||||||
public getPublicationsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
page?: number,
|
|
||||||
pageSize?: number,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (authorId === null || authorId === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter authorId was null or undefined when calling getPublicationsByAuthor.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>page,
|
|
||||||
'page',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>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<PublicationsByAuthorResponse>(
|
|
||||||
'get',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
params: localVarQueryParameters,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,457 +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<User>;
|
|
||||||
public createUser(
|
|
||||||
bodyCreateUser: BodyCreateUser,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<User>>;
|
|
||||||
public createUser(
|
|
||||||
bodyCreateUser: BodyCreateUser,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<User>>;
|
|
||||||
public createUser(
|
|
||||||
bodyCreateUser: BodyCreateUser,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
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<User>('post', `${basePath}${localVarPath}`, {
|
|
||||||
context: localVarHttpContext,
|
|
||||||
body: bodyCreateUser,
|
|
||||||
responseType: <any>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<AccessGrant>;
|
|
||||||
public getAccessGrant(
|
|
||||||
secret: string,
|
|
||||||
account: number,
|
|
||||||
organization: number,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<AccessGrant>>;
|
|
||||||
public getAccessGrant(
|
|
||||||
secret: string,
|
|
||||||
account: number,
|
|
||||||
organization: number,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<AccessGrant>>;
|
|
||||||
public getAccessGrant(
|
|
||||||
secret: string,
|
|
||||||
account: number,
|
|
||||||
organization: number,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
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', <any>secret) as any) ||
|
|
||||||
localVarFormParams;
|
|
||||||
}
|
|
||||||
if (account !== undefined) {
|
|
||||||
localVarFormParams =
|
|
||||||
(localVarFormParams.append('account', <any>account) as any) ||
|
|
||||||
localVarFormParams;
|
|
||||||
}
|
|
||||||
if (organization !== undefined) {
|
|
||||||
localVarFormParams =
|
|
||||||
(localVarFormParams.append('organization', <any>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<AccessGrant>(
|
|
||||||
'post',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
body: localVarConvertFormParamsToString
|
|
||||||
? localVarFormParams.toString()
|
|
||||||
: localVarFormParams,
|
|
||||||
responseType: <any>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<IdentityGrant>;
|
|
||||||
public getIdentityGrant(
|
|
||||||
username: string,
|
|
||||||
password: string,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<IdentityGrant>>;
|
|
||||||
public getIdentityGrant(
|
|
||||||
username: string,
|
|
||||||
password: string,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<IdentityGrant>>;
|
|
||||||
public getIdentityGrant(
|
|
||||||
username: string,
|
|
||||||
password: string,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
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', <any>username) as any) ||
|
|
||||||
localVarFormParams;
|
|
||||||
}
|
|
||||||
if (password !== undefined) {
|
|
||||||
localVarFormParams =
|
|
||||||
(localVarFormParams.append('password', <any>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<IdentityGrant>(
|
|
||||||
'post',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
body: localVarConvertFormParamsToString
|
|
||||||
? localVarFormParams.toString()
|
|
||||||
: localVarFormParams,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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<Item>;
|
|
||||||
public addItem(
|
|
||||||
itemCreate: ItemCreate,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<Item>>;
|
|
||||||
public addItem(
|
|
||||||
itemCreate: ItemCreate,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<Item>>;
|
|
||||||
public addItem(
|
|
||||||
itemCreate: ItemCreate,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
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<Item>('post', `${basePath}${localVarPath}`, {
|
|
||||||
context: localVarHttpContext,
|
|
||||||
body: itemCreate,
|
|
||||||
responseType: <any>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<any>;
|
|
||||||
public deleteItem(
|
|
||||||
id: number,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<any>>;
|
|
||||||
public deleteItem(
|
|
||||||
id: number,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<any>>;
|
|
||||||
public deleteItem(
|
|
||||||
id: number,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (id === null || id === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter id was null or undefined when calling 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<any>(
|
|
||||||
'delete',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
responseType: <any>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<Item>;
|
|
||||||
public getItem(
|
|
||||||
id: number,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<Item>>;
|
|
||||||
public getItem(
|
|
||||||
id: number,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<Item>>;
|
|
||||||
public getItem(
|
|
||||||
id: number,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (id === null || id === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter id was null or undefined when calling 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<Item>('get', `${basePath}${localVarPath}`, {
|
|
||||||
context: localVarHttpContext,
|
|
||||||
responseType: <any>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<ItemPage>;
|
|
||||||
public getItems(
|
|
||||||
pageOffset?: number,
|
|
||||||
pageSize?: number,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<ItemPage>>;
|
|
||||||
public getItems(
|
|
||||||
pageOffset?: number,
|
|
||||||
pageSize?: number,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<ItemPage>>;
|
|
||||||
public getItems(
|
|
||||||
pageOffset?: number,
|
|
||||||
pageSize?: number,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>pageOffset,
|
|
||||||
'pageOffset',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>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<ItemPage>(
|
|
||||||
'get',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
params: localVarQueryParameters,
|
|
||||||
responseType: <any>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<Item>;
|
|
||||||
public updateItem(
|
|
||||||
id: number,
|
|
||||||
itemCreate: ItemCreate,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<Item>>;
|
|
||||||
public updateItem(
|
|
||||||
id: number,
|
|
||||||
itemCreate: ItemCreate,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<Item>>;
|
|
||||||
public updateItem(
|
|
||||||
id: number,
|
|
||||||
itemCreate: ItemCreate,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (id === null || id === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter id was null or undefined when calling 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<Item>('put', `${basePath}${localVarPath}`, {
|
|
||||||
context: localVarHttpContext,
|
|
||||||
body: itemCreate,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+532
-1002
File diff suppressed because it is too large
Load Diff
@@ -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<InseOrganizationManagementModelOrganizationProfile>;
|
||||||
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<InseOrganizationManagementModelOrganizationProfile>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: createOrganizationRequest,
|
||||||
|
responseType: <any>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<any>;
|
||||||
|
public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<any>('delete', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>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<OrganizationPage>;
|
||||||
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
||||||
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
||||||
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>page, 'page');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>pageSize, 'page_size');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>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<OrganizationPage>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>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<InseOrganizationManagementModelOrganizationProfile>;
|
||||||
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
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<InseOrganizationManagementModelOrganizationProfile>('put', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: updateOrganizationRequest,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -9,18 +9,12 @@
|
|||||||
*/
|
*/
|
||||||
/* tslint:disable:no-unused-variable member-ordering */
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
import { Inject, Injectable, Optional } from '@angular/core';
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
import {
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
HttpClient,
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
HttpHeaders,
|
} from '@angular/common/http';
|
||||||
HttpParams,
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
HttpResponse,
|
import { Observable } from 'rxjs';
|
||||||
HttpEvent,
|
|
||||||
HttpParameterCodec,
|
|
||||||
HttpContext,
|
|
||||||
} from '@angular/common/http';
|
|
||||||
import { CustomHttpParameterCodec } from '../encoder';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { AllPatentsResponse } from '../model/allPatentsResponse';
|
import { AllPatentsResponse } from '../model/allPatentsResponse';
|
||||||
@@ -32,400 +26,210 @@ import { PatentEntry } from '../model/patentEntry';
|
|||||||
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
import { Configuration } from '../configuration';
|
import { Configuration } from '../configuration';
|
||||||
import { BaseService } from '../api.base.service';
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class PatentsService extends BaseService {
|
export class PatentsService extends BaseService {
|
||||||
constructor(
|
|
||||||
protected httpClient: HttpClient,
|
|
||||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
|
||||||
@Optional() configuration?: Configuration,
|
|
||||||
) {
|
|
||||||
super(basePath, configuration);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
* Get all patents with pagination and search.
|
super(basePath, configuration);
|
||||||
* @endpoint get /api/inse-service/patents
|
|
||||||
* @param page
|
|
||||||
* @param size
|
|
||||||
* @param search
|
|
||||||
* @param source
|
|
||||||
* @param sortBy
|
|
||||||
* @param sortDirection
|
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
|
||||||
* @param reportProgress flag to report request and response progress.
|
|
||||||
*/
|
|
||||||
public getAllPatents(
|
|
||||||
page?: number,
|
|
||||||
size?: number,
|
|
||||||
search?: string,
|
|
||||||
source?: string,
|
|
||||||
sortBy?: string,
|
|
||||||
sortDirection?: string,
|
|
||||||
observe?: 'body',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<AllPatentsResponse>;
|
|
||||||
public getAllPatents(
|
|
||||||
page?: number,
|
|
||||||
size?: number,
|
|
||||||
search?: string,
|
|
||||||
source?: string,
|
|
||||||
sortBy?: string,
|
|
||||||
sortDirection?: string,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<AllPatentsResponse>>;
|
|
||||||
public getAllPatents(
|
|
||||||
page?: number,
|
|
||||||
size?: number,
|
|
||||||
search?: string,
|
|
||||||
source?: string,
|
|
||||||
sortBy?: string,
|
|
||||||
sortDirection?: string,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<AllPatentsResponse>>;
|
|
||||||
public getAllPatents(
|
|
||||||
page?: number,
|
|
||||||
size?: number,
|
|
||||||
search?: string,
|
|
||||||
source?: string,
|
|
||||||
sortBy?: string,
|
|
||||||
sortDirection?: string,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>page,
|
|
||||||
'page',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>size,
|
|
||||||
'size',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>search,
|
|
||||||
'search',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>source,
|
|
||||||
'source',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>sortBy,
|
|
||||||
'sort_by',
|
|
||||||
);
|
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
|
||||||
localVarQueryParameters,
|
|
||||||
<any>sortDirection,
|
|
||||||
'sort_direction',
|
|
||||||
);
|
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
|
||||||
options?.httpHeaderAccept ??
|
|
||||||
this.configuration.selectHeaderAccept(['application/json']);
|
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
|
||||||
localVarHeaders = localVarHeaders.set(
|
|
||||||
'Accept',
|
|
||||||
localVarHttpHeaderAcceptSelected,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const localVarHttpContext: HttpContext =
|
/**
|
||||||
options?.context ?? new HttpContext();
|
* Get all patents with pagination and search.
|
||||||
|
* @endpoint get /api/inse-service/patents
|
||||||
|
* @param page
|
||||||
|
* @param size
|
||||||
|
* @param search
|
||||||
|
* @param source
|
||||||
|
* @param sortBy
|
||||||
|
* @param sortDirection
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AllPatentsResponse>;
|
||||||
|
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AllPatentsResponse>>;
|
||||||
|
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AllPatentsResponse>>;
|
||||||
|
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>page, 'page');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>size, 'size');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>search, 'search');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>source, 'source');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>sortBy, 'sort_by');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>sortDirection, 'sort_direction');
|
||||||
|
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
let localVarHeaders = this.defaultHeaders;
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
responseType_ = 'text';
|
'application/json'
|
||||||
} else if (
|
]);
|
||||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
) {
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
responseType_ = 'json';
|
}
|
||||||
} else {
|
|
||||||
responseType_ = 'blob';
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
}
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/patents`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<AllPatentsResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarPath = `/api/inse-service/patents`;
|
/**
|
||||||
const { basePath, withCredentials } = this.configuration;
|
* Returns one publication by OpenAlex ID or DOI.
|
||||||
return this.httpClient.request<AllPatentsResponse>(
|
* @endpoint get /api/inse-service/patents/{identifier}
|
||||||
'get',
|
* @param identifier
|
||||||
`${basePath}${localVarPath}`,
|
* @param prefix Application Prefix (EP or US)
|
||||||
{
|
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
||||||
context: localVarHttpContext,
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
params: localVarQueryParameters,
|
* @param reportProgress flag to report request and response progress.
|
||||||
responseType: <any>responseType_,
|
*/
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
|
||||||
headers: localVarHeaders,
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentEntry>>;
|
||||||
observe: observe,
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentEntry>>;
|
||||||
...(localVarTransferCache !== undefined
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
? { transferCache: localVarTransferCache }
|
if (identifier === null || identifier === undefined) {
|
||||||
: {}),
|
throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.');
|
||||||
reportProgress: reportProgress,
|
}
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
* Returns one publication by OpenAlex ID or DOI.
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
* @endpoint get /api/inse-service/patents/{identifier}
|
<any>prefix, 'prefix');
|
||||||
* @param identifier
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
* @param prefix Application Prefix (EP or US)
|
<any>title, 'title');
|
||||||
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
let localVarHeaders = this.defaultHeaders;
|
||||||
* @param reportProgress flag to report request and response progress.
|
|
||||||
*/
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
public getPatentByIdOrTitle(
|
'application/json'
|
||||||
identifier: string,
|
]);
|
||||||
prefix?: string,
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
title?: string,
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
observe?: 'body',
|
}
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<PatentEntry>;
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
public getPatentByIdOrTitle(
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
identifier: string,
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
prefix?: string,
|
responseType_ = 'text';
|
||||||
title?: string,
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
observe?: 'response',
|
responseType_ = 'json';
|
||||||
reportProgress?: boolean,
|
} else {
|
||||||
options?: {
|
responseType_ = 'blob';
|
||||||
httpHeaderAccept?: 'application/json';
|
}
|
||||||
context?: HttpContext;
|
}
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||||
): Observable<HttpResponse<PatentEntry>>;
|
const { basePath, withCredentials } = this.configuration;
|
||||||
public getPatentByIdOrTitle(
|
return this.httpClient.request<PatentEntry>('get', `${basePath}${localVarPath}`,
|
||||||
identifier: string,
|
{
|
||||||
prefix?: string,
|
context: localVarHttpContext,
|
||||||
title?: string,
|
params: localVarQueryParameters,
|
||||||
observe?: 'events',
|
responseType: <any>responseType_,
|
||||||
reportProgress?: boolean,
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
options?: {
|
headers: localVarHeaders,
|
||||||
httpHeaderAccept?: 'application/json';
|
observe: observe,
|
||||||
context?: HttpContext;
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
transferCache?: boolean;
|
reportProgress: reportProgress
|
||||||
},
|
}
|
||||||
): Observable<HttpEvent<PatentEntry>>;
|
);
|
||||||
public getPatentByIdOrTitle(
|
|
||||||
identifier: string,
|
|
||||||
prefix?: string,
|
|
||||||
title?: string,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (identifier === null || identifier === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
/**
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
* Get patents matched to an author by name.
|
||||||
localVarQueryParameters,
|
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||||
<any>prefix,
|
* @param authorId
|
||||||
'prefix',
|
* @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.
|
||||||
localVarQueryParameters = this.addToHttpParams(
|
*/
|
||||||
localVarQueryParameters,
|
public getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
|
||||||
<any>title,
|
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
||||||
'title',
|
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
||||||
);
|
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (authorId === null || authorId === undefined) {
|
||||||
|
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
|
||||||
|
}
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
options?.httpHeaderAccept ??
|
'application/json'
|
||||||
this.configuration.selectHeaderAccept(['application/json']);
|
]);
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
localVarHeaders = localVarHeaders.set(
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
'Accept',
|
}
|
||||||
localVarHttpHeaderAcceptSelected,
|
|
||||||
);
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const localVarHttpContext: HttpContext =
|
|
||||||
options?.context ?? new HttpContext();
|
|
||||||
|
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
|
||||||
|
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
|
||||||
responseType_ = 'text';
|
|
||||||
} else if (
|
|
||||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
|
||||||
) {
|
|
||||||
responseType_ = 'json';
|
|
||||||
} else {
|
|
||||||
responseType_ = 'blob';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
|
||||||
const { basePath, withCredentials } = this.configuration;
|
|
||||||
return this.httpClient.request<PatentEntry>(
|
|
||||||
'get',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
params: localVarQueryParameters,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get patents matched to an author by name.
|
|
||||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
|
||||||
* @param authorId
|
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
|
||||||
* @param reportProgress flag to report request and response progress.
|
|
||||||
*/
|
|
||||||
public getPatentsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'body',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<PatentsByAuthorResponse>;
|
|
||||||
public getPatentsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
|
||||||
public getPatentsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
|
||||||
public getPatentsByAuthor(
|
|
||||||
authorId: string,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (authorId === null || authorId === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
|
||||||
options?.httpHeaderAccept ??
|
|
||||||
this.configuration.selectHeaderAccept(['application/json']);
|
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
|
||||||
localVarHeaders = localVarHeaders.set(
|
|
||||||
'Accept',
|
|
||||||
localVarHttpHeaderAcceptSelected,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const localVarHttpContext: HttpContext =
|
|
||||||
options?.context ?? new HttpContext();
|
|
||||||
|
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
|
||||||
|
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
|
||||||
responseType_ = 'text';
|
|
||||||
} else if (
|
|
||||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
|
||||||
) {
|
|
||||||
responseType_ = 'json';
|
|
||||||
} else {
|
|
||||||
responseType_ = 'blob';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
|
|
||||||
const { basePath, withCredentials } = this.configuration;
|
|
||||||
return this.httpClient.request<PatentsByAuthorResponse>(
|
|
||||||
'get',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,18 +9,12 @@
|
|||||||
*/
|
*/
|
||||||
/* tslint:disable:no-unused-variable member-ordering */
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
import { Inject, Injectable, Optional } from '@angular/core';
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
import {
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
HttpClient,
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
HttpHeaders,
|
} from '@angular/common/http';
|
||||||
HttpParams,
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
HttpResponse,
|
import { Observable } from 'rxjs';
|
||||||
HttpEvent,
|
|
||||||
HttpParameterCodec,
|
|
||||||
HttpContext,
|
|
||||||
} from '@angular/common/http';
|
|
||||||
import { CustomHttpParameterCodec } from '../encoder';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { CollaborationNetwork } from '../model/collaborationNetwork';
|
import { CollaborationNetwork } from '../model/collaborationNetwork';
|
||||||
@@ -30,139 +24,86 @@ import { FilterProperties } from '../model/filterProperties';
|
|||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
import { Configuration } from '../configuration';
|
import { Configuration } from '../configuration';
|
||||||
import { BaseService } from '../api.base.service';
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class PersonNetworkService extends BaseService {
|
export class PersonNetworkService extends BaseService {
|
||||||
constructor(
|
|
||||||
protected httpClient: HttpClient,
|
|
||||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
|
||||||
@Optional() configuration?: Configuration,
|
|
||||||
) {
|
|
||||||
super(basePath, configuration);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
* Get a person\'s collaboration network.
|
super(basePath, configuration);
|
||||||
* 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<CollaborationNetwork>;
|
|
||||||
public getCollaborationNetwork(
|
|
||||||
rawUserId: string,
|
|
||||||
filterProperties?: FilterProperties,
|
|
||||||
observe?: 'response',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpResponse<CollaborationNetwork>>;
|
|
||||||
public getCollaborationNetwork(
|
|
||||||
rawUserId: string,
|
|
||||||
filterProperties?: FilterProperties,
|
|
||||||
observe?: 'events',
|
|
||||||
reportProgress?: boolean,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<HttpEvent<CollaborationNetwork>>;
|
|
||||||
public getCollaborationNetwork(
|
|
||||||
rawUserId: string,
|
|
||||||
filterProperties?: FilterProperties,
|
|
||||||
observe: any = 'body',
|
|
||||||
reportProgress: boolean = false,
|
|
||||||
options?: {
|
|
||||||
httpHeaderAccept?: 'application/json';
|
|
||||||
context?: HttpContext;
|
|
||||||
transferCache?: boolean;
|
|
||||||
},
|
|
||||||
): Observable<any> {
|
|
||||||
if (rawUserId === null || rawUserId === undefined) {
|
|
||||||
throw new Error(
|
|
||||||
'Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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<CollaborationNetwork>;
|
||||||
|
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationNetwork>>;
|
||||||
|
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationNetwork>>;
|
||||||
|
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (rawUserId === null || rawUserId === undefined) {
|
||||||
|
throw new Error('Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.');
|
||||||
|
}
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
let localVarHeaders = this.defaultHeaders;
|
||||||
options?.httpHeaderAccept ??
|
|
||||||
this.configuration.selectHeaderAccept(['application/json']);
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
'application/json'
|
||||||
localVarHeaders = localVarHeaders.set(
|
]);
|
||||||
'Accept',
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
localVarHttpHeaderAcceptSelected,
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
);
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// 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<CollaborationNetwork>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: filterProperties,
|
||||||
|
responseType: <any>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<CollaborationNetwork>(
|
|
||||||
'post',
|
|
||||||
`${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
body: filterProperties,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined
|
|
||||||
? { transferCache: localVarTransferCache }
|
|
||||||
: {}),
|
|
||||||
reportProgress: reportProgress,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+171
-197
@@ -1,219 +1,193 @@
|
|||||||
import {
|
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
|
||||||
HttpHeaders,
|
|
||||||
HttpParams,
|
|
||||||
HttpParameterCodec,
|
|
||||||
} from '@angular/common/http';
|
|
||||||
import { Param } from './param';
|
import { Param } from './param';
|
||||||
|
|
||||||
export interface ConfigurationParameters {
|
export interface ConfigurationParameters {
|
||||||
/**
|
/**
|
||||||
* @deprecated Since 5.0. Use credentials instead
|
* @deprecated Since 5.0. Use credentials instead
|
||||||
*/
|
*/
|
||||||
apiKeys?: { [key: string]: string };
|
apiKeys?: {[ key: string ]: string};
|
||||||
username?: string;
|
username?: string;
|
||||||
password?: string;
|
password?: string;
|
||||||
/**
|
/**
|
||||||
* @deprecated Since 5.0. Use credentials instead
|
* @deprecated Since 5.0. Use credentials instead
|
||||||
*/
|
*/
|
||||||
accessToken?: string | (() => string);
|
accessToken?: string | (() => string);
|
||||||
basePath?: string;
|
basePath?: string;
|
||||||
withCredentials?: boolean;
|
withCredentials?: boolean;
|
||||||
/**
|
/**
|
||||||
* Takes care of encoding query- and form-parameters.
|
* Takes care of encoding query- and form-parameters.
|
||||||
*/
|
*/
|
||||||
encoder?: HttpParameterCodec;
|
encoder?: HttpParameterCodec;
|
||||||
/**
|
/**
|
||||||
* Override the default method for encoding path parameters in various
|
* Override the default method for encoding path parameters in various
|
||||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||||
* <p>
|
* <p>
|
||||||
* See {@link README.md} for more details
|
* See {@link README.md} for more details
|
||||||
* </p>
|
* </p>
|
||||||
*/
|
*/
|
||||||
encodeParam?: (param: Param) => string;
|
encodeParam?: (param: Param) => string;
|
||||||
/**
|
/**
|
||||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||||
* document. They should map to the value used for authentication
|
* document. They should map to the value used for authentication
|
||||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||||
*/
|
*/
|
||||||
credentials?: { [key: string]: string | (() => string | undefined) };
|
credentials?: {[ key: string ]: string | (() => string | undefined)};
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Configuration {
|
export class Configuration {
|
||||||
/**
|
/**
|
||||||
* @deprecated Since 5.0. Use credentials instead
|
* @deprecated Since 5.0. Use credentials instead
|
||||||
*/
|
*/
|
||||||
apiKeys?: { [key: string]: string };
|
apiKeys?: {[ key: string ]: string};
|
||||||
username?: string;
|
username?: string;
|
||||||
password?: string;
|
password?: string;
|
||||||
/**
|
/**
|
||||||
* @deprecated Since 5.0. Use credentials instead
|
* @deprecated Since 5.0. Use credentials instead
|
||||||
*/
|
*/
|
||||||
accessToken?: string | (() => string);
|
accessToken?: string | (() => string);
|
||||||
basePath?: string;
|
basePath?: string;
|
||||||
withCredentials?: boolean;
|
withCredentials?: boolean;
|
||||||
/**
|
/**
|
||||||
* Takes care of encoding query- and form-parameters.
|
* Takes care of encoding query- and form-parameters.
|
||||||
*/
|
*/
|
||||||
encoder?: HttpParameterCodec;
|
encoder?: HttpParameterCodec;
|
||||||
/**
|
/**
|
||||||
* Encoding of various path parameter
|
* Encoding of various path parameter
|
||||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||||
* <p>
|
* <p>
|
||||||
* See {@link README.md} for more details
|
* See {@link README.md} for more details
|
||||||
* </p>
|
* </p>
|
||||||
*/
|
*/
|
||||||
encodeParam: (param: Param) => string;
|
encodeParam: (param: Param) => string;
|
||||||
/**
|
/**
|
||||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||||
* document. They should map to the value used for authentication
|
* document. They should map to the value used for authentication
|
||||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||||
*/
|
*/
|
||||||
credentials: { [key: string]: string | (() => string | undefined) };
|
credentials: {[ key: string ]: string | (() => string | undefined)};
|
||||||
|
|
||||||
constructor({
|
constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) {
|
||||||
accessToken,
|
if (apiKeys) {
|
||||||
apiKeys,
|
this.apiKeys = apiKeys;
|
||||||
basePath,
|
}
|
||||||
credentials,
|
if (username !== undefined) {
|
||||||
encodeParam,
|
this.username = username;
|
||||||
encoder,
|
}
|
||||||
password,
|
if (password !== undefined) {
|
||||||
username,
|
this.password = password;
|
||||||
withCredentials,
|
}
|
||||||
}: ConfigurationParameters = {}) {
|
if (accessToken !== undefined) {
|
||||||
if (apiKeys) {
|
this.accessToken = accessToken;
|
||||||
this.apiKeys = apiKeys;
|
}
|
||||||
}
|
if (basePath !== undefined) {
|
||||||
if (username !== undefined) {
|
this.basePath = basePath;
|
||||||
this.username = username;
|
}
|
||||||
}
|
if (withCredentials !== undefined) {
|
||||||
if (password !== undefined) {
|
this.withCredentials = withCredentials;
|
||||||
this.password = password;
|
}
|
||||||
}
|
if (encoder) {
|
||||||
if (accessToken !== undefined) {
|
this.encoder = encoder;
|
||||||
this.accessToken = accessToken;
|
}
|
||||||
}
|
this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param));
|
||||||
if (basePath !== undefined) {
|
this.credentials = credentials ?? {};
|
||||||
this.basePath = basePath;
|
|
||||||
}
|
|
||||||
if (withCredentials !== undefined) {
|
|
||||||
this.withCredentials = withCredentials;
|
|
||||||
}
|
|
||||||
if (encoder) {
|
|
||||||
this.encoder = encoder;
|
|
||||||
}
|
|
||||||
this.encodeParam =
|
|
||||||
encodeParam ?? ((param) => this.defaultEncodeParam(param));
|
|
||||||
this.credentials = credentials ?? {};
|
|
||||||
|
|
||||||
// init default bearer credential
|
// init default HTTPBearer credential
|
||||||
if (!this.credentials['bearer']) {
|
if (!this.credentials['HTTPBearer']) {
|
||||||
this.credentials['bearer'] = () => {
|
this.credentials['HTTPBearer'] = () => {
|
||||||
return typeof this.accessToken === 'function'
|
return typeof this.accessToken === 'function'
|
||||||
? this.accessToken()
|
? this.accessToken()
|
||||||
: this.accessToken;
|
: this.accessToken;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select the correct content-type to use for a request.
|
|
||||||
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
|
|
||||||
* If no content type is found return the first found type if the contentTypes is not empty
|
|
||||||
* @param contentTypes - the array of content types that are available for selection
|
|
||||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
|
||||||
*/
|
|
||||||
public selectHeaderContentType(contentTypes: string[]): string | undefined {
|
|
||||||
if (contentTypes.length === 0) {
|
|
||||||
return undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
/**
|
||||||
if (type === undefined) {
|
* Select the correct content-type to use for a request.
|
||||||
return contentTypes[0];
|
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
|
||||||
}
|
* If no content type is found return the first found type if the contentTypes is not empty
|
||||||
return type;
|
* @param contentTypes - the array of content types that are available for selection
|
||||||
}
|
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||||
|
*/
|
||||||
|
public selectHeaderContentType (contentTypes: string[]): string | undefined {
|
||||||
|
if (contentTypes.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||||
* Select the correct accept content-type to use for a request.
|
if (type === undefined) {
|
||||||
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
|
return contentTypes[0];
|
||||||
* If no content type is found return the first found type if the contentTypes is not empty
|
}
|
||||||
* @param accepts - the array of content types that are available for selection.
|
return type;
|
||||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
|
||||||
*/
|
|
||||||
public selectHeaderAccept(accepts: string[]): string | undefined {
|
|
||||||
if (accepts.length === 0) {
|
|
||||||
return undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const type = accepts.find((x: string) => this.isJsonMime(x));
|
/**
|
||||||
if (type === undefined) {
|
* Select the correct accept content-type to use for a request.
|
||||||
return accepts[0];
|
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
|
||||||
|
* If no content type is found return the first found type if the contentTypes is not empty
|
||||||
|
* @param accepts - the array of content types that are available for selection.
|
||||||
|
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||||
|
*/
|
||||||
|
public selectHeaderAccept(accepts: string[]): string | undefined {
|
||||||
|
if (accepts.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = accepts.find((x: string) => this.isJsonMime(x));
|
||||||
|
if (type === undefined) {
|
||||||
|
return accepts[0];
|
||||||
|
}
|
||||||
|
return type;
|
||||||
}
|
}
|
||||||
return type;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the given MIME is a JSON MIME.
|
* Check if the given MIME is a JSON MIME.
|
||||||
* JSON MIME examples:
|
* JSON MIME examples:
|
||||||
* application/json
|
* application/json
|
||||||
* application/json; charset=UTF8
|
* application/json; charset=UTF8
|
||||||
* APPLICATION/JSON
|
* APPLICATION/JSON
|
||||||
* application/vnd.company+json
|
* application/vnd.company+json
|
||||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||||
* @return True if the given MIME is JSON, false otherwise.
|
* @return True if the given MIME is JSON, false otherwise.
|
||||||
*/
|
*/
|
||||||
public isJsonMime(mime: string): boolean {
|
public isJsonMime(mime: string): boolean {
|
||||||
const jsonMime: RegExp = new RegExp(
|
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
|
||||||
'^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$',
|
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
|
||||||
'i',
|
}
|
||||||
);
|
|
||||||
return (
|
|
||||||
mime !== null &&
|
|
||||||
(jsonMime.test(mime) ||
|
|
||||||
mime.toLowerCase() === 'application/json-patch+json')
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public lookupCredential(key: string): string | undefined {
|
public lookupCredential(key: string): string | undefined {
|
||||||
const value = this.credentials[key];
|
const value = this.credentials[key];
|
||||||
return typeof value === 'function' ? value() : value;
|
return typeof value === 'function'
|
||||||
}
|
? value()
|
||||||
|
: value;
|
||||||
|
}
|
||||||
|
|
||||||
public addCredentialToHeaders(
|
public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders {
|
||||||
credentialKey: string,
|
const value = this.lookupCredential(credentialKey);
|
||||||
headerName: string,
|
return value
|
||||||
headers: HttpHeaders,
|
? headers.set(headerName, (prefix ?? '') + value)
|
||||||
prefix?: string,
|
: headers;
|
||||||
): HttpHeaders {
|
}
|
||||||
const value = this.lookupCredential(credentialKey);
|
|
||||||
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
public addCredentialToQuery(
|
public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
|
||||||
credentialKey: string,
|
const value = this.lookupCredential(credentialKey);
|
||||||
paramName: string,
|
return value
|
||||||
query: HttpParams,
|
? query.set(paramName, value)
|
||||||
): HttpParams {
|
: query;
|
||||||
const value = this.lookupCredential(credentialKey);
|
}
|
||||||
return value ? query.set(paramName, value) : query;
|
|
||||||
}
|
|
||||||
|
|
||||||
private defaultEncodeParam(param: Param): string {
|
private defaultEncodeParam(param: Param): string {
|
||||||
// This implementation exists as fallback for missing configuration
|
// This implementation exists as fallback for missing configuration
|
||||||
// and for backwards compatibility to older typescript-angular generator versions.
|
// and for backwards compatibility to older typescript-angular generator versions.
|
||||||
// It only works for the 'simple' parameter style.
|
// It only works for the 'simple' parameter style.
|
||||||
// Date-handling only works for the 'date-time' format.
|
// Date-handling only works for the 'date-time' format.
|
||||||
// All other styles and Date-formats are probably handled incorrectly.
|
// All other styles and Date-formats are probably handled incorrectly.
|
||||||
//
|
//
|
||||||
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
|
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
|
||||||
|
|
||||||
const value =
|
const value = param.dataFormat === 'date-time' && param.value instanceof Date
|
||||||
param.dataFormat === 'date-time' && param.value instanceof Date
|
? (param.value as Date).toISOString()
|
||||||
? (param.value as Date).toISOString()
|
: param.value;
|
||||||
: param.value;
|
|
||||||
|
|
||||||
return encodeURIComponent(String(value));
|
return encodeURIComponent(String(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user