Compare commits
1
Commits
permissions
...
fix-httpx
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11ea77135e |
@@ -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 @@
|
||||
|
||||
@@ -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,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,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,
|
||||
)
|
||||
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)
|
||||
@@ -30,7 +30,6 @@ class Settings(BaseSettings):
|
||||
openalex_works_search_index: str = "openalex-works*"
|
||||
openalex_works_search_timeout_seconds: float = 30.0
|
||||
# OpenAlex public API config
|
||||
openalex_api_base_url: str = "https://api.openalex.org"
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from pydantic import ValidationError
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||
|
||||
@@ -60,34 +59,17 @@ async def list_institutions(
|
||||
|
||||
openalex_client = client or OpenAlexInstitutionsClient()
|
||||
|
||||
try:
|
||||
data = await openalex_client.list_institutions(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex institutions request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex institutions request failed.")
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
data = await openalex_client.list_institutions(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_institutions_response(data)
|
||||
|
||||
@@ -1,36 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for OpenAlex institutions.
|
||||
"""
|
||||
"""Elasticsearch client for OpenAlex institutions."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
|
||||
class OpenAlexInstitutionsClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = (
|
||||
api_key if api_key is not None else config.settings.openalex_api_key
|
||||
)
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
def __init__(self, index: str | ESIndex = ESIndex.OPENALEX_INSTITUTIONS):
|
||||
self.index = index
|
||||
|
||||
def list_institutions_params(
|
||||
def list_institutions_query(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -43,60 +25,144 @@ class OpenAlexInstitutionsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
|
||||
must: list[dict[str, Any]] = []
|
||||
if search:
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
|
||||
return params
|
||||
|
||||
async def list_institutions(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/institutions",
|
||||
params=self.list_institutions_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
must.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": search,
|
||||
"fields": [
|
||||
"display_name^3",
|
||||
"display_name_alternatives^2",
|
||||
"display_name_acronyms^2",
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": must or [{"match_all": {}}],
|
||||
"filter": self._filters(filter),
|
||||
}
|
||||
}
|
||||
if sample is not None:
|
||||
query = {
|
||||
"function_score": {
|
||||
"query": query,
|
||||
"random_score": {"seed": sample},
|
||||
}
|
||||
}
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"query": query,
|
||||
"from": max((page or 1) - 1, 0) * per_page,
|
||||
"size": per_page,
|
||||
"track_total_hits": True,
|
||||
}
|
||||
if select:
|
||||
body["_source"] = [
|
||||
field.strip() for field in select.split(",") if field.strip()
|
||||
]
|
||||
if sort:
|
||||
body["sort"] = self._sort(sort)
|
||||
if cursor and cursor != "*":
|
||||
body["search_after"] = cursor.split(",")
|
||||
body.pop("from", None)
|
||||
if group_by:
|
||||
body["aggs"] = {
|
||||
"group_by": {
|
||||
"terms": {
|
||||
"field": self._keyword_field(group_by),
|
||||
"size": per_page,
|
||||
}
|
||||
}
|
||||
}
|
||||
return body
|
||||
|
||||
async def list_institutions(self, **kwargs: Any) -> dict[str, Any]:
|
||||
response = await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=self.list_institutions_query(**kwargs),
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_value = hits_block.get("total", 0)
|
||||
total = (
|
||||
total_value.get("value", 0)
|
||||
if isinstance(total_value, dict)
|
||||
else total_value
|
||||
)
|
||||
result: dict[str, Any] = {
|
||||
"meta": {
|
||||
"count": total,
|
||||
"page": kwargs.get("page", 1),
|
||||
"per_page": kwargs.get("per_page", 25),
|
||||
"next_cursor": self._next_cursor(hits),
|
||||
},
|
||||
"results": [hit.get("_source", {}) for hit in hits],
|
||||
}
|
||||
|
||||
buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets")
|
||||
if buckets is not None:
|
||||
result["group_by"] = [
|
||||
{
|
||||
"key": bucket.get("key"),
|
||||
"key_display_name": bucket.get(
|
||||
"key_as_string", bucket.get("key")
|
||||
),
|
||||
"count": bucket.get("doc_count"),
|
||||
}
|
||||
for bucket in buckets
|
||||
]
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _filters(value: str | None) -> list[dict[str, Any]]:
|
||||
clauses: list[dict[str, Any]] = []
|
||||
for item in (value or "").split(","):
|
||||
if not item or ":" not in item:
|
||||
continue
|
||||
field, raw_value = item.split(":", 1)
|
||||
field = field.strip()
|
||||
raw_value = raw_value.strip()
|
||||
if raw_value.startswith((">", "<")):
|
||||
operator = "gt" if raw_value[0] == ">" else "lt"
|
||||
clauses.append({"range": {field: {operator: raw_value[1:]}}})
|
||||
else:
|
||||
clauses.append(
|
||||
{"term": {OpenAlexInstitutionsClient._keyword_field(field): raw_value}}
|
||||
)
|
||||
return clauses
|
||||
|
||||
@staticmethod
|
||||
def _sort(value: str) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for item in value.split(","):
|
||||
field, _, direction = item.partition(":")
|
||||
result.append(
|
||||
{
|
||||
OpenAlexInstitutionsClient._sortable_field(field.strip()): {
|
||||
"order": direction or "desc",
|
||||
"missing": "_last",
|
||||
}
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _keyword_field(field: str) -> str:
|
||||
if field in {"id", "ror", "display_name"}:
|
||||
return f"{field}.keyword"
|
||||
return field
|
||||
|
||||
@staticmethod
|
||||
def _sortable_field(field: str) -> str:
|
||||
return "display_name.keyword" if field == "display_name" else field
|
||||
|
||||
@staticmethod
|
||||
def _next_cursor(hits: list[dict[str, Any]]) -> str | None:
|
||||
if not hits or not hits[-1].get("sort"):
|
||||
return None
|
||||
return ",".join(str(value) for value in hits[-1]["sort"])
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -11,166 +9,72 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"homepage_url": "https://www.uni-due.de",
|
||||
"image_url": "https://example.org/image.jpg",
|
||||
"image_thumbnail_url": "https://example.org/thumb.jpg",
|
||||
"display_name_acronyms": ["UDE"],
|
||||
"display_name_alternatives": ["Universitaet Duisburg-Essen"],
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"summary_stats": {
|
||||
"2yr_mean_citedness": 1.5,
|
||||
"h_index": 42,
|
||||
"i10_index": 99,
|
||||
},
|
||||
"geo": {
|
||||
"city": "Duisburg",
|
||||
"geonames_city_id": "2934691",
|
||||
"region": "North Rhine-Westphalia",
|
||||
"country_code": "DE",
|
||||
"country": "Germany",
|
||||
"latitude": 51.4344,
|
||||
"longitude": 6.7623,
|
||||
},
|
||||
"lineage": ["https://openalex.org/I123"],
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"mag": 123,
|
||||
"grid": "grid.12345.6",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen",
|
||||
"wikidata": "https://www.wikidata.org/wiki/Q317070",
|
||||
},
|
||||
"counts_by_year": [
|
||||
{
|
||||
"year": 2024,
|
||||
"works_count": 12,
|
||||
"cited_by_count": 34,
|
||||
}
|
||||
],
|
||||
"works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "DE",
|
||||
"key_display_name": "Germany",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
class StubInstitutionsClient:
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
self.kwargs = None
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
async def list_institutions(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_maps_elasticsearch_response_to_model():
|
||||
client = StubInstitutionsClient(
|
||||
{
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/012345678",
|
||||
"display_name": "Example University",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"geo": {"city": "Essen", "country": "Germany"},
|
||||
"ids": {"openalex": "https://openalex.org/I123"},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(search="Duisburg Essen", client=client)
|
||||
result = await logic.list_institutions(search="Example", client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
institution = result.results[0]
|
||||
assert institution.display_name == "University of Duisburg-Essen"
|
||||
assert institution.summary_stats.h_index == 42
|
||||
assert institution.geo.country == "Germany"
|
||||
assert institution.ids.mag == 123
|
||||
assert institution.counts_by_year[0].year == 2024
|
||||
assert result.group_by[0].key_display_name == "Germany"
|
||||
assert result.results[0].display_name == "Example University"
|
||||
assert result.results[0].geo.city == "Essen"
|
||||
assert client.kwargs["search"] == "Example"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_rejects_sample_with_sort():
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
with pytest.raises(BadRequestException):
|
||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"ror": 456,
|
||||
"display_name": "Example Institute",
|
||||
"country_code": 789,
|
||||
"type": "unknown-openalex-type",
|
||||
"display_name_acronyms": ["EI", 123],
|
||||
"display_name_alternatives": "not-a-list",
|
||||
"works_count": "12",
|
||||
"cited_by_count": "34.0",
|
||||
"summary_stats": {
|
||||
"2yr_mean_citedness": "1.25",
|
||||
"h_index": "10.0",
|
||||
"i10_index": True,
|
||||
},
|
||||
"geo": {
|
||||
"city": 123,
|
||||
"geonames_city_id": 12345,
|
||||
"latitude": "51.4",
|
||||
"longitude": "6",
|
||||
},
|
||||
"ids": {"openalex": 123, "mag": "123"},
|
||||
"counts_by_year": [
|
||||
{
|
||||
"year": "2024",
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
}
|
||||
],
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": 1}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
async def test_list_institutions_normalizes_elasticsearch_values():
|
||||
client = StubInstitutionsClient(
|
||||
{
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"type": "unknown-type",
|
||||
"works_count": "12.0",
|
||||
"ids": {"openalex": 123, "mag": "123"},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(client=client)
|
||||
|
||||
assert result.results[0].id == "123"
|
||||
assert result.results[0].ror == "456"
|
||||
assert result.results[0].country_code == "789"
|
||||
assert result.results[0].display_name == "456"
|
||||
assert result.results[0].type is None
|
||||
assert result.results[0].display_name_acronyms == ["EI", "123"]
|
||||
assert result.results[0].display_name_alternatives is None
|
||||
assert result.results[0].works_count == 12
|
||||
assert result.results[0].cited_by_count == 34
|
||||
assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25
|
||||
assert result.results[0].summary_stats.h_index == 10
|
||||
assert result.results[0].summary_stats.i10_index is None
|
||||
assert result.results[0].geo.city == "123"
|
||||
assert result.results[0].geo.geonames_city_id == "12345"
|
||||
assert result.results[0].geo.latitude == 51.4
|
||||
assert result.results[0].geo.longitude == 6
|
||||
assert result.results[0].ids.openalex == "123"
|
||||
assert result.results[0].ids.mag == 123
|
||||
assert result.results[0].counts_by_year[0].year == 2024
|
||||
assert result.results[0].counts_by_year[0].works_count == 12
|
||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import httpx
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
|
||||
@@ -9,69 +11,47 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_institutions_params_include_openalex_query_parameters():
|
||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
||||
|
||||
params = client.list_institutions_params(
|
||||
def test_list_institutions_query_builds_elasticsearch_query():
|
||||
body = OpenAlexInstitutionsClient().list_institutions_query(
|
||||
search="Duisburg Essen",
|
||||
filter="country_code:DE,type:education",
|
||||
filter="country_code:DE,type:education,works_count:>1000",
|
||||
sort="works_count:desc",
|
||||
group_by="country_code",
|
||||
per_page=10,
|
||||
page=2,
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert params == {
|
||||
"search": "Duisburg Essen",
|
||||
"filter": "country_code:DE,type:education",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "country_code",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
|
||||
|
||||
def test_list_institutions_params_prefers_cursor_over_page():
|
||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
||||
|
||||
params = client.list_institutions_params(cursor="*", page=3)
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
assert body["from"] == 10
|
||||
assert body["size"] == 10
|
||||
assert body["_source"] == ["id", "display_name"]
|
||||
assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "Duisburg Essen"
|
||||
assert {"term": {"country_code": "DE"}} in body["query"]["bool"]["filter"]
|
||||
assert {"term": {"type": "education"}} in body["query"]["bool"]["filter"]
|
||||
assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"]
|
||||
assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_calls_openalex_institutions_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/institutions"
|
||||
assert request.url.params["search"] == "Duisburg Essen"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
async def test_list_institutions_calls_elasticsearch_and_maps_hits():
|
||||
response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/I123",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"display_name": "Example University",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.list_institutions(search="Duisburg Essen")
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search:
|
||||
search.return_value = response
|
||||
result = await OpenAlexInstitutionsClient().list_institutions(search="Example")
|
||||
|
||||
search.assert_awaited_once()
|
||||
assert search.await_args.kwargs["index"] == ESIndex.OPENALEX_INSTITUTIONS
|
||||
assert search.await_args.kwargs["cluster"] == ESCluster.NES
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "University of Duisburg-Essen"
|
||||
assert result["results"][0]["display_name"] == "Example University"
|
||||
|
||||
@@ -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,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,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"
|
||||
@@ -8,7 +8,6 @@ import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from pydantic import ValidationError
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
@@ -46,34 +45,17 @@ async def list_topics(
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
|
||||
try:
|
||||
data = await openalex_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex topics request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
data = await openalex_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
|
||||
@@ -1,33 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for OpenAlex topics.
|
||||
"""
|
||||
"""Elasticsearch client for OpenAlex topics."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
|
||||
class OpenAlexTopicsClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
def __init__(self, index: str = "topicvectors"):
|
||||
self.index = index
|
||||
|
||||
def list_topics_params(
|
||||
def list_topics_query(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -40,60 +25,118 @@ class OpenAlexTopicsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
|
||||
filters = self._filters(filter)
|
||||
must: list[dict[str, Any]] = []
|
||||
if search:
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
|
||||
return params
|
||||
|
||||
async def list_topics(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/topics",
|
||||
params=self.list_topics_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
must.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": search,
|
||||
"fields": ["display_name^3", "keywords^2", "description"],
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": must or [{"match_all": {}}],
|
||||
"filter": filters,
|
||||
}
|
||||
}
|
||||
if sample is not None:
|
||||
query = {"function_score": {"query": query, "random_score": {"seed": sample}}}
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"query": query,
|
||||
"from": max((page or 1) - 1, 0) * per_page,
|
||||
"size": per_page,
|
||||
"track_total_hits": True,
|
||||
"_source": (
|
||||
[field.strip() for field in select.split(",") if field.strip()]
|
||||
if select
|
||||
else {"excludes": ["display_name_vector", "keyword_vectors"]}
|
||||
),
|
||||
}
|
||||
if sort:
|
||||
body["sort"] = self._sort(sort)
|
||||
if cursor and cursor != "*":
|
||||
body["search_after"] = cursor.split(",")
|
||||
body.pop("from", None)
|
||||
if group_by:
|
||||
body["aggs"] = {
|
||||
"group_by": {
|
||||
"terms": {"field": self._keyword_field(group_by), "size": per_page}
|
||||
}
|
||||
}
|
||||
return body
|
||||
|
||||
async def list_topics(self, **kwargs: Any) -> dict[str, Any]:
|
||||
body = self.list_topics_query(**kwargs)
|
||||
response = await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=body,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_value = hits_block.get("total", 0)
|
||||
total = total_value.get("value", 0) if isinstance(total_value, dict) else total_value
|
||||
per_page = kwargs.get("per_page", 25)
|
||||
page = kwargs.get("page", 1)
|
||||
|
||||
result: dict[str, Any] = {
|
||||
"meta": {
|
||||
"count": total,
|
||||
"page": page,
|
||||
"per_page": per_page,
|
||||
"next_cursor": self._next_cursor(hits),
|
||||
},
|
||||
"results": [hit.get("_source", {}) for hit in hits],
|
||||
}
|
||||
buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets")
|
||||
if buckets is not None:
|
||||
result["group_by"] = [
|
||||
{
|
||||
"key": bucket.get("key"),
|
||||
"key_display_name": bucket.get("key_as_string", bucket.get("key")),
|
||||
"count": bucket.get("doc_count"),
|
||||
}
|
||||
for bucket in buckets
|
||||
]
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _filters(value: str | None) -> list[dict[str, Any]]:
|
||||
clauses: list[dict[str, Any]] = []
|
||||
for item in (value or "").split(","):
|
||||
if not item or ":" not in item:
|
||||
continue
|
||||
field, raw_value = item.split(":", 1)
|
||||
field = OpenAlexTopicsClient._keyword_field(field.strip())
|
||||
raw_value = raw_value.strip()
|
||||
if raw_value.startswith((">", "<")):
|
||||
operator = "gt" if raw_value[0] == ">" else "lt"
|
||||
clauses.append({"range": {field.removesuffix(".keyword"): {operator: raw_value[1:]}}})
|
||||
else:
|
||||
clauses.append({"term": {field: raw_value}})
|
||||
return clauses
|
||||
|
||||
@staticmethod
|
||||
def _sort(value: str) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for item in value.split(","):
|
||||
field, _, direction = item.partition(":")
|
||||
result.append({field.strip(): {"order": direction or "desc", "missing": "_last"}})
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _keyword_field(field: str) -> str:
|
||||
if field in {"id", "display_name", "domain.id", "field.id", "subfield.id"}:
|
||||
return f"{field}.keyword"
|
||||
return field
|
||||
|
||||
@staticmethod
|
||||
def _next_cursor(hits: list[dict[str, Any]]) -> str | None:
|
||||
if not hits or not hits[-1].get("sort"):
|
||||
return None
|
||||
return ",".join(str(value) for value in hits[-1]["sort"])
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -11,183 +9,71 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_display_name": "Physical Sciences",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
class StubTopicsClient:
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
self.kwargs = None
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
async def list_topics(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||
client = StubTopicsClient(
|
||||
{
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_topics(search="machine learning", client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
topic = result.results[0]
|
||||
assert topic.display_name == "Machine learning"
|
||||
assert topic.var_field.display_name == "Computer Science"
|
||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||
assert topic.domain.display_name == "Physical Sciences"
|
||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||
assert result.results[0].var_field.display_name == "Computer Science"
|
||||
assert client.kwargs["search"] == "machine learning"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
with pytest.raises(BadRequestException):
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": "1"}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_topics(client=client)
|
||||
|
||||
topic = result.results[0]
|
||||
assert topic.id == "123"
|
||||
assert topic.display_name == "456"
|
||||
assert topic.description == "true"
|
||||
assert topic.keywords == ["topic", "123"]
|
||||
assert topic.works_count == 12
|
||||
assert topic.cited_by_count is None
|
||||
assert topic.var_field.id == "3"
|
||||
assert topic.domain.display_name == "6"
|
||||
assert topic.ids.wikipedia == "456"
|
||||
assert topic.created_date.isoformat() == "2023-12-25"
|
||||
assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00"
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_topics_returns_frontend_options():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert request.url.params["sort"] == "works_count:desc"
|
||||
assert request.url.params["per_page"] == "5"
|
||||
assert request.url.params["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
client = StubTopicsClient(
|
||||
{
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_topics(
|
||||
query="machine learning",
|
||||
domain_id="https://openalex.org/domains/4",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
subfield_id="https://openalex.org/subfields/1702",
|
||||
limit=5,
|
||||
client=client,
|
||||
)
|
||||
result = await logic.autocomplete_topics(query="machine learning", limit=5, client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
assert len(result.results) == 1
|
||||
option = result.results[0]
|
||||
assert option.id == "https://openalex.org/T12419"
|
||||
assert option.display_name == "Machine learning"
|
||||
assert option.hint == (
|
||||
"Computer Science · Artificial Intelligence · Physical Sciences"
|
||||
)
|
||||
assert option.works_count == 123
|
||||
assert option.cited_by_count == 456
|
||||
assert option.entity_type == "topic"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
assert result.results[0].hint == "Computer Science · Artificial Intelligence · Physical Sciences"
|
||||
assert result.results[0].entity_type == "topic"
|
||||
assert client.kwargs["sort"] == "works_count:desc"
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import httpx
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from inse.model import ESCluster
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@@ -9,67 +11,39 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_topics_params_include_openalex_query_parameters():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
|
||||
params = client.list_topics_params(
|
||||
def test_list_topics_query_builds_elasticsearch_query():
|
||||
body = OpenAlexTopicsClient().list_topics_query(
|
||||
search="machine learning",
|
||||
filter="domain.id:4,works_count:>1000",
|
||||
filter="domain.id:https://openalex.org/domains/4,works_count:>1000",
|
||||
sort="works_count:desc",
|
||||
group_by="domain.id",
|
||||
per_page=10,
|
||||
page=2,
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert params == {
|
||||
"search": "machine learning",
|
||||
"filter": "domain.id:4,works_count:>1000",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "domain.id",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
|
||||
|
||||
def test_list_topics_params_prefers_cursor_over_page():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
|
||||
params = client.list_topics_params(cursor="*", page=3)
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
assert body["from"] == 10
|
||||
assert body["size"] == 10
|
||||
assert body["_source"] == ["id", "display_name"]
|
||||
assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "machine learning"
|
||||
assert {"term": {"domain.id.keyword": "https://openalex.org/domains/4"}} in body["query"]["bool"]["filter"]
|
||||
assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"]
|
||||
assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/topics"
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.list_topics(search="machine learning")
|
||||
async def test_list_topics_calls_elasticsearch_and_maps_hits():
|
||||
response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [{"_source": {"id": "T1", "display_name": "Machine learning"}}],
|
||||
}
|
||||
}
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search:
|
||||
search.return_value = response
|
||||
result = await OpenAlexTopicsClient(index="topicvectors").list_topics(search="machine")
|
||||
|
||||
search.assert_awaited_once()
|
||||
assert search.await_args.kwargs["index"] == "topicvectors"
|
||||
assert search.await_args.kwargs["cluster"] == ESCluster.NES
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "Machine learning"
|
||||
|
||||
@@ -1,176 +1,94 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.works import logic
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
# @pytest.fixture
|
||||
# def anyio_backend():
|
||||
# return "asyncio"
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||
# def handler(request: httpx.Request) -> httpx.Response:
|
||||
# return httpx.Response(
|
||||
# 200,
|
||||
# json={
|
||||
# "hits": {
|
||||
# "total": {"value": 1},
|
||||
# "hits": [
|
||||
# {
|
||||
# "_source": {
|
||||
# "id": "https://openalex.org/W2741809807",
|
||||
# "doi": "https://doi.org/10.7717/peerj.4375",
|
||||
# "display_name": "Example work",
|
||||
# "type": "article",
|
||||
# "language": "en",
|
||||
# "publication_year": 2023,
|
||||
# "cited_by_count": 42,
|
||||
# "topics": [
|
||||
# {
|
||||
# "id": "https://openalex.org/T10102",
|
||||
# "display_name": "Machine learning",
|
||||
# "score": 0.91,
|
||||
# }
|
||||
# ],
|
||||
# "primary_location": {
|
||||
# "source": {
|
||||
# "id": "https://openalex.org/S123",
|
||||
# "display_name": "Example Source",
|
||||
# "issn": None,
|
||||
# }
|
||||
# },
|
||||
# "authorships": [
|
||||
# {
|
||||
# "author": {
|
||||
# "id": "https://openalex.org/A5023888391",
|
||||
# "display_name": "Example Author",
|
||||
# }
|
||||
# }
|
||||
# ],
|
||||
# }
|
||||
# }
|
||||
# ],
|
||||
# },
|
||||
# },
|
||||
# )
|
||||
|
||||
# client = OpenAlexWorksSearchClient(
|
||||
# base_url="https://project.nes.uni-due.de/elastic",
|
||||
# api_key="test-key",
|
||||
# transport=httpx.MockTransport(handler),
|
||||
# )
|
||||
|
||||
# page = await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
# assert page.total == 1
|
||||
# assert page.elements[0].doi == "https://doi.org/10.7717/peerj.4375"
|
||||
# assert page.elements[0].title == "Example work"
|
||||
# assert page.elements[0].type == "article"
|
||||
# assert page.elements[0].language == "en"
|
||||
# assert page.elements[0].publication_year == 2023
|
||||
# assert page.elements[0].cited_by_count == 42
|
||||
# assert page.elements[0].topics == ["Machine learning"]
|
||||
def work_hit(identifier: str, title: str) -> dict:
|
||||
return {
|
||||
"_source": {
|
||||
"id": f"https://openalex.org/{identifier}",
|
||||
"doi": f"https://doi.org/10.1234/{identifier.lower()}",
|
||||
"title": title,
|
||||
"display_name": title,
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"publication_year": 2024,
|
||||
"publication_date": "2024-01-01",
|
||||
"cited_by_count": 42,
|
||||
"topics": [
|
||||
{
|
||||
"id": "https://openalex.org/T10102",
|
||||
"display_name": "Machine learning",
|
||||
"score": 0.91,
|
||||
}
|
||||
],
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5023888391",
|
||||
"display_name": "Example Author",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_all_author_works_collects_all_pages():
|
||||
# requested_pages = []
|
||||
class StubWorksSearchClient:
|
||||
def __init__(self, pages: list[list[dict]], total: int):
|
||||
self.pages = pages
|
||||
self.total = total
|
||||
self.calls: list[dict] = []
|
||||
|
||||
# def handler(request: httpx.Request) -> httpx.Response:
|
||||
# payload = json_from_request(request)
|
||||
# requested_pages.append(payload["from"] // payload["size"] + 1)
|
||||
# page = requested_pages[-1]
|
||||
# hits = [
|
||||
# {
|
||||
# "_source": {
|
||||
# "id": f"https://openalex.org/W{page}",
|
||||
# "doi": f"https://doi.org/10.1234/example-{page}",
|
||||
# "title": f"Example work {page}",
|
||||
# "display_name": f"Example work {page}",
|
||||
# "type": "article",
|
||||
# "language": "en",
|
||||
# "publication_year": 2024,
|
||||
# "publication_date": "2024-01-01",
|
||||
# "cited_by_count": page,
|
||||
# "primary_location": {
|
||||
# "is_oa": True,
|
||||
# "source": {
|
||||
# "id": "https://openalex.org/S123",
|
||||
# "display_name": "Example Source",
|
||||
# },
|
||||
# },
|
||||
# "authorships": [
|
||||
# {
|
||||
# "author": {
|
||||
# "id": "https://openalex.org/A5023888391",
|
||||
# "display_name": "Example Author",
|
||||
# },
|
||||
# },
|
||||
# ],
|
||||
# "topics": [],
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# return httpx.Response(
|
||||
# 200,
|
||||
# json={
|
||||
# "hits": {
|
||||
# "total": {"value": 2},
|
||||
# "hits": hits,
|
||||
# },
|
||||
# },
|
||||
# )
|
||||
|
||||
# client = OpenAlexWorksSearchClient(
|
||||
# base_url="https://project.nes.uni-due.de/elastic",
|
||||
# api_key="test-key",
|
||||
# transport=httpx.MockTransport(handler),
|
||||
# )
|
||||
|
||||
# works = await logic.get_all_author_works("A5023888391", client=client)
|
||||
|
||||
# assert requested_pages == [1, 2]
|
||||
# assert works.total == 2
|
||||
# assert [work.title for work in works.elements] == ["Example work 1", "Example work 2"]
|
||||
# assert works.elements[0].id == "https://openalex.org/W1"
|
||||
# assert works.elements[0].display_name == "Example work 1"
|
||||
# assert works.elements[0].publication_date == "2024-01-01"
|
||||
# assert works.elements[0].primary_location.is_oa is True
|
||||
# assert works.elements[0].authorships[0].author.id == "https://openalex.org/A5023888391"
|
||||
async def search_author_works(self, author_id, page, size, **filters):
|
||||
self.calls.append(
|
||||
{
|
||||
"author_id": author_id,
|
||||
"page": page,
|
||||
"size": size,
|
||||
**filters,
|
||||
}
|
||||
)
|
||||
hits = self.pages[page - 1] if page <= len(self.pages) else []
|
||||
return {"hits": {"total": {"value": self.total}, "hits": hits}}
|
||||
|
||||
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_author_works_maps_missing_api_key_to_service_unavailable():
|
||||
# client = OpenAlexWorksSearchClient(api_key="")
|
||||
@pytest.mark.anyio
|
||||
async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||
client = StubWorksSearchClient(
|
||||
pages=[[work_hit("W2741809807", "Example work")]],
|
||||
total=1,
|
||||
)
|
||||
|
||||
# with pytest.raises(HTTPException) as exc:
|
||||
# await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
page = await logic.get_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
publication_year=[2024],
|
||||
client=client,
|
||||
)
|
||||
|
||||
# assert exc.value.status_code == 503
|
||||
assert page.total == 1
|
||||
assert page.last_page is True
|
||||
assert page.elements[0].title == "Example work"
|
||||
assert page.elements[0].doi == "https://doi.org/10.1234/w2741809807"
|
||||
assert client.calls[0]["publication_year"] == [2024]
|
||||
|
||||
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_author_works_maps_elasticsearch_errors_to_bad_gateway():
|
||||
# def handler(request: httpx.Request) -> httpx.Response:
|
||||
# return httpx.Response(500, json={"error": "upstream failed"})
|
||||
@pytest.mark.anyio
|
||||
async def test_get_all_author_works_collects_all_elasticsearch_pages():
|
||||
first_page = [work_hit(f"W{number}", f"Example work {number}") for number in range(100)]
|
||||
second_page = [work_hit("W100", "Example work 100")]
|
||||
client = StubWorksSearchClient(pages=[first_page, second_page], total=101)
|
||||
|
||||
# client = OpenAlexWorksSearchClient(
|
||||
# base_url="https://project.nes.uni-due.de/elastic",
|
||||
# api_key="test-key",
|
||||
# transport=httpx.MockTransport(handler),
|
||||
# )
|
||||
response = await logic.get_all_author_works("A5023888391", client=client)
|
||||
|
||||
# with pytest.raises(HTTPException) as exc:
|
||||
# await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
# assert exc.value.status_code == 502
|
||||
|
||||
|
||||
# def json_from_request(request: httpx.Request) -> dict:
|
||||
# return json.loads(request.content.decode("utf-8"))
|
||||
assert response.meta.count == 101
|
||||
assert len(response.results) == 101
|
||||
assert response.results[-1].title == "Example work 100"
|
||||
assert [call["page"] for call in client.calls] == [1, 2]
|
||||
|
||||
@@ -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,24 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { RefreshToken } from './refreshToken';
|
||||
import { AccessToken } from './accessToken';
|
||||
|
||||
|
||||
export interface AccessResponse {
|
||||
/**
|
||||
* The access token issued upon successful authentication.
|
||||
*/
|
||||
access_token: AccessToken;
|
||||
/**
|
||||
* The refresh token issued alongside the access token for obtaining new access tokens.
|
||||
*/
|
||||
refresh_token: RefreshToken;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { TokenType } from './tokenType';
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface AccessToken {
|
||||
/**
|
||||
* The type of the token, which is always ACCESS_TOKEN for this class.
|
||||
*/
|
||||
token_type?: TokenType;
|
||||
/**
|
||||
* The unique identifier of the real account associated with this token.
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The timestamp indicating when the token will expire.
|
||||
*/
|
||||
expires_at: string;
|
||||
/**
|
||||
* The epoch value for the token. Used for versioning of tokens.
|
||||
*/
|
||||
epoch?: number;
|
||||
/**
|
||||
* A hash of the user\'s fingerprint to ensure the token is used by the same user.
|
||||
*/
|
||||
user_fingerprint_hash: string;
|
||||
/**
|
||||
* The raw token string.
|
||||
*/
|
||||
raw_token: string;
|
||||
/**
|
||||
* The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.
|
||||
*/
|
||||
effective_account_id: string;
|
||||
/**
|
||||
* The specific role this access token grants within its organization.
|
||||
*/
|
||||
effective_role?: UserRole;
|
||||
/**
|
||||
* The unique identifier of the organization associated with this access token.
|
||||
*/
|
||||
effective_organization_id: string;
|
||||
}
|
||||
export namespace AccessToken {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { AccountProfile } from './accountProfile';
|
||||
|
||||
|
||||
export interface AccountPage {
|
||||
items: Array<AccountProfile>;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface AccountProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
is_current?: boolean;
|
||||
is_real_account?: boolean;
|
||||
is_impersonating?: boolean;
|
||||
}
|
||||
export namespace AccountProfile {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyChangePassword {
|
||||
/**
|
||||
* Current password
|
||||
*/
|
||||
current_password: string;
|
||||
/**
|
||||
* New password
|
||||
*/
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyGetAccessToken {
|
||||
/**
|
||||
* User\'s account ID
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* Effective account ID for the access token
|
||||
*/
|
||||
effective_account_id: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyLogin {
|
||||
/**
|
||||
* User\'s account ID
|
||||
*/
|
||||
account_id: string;
|
||||
/**
|
||||
* One-time code sent to user\'s email
|
||||
*/
|
||||
email_code: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyRequestOtk {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* User\'s password
|
||||
*/
|
||||
password: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface CreateAccountRequest {
|
||||
email: string;
|
||||
name: string;
|
||||
role?: UserRole;
|
||||
organization_id: string;
|
||||
password: string;
|
||||
openalex_person_id?: string | null;
|
||||
}
|
||||
export namespace CreateAccountRequest {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { TokenType } from './tokenType';
|
||||
|
||||
|
||||
export interface IdToken {
|
||||
/**
|
||||
* The type of the token, which is always ID_TOKEN for this class.
|
||||
*/
|
||||
token_type?: TokenType;
|
||||
/**
|
||||
* The unique identifier of the real account associated with this token.
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The timestamp indicating when the token will expire.
|
||||
*/
|
||||
expires_at: string;
|
||||
/**
|
||||
* The epoch value for the token. Used for versioning of tokens.
|
||||
*/
|
||||
epoch?: number;
|
||||
/**
|
||||
* A hash of the user\'s fingerprint to ensure the token is used by the same user.
|
||||
*/
|
||||
user_fingerprint_hash: string;
|
||||
/**
|
||||
* The raw token string.
|
||||
*/
|
||||
raw_token: string;
|
||||
}
|
||||
export namespace IdToken {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { IdToken } from './idToken';
|
||||
|
||||
|
||||
export interface LoginResponse {
|
||||
/**
|
||||
* The ID token issued upon successful login.
|
||||
*/
|
||||
id_token: IdToken;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { TokenType } from './tokenType';
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface RefreshToken {
|
||||
/**
|
||||
* The type of the token, which is always REFRESH_TOKEN for this class.
|
||||
*/
|
||||
token_type?: TokenType;
|
||||
/**
|
||||
* The unique identifier of the real account associated with this token.
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The timestamp indicating when the token will expire.
|
||||
*/
|
||||
expires_at: string;
|
||||
/**
|
||||
* The epoch value for the token. Used for versioning of tokens.
|
||||
*/
|
||||
epoch?: number;
|
||||
/**
|
||||
* A hash of the user\'s fingerprint to ensure the token is used by the same user.
|
||||
*/
|
||||
user_fingerprint_hash: string;
|
||||
/**
|
||||
* The raw token string.
|
||||
*/
|
||||
raw_token: string;
|
||||
/**
|
||||
* The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.
|
||||
*/
|
||||
effective_account_id: string;
|
||||
/**
|
||||
* The specific role this access token grants within its organization.
|
||||
*/
|
||||
effective_role?: UserRole;
|
||||
/**
|
||||
* The unique identifier of the organization associated with this access token.
|
||||
*/
|
||||
effective_organization_id: string;
|
||||
}
|
||||
export namespace RefreshToken {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export const TokenType = {
|
||||
Id: 'ID',
|
||||
Refresh: 'REFRESH',
|
||||
Access: 'ACCESS'
|
||||
} as const;
|
||||
export type TokenType = typeof TokenType[keyof typeof TokenType];
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface UpdateAccountRequest {
|
||||
email?: string | null;
|
||||
name?: string | null;
|
||||
role?: UserRole | null;
|
||||
organization_id?: string | null;
|
||||
password?: string | null;
|
||||
openalex_person_id?: string | null;
|
||||
deleted?: boolean | null;
|
||||
}
|
||||
export namespace UpdateAccountRequest {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export const UserRole = {
|
||||
SuperAdmin: 'SUPER_ADMIN',
|
||||
Admin: 'ADMIN',
|
||||
Manager: 'MANAGER',
|
||||
User: 'USER'
|
||||
} as const;
|
||||
export type UserRole = typeof UserRole[keyof typeof UserRole];
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<h2 mat-dialog-title>
|
||||
{{ data.mode === 'create' ? 'Account erstellen' : 'Account bearbeiten' }}
|
||||
</h2>
|
||||
|
||||
<mat-dialog-content>
|
||||
<form class="account-form" [formGroup]="form" (ngSubmit)="submit()">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>E-Mail</mat-label>
|
||||
<input matInput type="email" formControlName="email" />
|
||||
@if (form.controls.email.hasError('required')) {
|
||||
<mat-error>E-Mail ist erforderlich.</mat-error>
|
||||
} @else if (form.controls.email.hasError('email')) {
|
||||
<mat-error>Bitte gültige E-Mail eingeben.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Name</mat-label>
|
||||
<input matInput formControlName="name" />
|
||||
@if (form.controls.name.hasError('required')) {
|
||||
<mat-error>Name ist erforderlich.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Rolle</mat-label>
|
||||
<mat-select formControlName="role">
|
||||
@for (role of data.roles; track role) {
|
||||
<mat-option [value]="role">{{ role }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
|
||||
@if (data.canSelectOrganization) {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Organisation</mat-label>
|
||||
<mat-select formControlName="organizationId">
|
||||
@for (organization of data.organizations; track organization.id) {
|
||||
<mat-option [value]="organization.id">
|
||||
{{ organization.name }}
|
||||
</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>
|
||||
{{
|
||||
data.mode === 'create'
|
||||
? 'Initiales Passwort'
|
||||
: 'Neues Passwort'
|
||||
}}
|
||||
</mat-label>
|
||||
<input matInput type="password" formControlName="password" />
|
||||
@if (form.controls.password.hasError('required')) {
|
||||
<mat-error>Passwort ist erforderlich.</mat-error>
|
||||
} @else if (form.controls.password.hasError('minlength')) {
|
||||
<mat-error>Mindestens 8 Zeichen.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
</form>
|
||||
</mat-dialog-content>
|
||||
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" (click)="close()">Abbrechen</button>
|
||||
<button mat-flat-button color="primary" type="button" (click)="submit()">
|
||||
<mat-icon>save</mat-icon>
|
||||
Speichern
|
||||
</button>
|
||||
</mat-dialog-actions>
|
||||
@@ -0,0 +1,22 @@
|
||||
.account-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px 14px;
|
||||
min-width: min(680px, calc(100vw - 64px));
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.account-form mat-form-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
mat-dialog-actions {
|
||||
padding: 12px 24px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.account-form {
|
||||
grid-template-columns: 1fr;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
ReactiveFormsModule,
|
||||
Validators,
|
||||
} from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import {
|
||||
MAT_DIALOG_DATA,
|
||||
MatDialogModule,
|
||||
MatDialogRef,
|
||||
} from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import type {
|
||||
AccountPayload,
|
||||
AccountProfile,
|
||||
AccountRole,
|
||||
CreateAccountPayload,
|
||||
OrganizationProfile,
|
||||
} from '../../shared/services/account-management.service';
|
||||
|
||||
export type AccountDialogMode = 'create' | 'edit';
|
||||
|
||||
export interface AccountDialogData {
|
||||
mode: AccountDialogMode;
|
||||
account?: AccountProfile;
|
||||
organizations: OrganizationProfile[];
|
||||
canSelectOrganization: boolean;
|
||||
roles: AccountRole[];
|
||||
}
|
||||
|
||||
export type AccountDialogResult =
|
||||
| { mode: 'create'; payload: CreateAccountPayload }
|
||||
| { mode: 'edit'; accountId: string; payload: AccountPayload };
|
||||
|
||||
@Component({
|
||||
selector: 'app-account-dialog',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
],
|
||||
templateUrl: './account-dialog.component.html',
|
||||
styleUrl: './account-dialog.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class AccountDialogComponent {
|
||||
private readonly dialogRef =
|
||||
inject<
|
||||
MatDialogRef<AccountDialogComponent, AccountDialogResult | undefined>
|
||||
>(MatDialogRef);
|
||||
protected readonly data = inject<AccountDialogData>(MAT_DIALOG_DATA);
|
||||
|
||||
protected readonly form = new FormGroup({
|
||||
email: new FormControl<string>(this.data.account?.email ?? '', [
|
||||
Validators.required,
|
||||
Validators.email,
|
||||
]),
|
||||
name: new FormControl<string>(this.data.account?.name ?? '', [
|
||||
Validators.required,
|
||||
]),
|
||||
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [
|
||||
Validators.required,
|
||||
]),
|
||||
organizationId: new FormControl<string>(
|
||||
this.data.account?.organization_id ??
|
||||
(this.data.organizations.length === 1
|
||||
? this.data.organizations[0].id
|
||||
: ''),
|
||||
[Validators.required],
|
||||
),
|
||||
password: new FormControl<string>('', [
|
||||
...(this.data.mode === 'create' ? [Validators.required] : []),
|
||||
Validators.minLength(8),
|
||||
]),
|
||||
});
|
||||
|
||||
protected submit(): void {
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this.form.getRawValue();
|
||||
|
||||
if (this.data.mode === 'create') {
|
||||
this.dialogRef.close({
|
||||
mode: 'create',
|
||||
payload: {
|
||||
email: value.email ?? '',
|
||||
name: value.name ?? '',
|
||||
role: value.role ?? 'USER',
|
||||
organization_id: value.organizationId ?? '',
|
||||
password: value.password ?? '',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const account = this.data.account!;
|
||||
const payload: AccountPayload = {};
|
||||
|
||||
const email = (value.email ?? '').trim();
|
||||
const name = (value.name ?? '').trim();
|
||||
const role = value.role ?? account.role;
|
||||
const organizationId = value.organizationId ?? account.organization_id;
|
||||
const password = value.password?.trim() ?? '';
|
||||
|
||||
if (email !== account.email) {
|
||||
payload.email = email;
|
||||
}
|
||||
|
||||
if (name !== account.name) {
|
||||
payload.name = name;
|
||||
}
|
||||
|
||||
if (role !== account.role) {
|
||||
payload.role = role;
|
||||
}
|
||||
|
||||
if (password) {
|
||||
payload.password = password;
|
||||
}
|
||||
|
||||
if (
|
||||
this.data.canSelectOrganization &&
|
||||
organizationId &&
|
||||
organizationId !== account.organization_id
|
||||
) {
|
||||
payload.organization_id = organizationId;
|
||||
}
|
||||
|
||||
this.dialogRef.close({
|
||||
mode: 'edit',
|
||||
accountId: account.id,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
protected close(): void {
|
||||
this.dialogRef.close(undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<section class="accounts-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>Accounts</h1>
|
||||
<p>Account-Zugänge verwalten, Rollen setzen und Impersonation starten.</p>
|
||||
</div>
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
(click)="startCreate()">
|
||||
<mat-icon>person_add</mat-icon>
|
||||
Neuer Account
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<form class="filters" [formGroup]="filterForm" (ngSubmit)="applyFilters()">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Name oder E-Mail</mat-label>
|
||||
<input matInput formControlName="search" />
|
||||
</mat-form-field>
|
||||
|
||||
@if (credentialService.isEffectiveSuperAdmin()) {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Organisation</mat-label>
|
||||
<mat-select formControlName="organizationId">
|
||||
<mat-option value="">Alle Organisationen</mat-option>
|
||||
@for (organization of organizations; track organization.id) {
|
||||
<mat-option [value]="organization.id">
|
||||
{{ organization.name }}
|
||||
</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
|
||||
<div class="filter-actions">
|
||||
<button mat-flat-button color="primary" type="submit">
|
||||
<mat-icon>search</mat-icon>
|
||||
Suchen
|
||||
</button>
|
||||
<button mat-button type="button" (click)="resetFilters()">
|
||||
Zurücksetzen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section class="table-panel">
|
||||
<div class="table-header">
|
||||
<strong>{{ total }} Accounts</strong>
|
||||
@if (isLoading) {
|
||||
<span>Wird geladen...</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>E-Mail</th>
|
||||
<th>Organisation</th>
|
||||
<th>Rolle</th>
|
||||
<th>Status</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (account of accounts; track account.id) {
|
||||
<tr [class.deleted]="account.deleted">
|
||||
<td>
|
||||
<button
|
||||
class="link-button"
|
||||
type="button"
|
||||
(click)="startEdit(account)">
|
||||
{{ account.name }}
|
||||
</button>
|
||||
</td>
|
||||
<td>{{ account.email }}</td>
|
||||
<td>{{ account.organization_name }}</td>
|
||||
<td>
|
||||
<span class="role">{{ account.role }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="status" [class.status--deleted]="account.deleted">
|
||||
{{ account.deleted ? 'deleted' : 'active' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
(click)="startEdit(account)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Impersonate"
|
||||
[disabled]="!canImpersonate(account)"
|
||||
(click)="impersonate(account)">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="account.is_current || account.deleted"
|
||||
(click)="deleteAccount(account)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr>
|
||||
<td colspan="6" class="empty">Keine Accounts gefunden.</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination">
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[disabled]="!canPageBack"
|
||||
(click)="loadAccounts(page - 1)">
|
||||
<mat-icon>chevron_left</mat-icon>
|
||||
Zurück
|
||||
</button>
|
||||
<span>Seite {{ page + 1 }}</span>
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[disabled]="!canPageForward"
|
||||
(click)="loadAccounts(page + 1)">
|
||||
Weiter
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
@@ -0,0 +1,147 @@
|
||||
.accounts-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.page-header,
|
||||
.filters,
|
||||
.table-header,
|
||||
.pagination,
|
||||
.row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
color: #64748b;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.filters {
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filters mat-form-field {
|
||||
width: min(320px, 100%);
|
||||
}
|
||||
|
||||
.filter-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.table-panel {
|
||||
border: 1px solid #d7dde6;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.table-header {
|
||||
justify-content: space-between;
|
||||
padding: 16px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.table-header span {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 12px 16px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #edf1f7;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
th {
|
||||
color: #475569;
|
||||
font-weight: 700;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
tr.deleted {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #1d4ed8;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.role,
|
||||
.status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
background: #eef2ff;
|
||||
color: #3730a3;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.status--deleted {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: #64748b;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.accounts-page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||
import { Router } from '@angular/router';
|
||||
import { finalize } from 'rxjs';
|
||||
import { AccountManagementService } from '../../shared/services/account-management.service';
|
||||
import type {
|
||||
AccountProfile,
|
||||
AccountRole,
|
||||
OrganizationProfile,
|
||||
} from '../../shared/services/account-management.service';
|
||||
import { CredentialService } from '../../shared/services/credential.service';
|
||||
import type {
|
||||
AccountDialogComponent,
|
||||
AccountDialogResult,
|
||||
} from './account-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-accounts',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
MatSnackBarModule,
|
||||
MatDialogModule,
|
||||
],
|
||||
templateUrl: './accounts.component.html',
|
||||
styleUrl: './accounts.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class AccountsComponent implements OnInit {
|
||||
private readonly accountService = inject(AccountManagementService);
|
||||
protected readonly credentialService = inject(CredentialService);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly router = inject(Router);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
|
||||
protected get availableRoles(): AccountRole[] {
|
||||
if (this.credentialService.isEffectiveSuperAdmin()) {
|
||||
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
|
||||
}
|
||||
|
||||
return ['MANAGER', 'USER'];
|
||||
}
|
||||
protected accounts: AccountProfile[] = [];
|
||||
protected organizations: OrganizationProfile[] = [];
|
||||
protected total = 0;
|
||||
protected page = 0;
|
||||
protected readonly pageSize = 10;
|
||||
protected isLoading = false;
|
||||
|
||||
protected filterForm = new FormGroup({
|
||||
search: new FormControl<string>(''),
|
||||
organizationId: new FormControl<string>(''),
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadOrganizations();
|
||||
this.loadAccounts();
|
||||
}
|
||||
|
||||
protected loadAccounts(page = this.page): void {
|
||||
this.page = page;
|
||||
this.isLoading = true;
|
||||
this.accountService
|
||||
.listAccounts({
|
||||
page: this.page,
|
||||
pageSize: this.pageSize,
|
||||
search: this.filterForm.controls.search.value?.trim() || undefined,
|
||||
organizationId:
|
||||
this.filterForm.controls.organizationId.value || undefined,
|
||||
})
|
||||
.pipe(finalize(() => (this.isLoading = false)))
|
||||
.subscribe({
|
||||
next: (result) => {
|
||||
this.accounts = result.items;
|
||||
this.total = result.total;
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open('Accounts konnten nicht geladen werden.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected loadOrganizations(): void {
|
||||
this.accountService.listOrganizations().subscribe({
|
||||
next: (organizations) => {
|
||||
this.organizations = organizations;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected applyFilters(): void {
|
||||
this.loadAccounts(0);
|
||||
}
|
||||
|
||||
protected resetFilters(): void {
|
||||
this.filterForm.reset({ search: '', organizationId: '' });
|
||||
this.loadAccounts(0);
|
||||
}
|
||||
|
||||
protected startCreate(): void {
|
||||
this.openAccountDialog({ mode: 'create' });
|
||||
}
|
||||
|
||||
protected startEdit(account: AccountProfile): void {
|
||||
this.openAccountDialog({ mode: 'edit', account });
|
||||
}
|
||||
|
||||
private saveDialogResult(result: AccountDialogResult): void {
|
||||
const request =
|
||||
result.mode === 'create'
|
||||
? this.accountService.createAccount(result.payload)
|
||||
: this.accountService.updateAccount(result.accountId, result.payload);
|
||||
|
||||
request.subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Account wurde gespeichert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadAccounts(0);
|
||||
},
|
||||
error: (error) => {
|
||||
const message =
|
||||
error.status === 409
|
||||
? 'Diese E-Mail-Adresse wird bereits verwendet.'
|
||||
: 'Account konnte nicht gespeichert werden.';
|
||||
this.snackBar.open(message, 'OK', { duration: 5000 });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private openAccountDialog(data: {
|
||||
mode: 'create' | 'edit';
|
||||
account?: AccountProfile;
|
||||
}): void {
|
||||
import('./account-dialog.component').then(({ AccountDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open<
|
||||
AccountDialogComponent,
|
||||
{
|
||||
mode: 'create' | 'edit';
|
||||
account?: AccountProfile;
|
||||
organizations: OrganizationProfile[];
|
||||
canSelectOrganization: boolean;
|
||||
roles: AccountRole[];
|
||||
},
|
||||
AccountDialogResult | undefined
|
||||
>(AccountDialogComponent, {
|
||||
width: '760px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
data: {
|
||||
...data,
|
||||
organizations: this.organizations,
|
||||
canSelectOrganization:
|
||||
this.credentialService.isEffectiveSuperAdmin(),
|
||||
roles: this.availableRoles,
|
||||
},
|
||||
});
|
||||
|
||||
dialogRef.afterClosed().subscribe((result) => {
|
||||
if (result) {
|
||||
this.saveDialogResult(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected deleteAccount(account: AccountProfile): void {
|
||||
if (account.is_current) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.accountService.deleteAccount(account.id).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Account wurde deaktiviert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadAccounts();
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected impersonate(account: AccountProfile): void {
|
||||
if (!this.canImpersonate(account)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.credentialService.impersonateAccount(account.id).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
|
||||
duration: 4000,
|
||||
});
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open(
|
||||
'Impersonation konnte nicht gestartet werden.',
|
||||
'OK',
|
||||
{
|
||||
duration: 5000,
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected get canPageBack(): boolean {
|
||||
return this.page > 0;
|
||||
}
|
||||
|
||||
protected get canPageForward(): boolean {
|
||||
return (this.page + 1) * this.pageSize < this.total;
|
||||
}
|
||||
|
||||
protected canImpersonate(account: AccountProfile): boolean {
|
||||
if (account.is_current || account.deleted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.credentialService.isEffectiveSuperAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
this.credentialService.isEffectiveAdmin() &&
|
||||
(account.role === 'MANAGER' || account.role === 'USER')
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<section class="organizations-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>Organisationen</h1>
|
||||
<p>Mandanten, externe Institutions-IDs und Status verwalten.</p>
|
||||
</div>
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
(click)="startCreate()">
|
||||
<mat-icon>add_business</mat-icon>
|
||||
Neue Organisation
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section class="table-panel">
|
||||
<div class="table-header">
|
||||
<strong>{{ total }} Organisationen</strong>
|
||||
@if (isLoading) {
|
||||
<span>Wird geladen...</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Externe Institutions-ID</th>
|
||||
<th>Mitglieder</th>
|
||||
<th>Status</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (organization of organizations; track organization.id) {
|
||||
<tr [class.deleted]="organization.deleted">
|
||||
<td>
|
||||
<button
|
||||
class="link-button"
|
||||
type="button"
|
||||
(click)="startEdit(organization)">
|
||||
{{ organization.name }}
|
||||
</button>
|
||||
</td>
|
||||
<td>{{ organization.other_inst_id || '–' }}</td>
|
||||
<td>{{ organization.member_count }}</td>
|
||||
<td>
|
||||
<span
|
||||
class="status"
|
||||
[class.status--deleted]="organization.deleted">
|
||||
{{ organization.deleted ? 'deleted' : 'active' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
(click)="startEdit(organization)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="organization.deleted"
|
||||
(click)="deleteOrganization(organization)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr>
|
||||
<td colspan="6" class="empty">Keine Organisationen gefunden.</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination">
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[disabled]="!canPageBack"
|
||||
(click)="loadOrganizations(page - 1)">
|
||||
<mat-icon>chevron_left</mat-icon>
|
||||
Zurück
|
||||
</button>
|
||||
<span>Seite {{ page + 1 }}</span>
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[disabled]="!canPageForward"
|
||||
(click)="loadOrganizations(page + 1)">
|
||||
Weiter
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
@@ -0,0 +1,130 @@
|
||||
.organizations-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.page-header,
|
||||
.table-header,
|
||||
.pagination,
|
||||
.row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
h1,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-header p,
|
||||
.table-header span {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.table-panel {
|
||||
overflow: hidden;
|
||||
border: 1px solid #d7dde6;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.table-header {
|
||||
justify-content: space-between;
|
||||
padding: 16px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 12px 16px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #edf1f7;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
th {
|
||||
color: #475569;
|
||||
font-weight: 700;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
tr.deleted {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.identifier {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #1d4ed8;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status--deleted {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: #64748b;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.organizations-page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { finalize } from 'rxjs';
|
||||
import {
|
||||
OrganizationManagementService,
|
||||
OrganizationProfile,
|
||||
} from '../../shared/services/organization-management.service';
|
||||
import type {
|
||||
OrganizationDialogComponent,
|
||||
OrganizationDialogData,
|
||||
OrganizationDialogResult,
|
||||
} from './organization-dialog/organization-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-organizations',
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatButtonModule,
|
||||
MatDialogModule,
|
||||
MatIconModule,
|
||||
MatSnackBarModule,
|
||||
],
|
||||
templateUrl: './organizations.component.html',
|
||||
styleUrl: './organizations.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class OrganizationsComponent implements OnInit {
|
||||
private readonly organizationService = inject(OrganizationManagementService);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
|
||||
protected organizations: OrganizationProfile[] = [];
|
||||
protected total = 0;
|
||||
protected page = 0;
|
||||
protected readonly pageSize = 10;
|
||||
protected isLoading = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadOrganizations();
|
||||
}
|
||||
|
||||
protected loadOrganizations(page = this.page): void {
|
||||
this.page = page;
|
||||
this.isLoading = true;
|
||||
this.organizationService
|
||||
.getOrganizations(page, this.pageSize)
|
||||
.pipe(finalize(() => (this.isLoading = false)))
|
||||
.subscribe({
|
||||
next: (result) => {
|
||||
this.organizations = result.items;
|
||||
this.total = result.total;
|
||||
},
|
||||
error: () => this.showError('Organisationen konnten nicht geladen werden.'),
|
||||
});
|
||||
}
|
||||
|
||||
protected startCreate(): void {
|
||||
this.openDialog({ mode: 'create' });
|
||||
}
|
||||
|
||||
protected startEdit(organization: OrganizationProfile): void {
|
||||
this.openDialog({ mode: 'edit', organization });
|
||||
}
|
||||
|
||||
protected deleteOrganization(organization: OrganizationProfile): void {
|
||||
if (organization.deleted) return;
|
||||
|
||||
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
|
||||
({ ConfirmationDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
|
||||
data: {
|
||||
title: 'Organisation deaktivieren',
|
||||
message: `Möchtest Du die Organisation „${organization.name}“ wirklich deaktivieren?`,
|
||||
confirmText: 'Deaktivieren',
|
||||
cancelText: 'Abbrechen',
|
||||
},
|
||||
});
|
||||
|
||||
dialogRef.componentInstance.confirmDelete.subscribe(() => {
|
||||
this.softDeleteOrganization(organization);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private softDeleteOrganization(organization: OrganizationProfile): void {
|
||||
this.organizationService.deleteOrganization(organization.id).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Organisation wurde deaktiviert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadOrganizations();
|
||||
},
|
||||
error: () => this.showError('Organisation konnte nicht deaktiviert werden.'),
|
||||
});
|
||||
}
|
||||
|
||||
protected get canPageBack(): boolean {
|
||||
return this.page > 0;
|
||||
}
|
||||
|
||||
protected get canPageForward(): boolean {
|
||||
return (this.page + 1) * this.pageSize < this.total;
|
||||
}
|
||||
|
||||
private openDialog(data: OrganizationDialogData): void {
|
||||
import('./organization-dialog/organization-dialog.component').then(
|
||||
({ OrganizationDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open<
|
||||
OrganizationDialogComponent,
|
||||
OrganizationDialogData,
|
||||
OrganizationDialogResult | undefined
|
||||
>(OrganizationDialogComponent, {
|
||||
width: '620px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
data,
|
||||
});
|
||||
|
||||
dialogRef.afterClosed().subscribe((result) => {
|
||||
if (result) this.save(result);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private save(result: OrganizationDialogResult): void {
|
||||
const request =
|
||||
result.mode === 'create'
|
||||
? this.organizationService.createOrganization(result.payload)
|
||||
: this.organizationService.updateOrganization(
|
||||
result.organizationId,
|
||||
result.payload,
|
||||
);
|
||||
|
||||
request.subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Organisation wurde gespeichert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadOrganizations(0);
|
||||
},
|
||||
error: (error) =>
|
||||
this.showError(
|
||||
error.status === 409
|
||||
? 'Eine Organisation mit diesem Namen existiert bereits.'
|
||||
: 'Organisation konnte nicht gespeichert werden.',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
private showError(message: string): void {
|
||||
this.snackBar.open(message, 'OK', { duration: 5000 });
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
ViewChild,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router';
|
||||
import {
|
||||
@@ -37,7 +36,12 @@ import {
|
||||
switchMap,
|
||||
} from 'rxjs';
|
||||
|
||||
import { Work, WorksService } from '../../api';
|
||||
import {
|
||||
InstitutionsService,
|
||||
TopicsService,
|
||||
Work,
|
||||
WorksService,
|
||||
} from '../../api';
|
||||
import { PaginationService } from '../../shared/services/pagination.service';
|
||||
import { createLoadError } from '../../resolvers/utils/errorHandler';
|
||||
import { ChipComponent } from '../../shared/ui/chip/chip.component';
|
||||
@@ -52,10 +56,6 @@ interface InstitutionAutocompleteOption {
|
||||
external_id?: string | null;
|
||||
}
|
||||
|
||||
interface InstitutionAutocompleteResponse {
|
||||
results?: InstitutionAutocompleteOption[] | null;
|
||||
}
|
||||
|
||||
interface TopicAutocompleteOption {
|
||||
id?: string | null;
|
||||
display_name?: string | null;
|
||||
@@ -66,10 +66,6 @@ interface TopicAutocompleteOption {
|
||||
external_id?: string | null;
|
||||
}
|
||||
|
||||
interface TopicAutocompleteResponse {
|
||||
results?: TopicAutocompleteOption[] | null;
|
||||
}
|
||||
|
||||
interface PublicationFilterQueryState {
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
@@ -184,7 +180,8 @@ export class PersonPublicationsComponent implements OnInit {
|
||||
private readonly route: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
private readonly workService: WorksService,
|
||||
private readonly httpClient: HttpClient,
|
||||
private readonly institutionsService: InstitutionsService,
|
||||
private readonly topicsService: TopicsService,
|
||||
public readonly paginationService: PaginationService,
|
||||
private readonly snackBar: MatSnackBar,
|
||||
) {}
|
||||
@@ -438,27 +435,14 @@ export class PersonPublicationsComponent implements OnInit {
|
||||
}
|
||||
|
||||
private searchInstitutions(query: string) {
|
||||
const params = new HttpParams().set('query', query).set('limit', '10');
|
||||
|
||||
const basePath = this.workService.configuration.basePath ?? '';
|
||||
return this.httpClient
|
||||
.get<InstitutionAutocompleteResponse>(
|
||||
`${basePath}/api/institutions/autocomplete`,
|
||||
{
|
||||
params,
|
||||
},
|
||||
)
|
||||
return this.institutionsService
|
||||
.autocompleteInstitutions(query, undefined, undefined, 10)
|
||||
.pipe(map((response) => response.results ?? []));
|
||||
}
|
||||
|
||||
private searchTopics(query: string) {
|
||||
const params = new HttpParams().set('query', query).set('limit', '10');
|
||||
|
||||
const basePath = this.workService.configuration.basePath ?? '';
|
||||
return this.httpClient
|
||||
.get<TopicAutocompleteResponse>(`${basePath}/api/topics/autocomplete`, {
|
||||
params,
|
||||
})
|
||||
return this.topicsService
|
||||
.autocompleteTopics(query, undefined, undefined, undefined, 10)
|
||||
.pipe(map((response) => response.results ?? []));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
|
||||
export const superAdminGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
switchMap(() => {
|
||||
if (!credentialService.isEffectiveSuperAdmin()) {
|
||||
void router.navigate(['/dashboard']);
|
||||
return of(false);
|
||||
}
|
||||
return of(true);
|
||||
}),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Configuration } from '../../api';
|
||||
|
||||
export type AccountRole = 'SUPER_ADMIN' | 'ADMIN' | 'MANAGER' | 'USER';
|
||||
|
||||
export interface AccountProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: AccountRole;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
is_current: boolean;
|
||||
is_real_account: boolean;
|
||||
is_impersonating: boolean;
|
||||
}
|
||||
|
||||
export interface AccountPage {
|
||||
items: AccountProfile[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface OrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
openalex_institution_id?: string | null;
|
||||
}
|
||||
|
||||
export interface AccountPayload {
|
||||
email?: string;
|
||||
name?: string;
|
||||
role?: AccountRole;
|
||||
organization_id?: string;
|
||||
password?: string;
|
||||
deleted?: boolean;
|
||||
}
|
||||
|
||||
export interface CreateAccountPayload {
|
||||
email: string;
|
||||
name: string;
|
||||
role: AccountRole;
|
||||
organization_id: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AccountManagementService {
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||
|
||||
getCurrentAccount(): Observable<AccountProfile> {
|
||||
return this.httpClient.get<AccountProfile>(`${this.apiBasePath}/api/accounts/me`);
|
||||
}
|
||||
|
||||
listAccounts(options: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
search?: string;
|
||||
organizationId?: string;
|
||||
}): Observable<AccountPage> {
|
||||
let params = new HttpParams()
|
||||
.set('page', options.page)
|
||||
.set('page_size', options.pageSize);
|
||||
|
||||
if (options.search) {
|
||||
params = params.set('search', options.search);
|
||||
}
|
||||
|
||||
if (options.organizationId) {
|
||||
params = params.set('organization_id', options.organizationId);
|
||||
}
|
||||
|
||||
return this.httpClient.get<AccountPage>(`${this.apiBasePath}/api/accounts`, {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
createAccount(payload: CreateAccountPayload): Observable<AccountProfile> {
|
||||
return this.httpClient.post<AccountProfile>(
|
||||
`${this.apiBasePath}/api/accounts`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
updateAccount(
|
||||
accountId: string,
|
||||
payload: AccountPayload,
|
||||
): Observable<AccountProfile> {
|
||||
return this.httpClient.put<AccountProfile>(
|
||||
`${this.apiBasePath}/api/accounts/${accountId}`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
deleteAccount(accountId: string): Observable<void> {
|
||||
return this.httpClient.delete<void>(
|
||||
`${this.apiBasePath}/api/accounts/${accountId}`,
|
||||
);
|
||||
}
|
||||
|
||||
listOrganizations(): Observable<OrganizationProfile[]> {
|
||||
return this.httpClient.get<OrganizationProfile[]>(
|
||||
`${this.apiBasePath}/api/accounts/organizations`,
|
||||
);
|
||||
}
|
||||
|
||||
private get apiBasePath(): string {
|
||||
return this.apiConfiguration?.basePath ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Configuration } from '../../api';
|
||||
|
||||
export interface OrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted: boolean;
|
||||
member_count: number;
|
||||
}
|
||||
|
||||
export interface OrganizationPage {
|
||||
items: OrganizationProfile[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface CreateOrganizationPayload {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateOrganizationPayload {
|
||||
name?: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted?: boolean;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class OrganizationManagementService {
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||
|
||||
getOrganizations(page: number, pageSize: number): Observable<OrganizationPage> {
|
||||
const params = new HttpParams()
|
||||
.set('page', page)
|
||||
.set('page_size', pageSize);
|
||||
return this.httpClient.get<OrganizationPage>(
|
||||
`${this.apiBasePath}/api/organizations`,
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
createOrganization(
|
||||
payload: CreateOrganizationPayload,
|
||||
): Observable<OrganizationProfile> {
|
||||
return this.httpClient.post<OrganizationProfile>(
|
||||
`${this.apiBasePath}/api/organizations`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
updateOrganization(
|
||||
organizationId: string,
|
||||
payload: UpdateOrganizationPayload,
|
||||
): Observable<OrganizationProfile> {
|
||||
return this.httpClient.put<OrganizationProfile>(
|
||||
`${this.apiBasePath}/api/organizations/${organizationId}`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
deleteOrganization(organizationId: string): Observable<void> {
|
||||
return this.httpClient.delete<void>(
|
||||
`${this.apiBasePath}/api/organizations/${organizationId}`,
|
||||
);
|
||||
}
|
||||
|
||||
private get apiBasePath(): string {
|
||||
return this.apiConfiguration?.basePath ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class UiFocusService {
|
||||
public blurActiveElement(): void {
|
||||
const activeElement = document.activeElement;
|
||||
|
||||
if (activeElement instanceof HTMLElement) {
|
||||
activeElement.blur();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user