Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97ba57b9a2 | ||
|
|
5a91887861 | ||
|
|
c8179d44f6 | ||
|
|
1019cedb97 | ||
|
|
4b6ad1ec3d | ||
|
|
0648e1774c | ||
|
|
b993862afb | ||
|
|
f951eba7e4 | ||
|
|
d5122a5eb7 | ||
|
|
1351264c80 | ||
|
|
7b13db6dbf | ||
|
|
b4257f2efa | ||
|
|
52a567df3e |
@@ -1,8 +1,20 @@
|
||||
{
|
||||
"organizations": [
|
||||
{
|
||||
"id": "c001beef-cafe-4000-8000-d34db33f000d",
|
||||
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||
"name": "The Super Admin Organization"
|
||||
},
|
||||
{
|
||||
"name": "Universität Duisburg-Essen",
|
||||
"openalex_instution_id": "https://openalex.org/I62318514"
|
||||
},
|
||||
{
|
||||
"name": "Ruhr-Universität Bochum",
|
||||
"openalex_instution_id": "https://openalex.org/I904495901"
|
||||
},
|
||||
{
|
||||
"name": "TU Dortmund",
|
||||
"openalex_instution_id": "https://openalex.org/I200332995"
|
||||
}
|
||||
],
|
||||
"accounts": [
|
||||
@@ -10,7 +22,7 @@
|
||||
"email": "super@admin.com",
|
||||
"password": "superadmin",
|
||||
"name": "Super Admin",
|
||||
"organization_id": "c001beef-cafe-4000-8000-d34db33f000d",
|
||||
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||
"role": "SUPER_ADMIN"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"username": "superadmin",
|
||||
"password": "superadmin",
|
||||
"email": "some_email@uni-due.de",
|
||||
"account": 0,
|
||||
"organization": 0,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": true
|
||||
},
|
||||
{
|
||||
"username": "user",
|
||||
"password": "user",
|
||||
"email": "user_email@uni-due.de",
|
||||
"account": 1,
|
||||
"organization": 1,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module contains the validation logic for
|
||||
user names and passwords.
|
||||
"""
|
||||
import typing
|
||||
import logging
|
||||
from . import model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def _get_users() -> typing.List[model.User]:
|
||||
''' Returns the list of users from the user configuration file. '''
|
||||
try:
|
||||
with open('../data/users.json') as file:
|
||||
config = model.UserFile.model_validate_json(file.read())
|
||||
return config.users
|
||||
except Exception as e:
|
||||
logger.error('Could not read user configuration file.', exc_info=e)
|
||||
return []
|
||||
|
||||
def get_user(username: str) -> typing.Optional[model.User]:
|
||||
''' Returns the user with the given username. '''
|
||||
for user in _get_users():
|
||||
if user.username == username:
|
||||
return user
|
||||
return None
|
||||
|
||||
def validate_user(username: str, password: str) -> typing.Optional[model.User]:
|
||||
''' Validates the user with the given username and password. '''
|
||||
user = get_user(username)
|
||||
if user and user.password == password:
|
||||
return user
|
||||
return None
|
||||
|
||||
def create_user(username, password, email, institution, superadmin) -> typing.Optional[model.User]:
|
||||
''' Adds a new user to the user configuration file. '''
|
||||
users = _get_users()
|
||||
if any(u.username == username for u in users):
|
||||
logger.warning("Attempt to create duplicate user: %s", username)
|
||||
return None
|
||||
|
||||
# Determine new IDs
|
||||
next_account = max((u.account for u in users), default=0) + 1
|
||||
next_org = max((u.organization for u in users), default=0) + 1
|
||||
|
||||
new_user = model.User(
|
||||
username=username,
|
||||
password=password,
|
||||
email=email,
|
||||
account=next_account,
|
||||
organization=next_org,
|
||||
organization_name=institution,
|
||||
superadmin=superadmin
|
||||
)
|
||||
|
||||
users.append(new_user)
|
||||
user_file = model.UserFile(users=users)
|
||||
try:
|
||||
with open('../data/users.json', 'w') as file:
|
||||
file.write(user_file.model_dump_json(indent=4))
|
||||
return new_user
|
||||
except Exception as e:
|
||||
logger.error('Could not write user configuration file.', exc_info=e)
|
||||
return None
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Data models for the standalone account sub-app.
|
||||
"""
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from pydantic import StrictInt
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
''' An entry in the user configuration file. '''
|
||||
username: str = Field(description="The username of the user.")
|
||||
password: str = Field(description="The password of the user.")
|
||||
email: str = Field(description="The email of the user.")
|
||||
account: StrictInt = Field(description="The account id of the user.")
|
||||
organization: StrictInt = Field(description="The organization id of the user.")
|
||||
organization_name: str = Field(description="The organization name of the user.")
|
||||
superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.")
|
||||
|
||||
|
||||
class UserFile(BaseModel):
|
||||
''' The data model for the file containing the user configuration. '''
|
||||
users: List[User] = Field(default=[], description="The list of users.")
|
||||
|
||||
|
||||
class AuthAccount(BaseModel):
|
||||
i: int
|
||||
l: str
|
||||
o: int
|
||||
e: str
|
||||
on: str
|
||||
|
||||
|
||||
class AuthScope(BaseModel):
|
||||
t: str
|
||||
a: AuthAccount
|
||||
d: Optional[int] = None
|
||||
r: List[str] = []
|
||||
|
||||
|
||||
class IdentityGrant(BaseModel):
|
||||
token_type: str
|
||||
access_token: str
|
||||
expires_in: int
|
||||
scope: AuthScope
|
||||
|
||||
|
||||
class AccessGrant(BaseModel):
|
||||
token_type: str
|
||||
access_token: str
|
||||
expires_in: int
|
||||
scope: AuthScope
|
||||
refresh_token: str
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the security-related code.
|
||||
"""
|
||||
from typing import Optional
|
||||
from typing import Dict
|
||||
from typing import Literal
|
||||
import jwt
|
||||
import time
|
||||
import logging
|
||||
from .. import config
|
||||
from .. import security
|
||||
from . import model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def principal(id_token: str) -> Optional[security.Principal]:
|
||||
''' Extracts the principal from the id token. '''
|
||||
return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH'])
|
||||
|
||||
def id_token(user: model.User, exp: int) -> str:
|
||||
''' Creates a new identity token for the specified user. '''
|
||||
return _encode(_payload(user, 'ID', exp))
|
||||
|
||||
def access_token(user: model.User, exp: int) -> str:
|
||||
''' Creates a new access token for the specified user. '''
|
||||
return _encode(_payload(user, 'ACCESS', exp))
|
||||
|
||||
def refresh_token(user: model.User, exp: int) -> str:
|
||||
''' Creates a new refresh token for the specified user. '''
|
||||
return _encode(_payload(user, 'REFRESH', exp))
|
||||
|
||||
def _encode(payload: Dict[str, any]) -> str:
|
||||
''' Creates a valid web token that encodes the contents with the symmetric key. '''
|
||||
headers = {
|
||||
"kid" : "sym",
|
||||
}
|
||||
return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers)
|
||||
|
||||
def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str:
|
||||
''' Creates the payload of the token for the specified user and token type. '''
|
||||
now = int(time.time())
|
||||
roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ]
|
||||
payload = {
|
||||
"iss" : "my-app",
|
||||
"exp" : now + exp,
|
||||
"iat" : now,
|
||||
"nbf" : now,
|
||||
"inse" : {
|
||||
"t" : type,
|
||||
"a" : {
|
||||
"i" : user.account,
|
||||
"l" : user.username,
|
||||
"o" : user.organization
|
||||
},
|
||||
"d" : None,
|
||||
"r" : roles if type == 'ACCESS' else []
|
||||
}
|
||||
}
|
||||
return payload
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Standalone account service that provides identity and access
|
||||
token endpoints for authentication.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import fastapi
|
||||
import typing
|
||||
from . import logic
|
||||
from . import model
|
||||
from . import security
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_403_FORBIDDEN
|
||||
from starlette.status import HTTP_200_OK
|
||||
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = fastapi.APIRouter(
|
||||
prefix="/inse-account",
|
||||
tags=["INSE Account Service"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/auth/id",
|
||||
operation_id="getIdentityGrant",
|
||||
responses={
|
||||
HTTP_200_OK: {"model": model.IdentityGrant},
|
||||
HTTP_400_BAD_REQUEST: {
|
||||
"model": None,
|
||||
"description": "Invalid request parameters.",
|
||||
},
|
||||
HTTP_403_FORBIDDEN: {
|
||||
"model": None,
|
||||
"description": "Account login not successful.",
|
||||
},
|
||||
HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"model": None,
|
||||
"description": "Token generation failed.",
|
||||
},
|
||||
},
|
||||
)
|
||||
async def get_identity_grant(
|
||||
username: typing.Annotated[str, fastapi.Form()],
|
||||
password: typing.Annotated[str, fastapi.Form()],
|
||||
):
|
||||
user = logic.validate_user(username, password)
|
||||
if user is None:
|
||||
logger.info("Invalid login attempt (%s).", username)
|
||||
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
try:
|
||||
exp = 12 * 60 * 60
|
||||
token = security.id_token(user, exp=exp)
|
||||
account = model.AuthAccount(
|
||||
i=user.account,
|
||||
l=user.username,
|
||||
o=user.organization,
|
||||
e=user.email,
|
||||
on=user.organization_name,
|
||||
)
|
||||
scope = model.AuthScope(t="ID", a=account, d=None, r=[])
|
||||
grant = model.IdentityGrant(
|
||||
token_type="bearer", access_token=token, expires_in=exp, scope=scope
|
||||
)
|
||||
logger.info("Identity token generated (%s).", username)
|
||||
return grant
|
||||
except Exception as e:
|
||||
logger.error("Token generation failed (%s).", username, exc_info=e)
|
||||
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/auth/access",
|
||||
operation_id="getAccessGrant",
|
||||
responses={
|
||||
HTTP_200_OK: {"model": model.AccessGrant},
|
||||
HTTP_400_BAD_REQUEST: {
|
||||
"model": None,
|
||||
"description": "Invalid request parameters.",
|
||||
},
|
||||
HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."},
|
||||
HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"model": None,
|
||||
"description": "Token generation failed.",
|
||||
},
|
||||
},
|
||||
)
|
||||
async def get_access_grant(
|
||||
secret: typing.Annotated[str, fastapi.Form()],
|
||||
account: typing.Annotated[int, fastapi.Form()],
|
||||
organization: typing.Annotated[int, fastapi.Form()],
|
||||
):
|
||||
principal = security.principal(secret)
|
||||
if principal is None:
|
||||
logger.info("Invalid access attempt without principal (%s).", account)
|
||||
raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST)
|
||||
user = logic.get_user(principal.account.login)
|
||||
if user is None:
|
||||
logger.info("Invalid access attempt without user (%s).", account)
|
||||
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
if user.organization != organization or user.account != account:
|
||||
logger.info("Invalid personation attempt (%s).", account)
|
||||
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
try:
|
||||
exp = 10 * 60
|
||||
token = security.access_token(user, exp=exp)
|
||||
refresh = security.refresh_token(user, exp=exp)
|
||||
auth_account = model.AuthAccount(
|
||||
i=user.account,
|
||||
l=user.username,
|
||||
o=user.organization,
|
||||
e=user.email,
|
||||
on=user.organization_name,
|
||||
)
|
||||
scope = model.AuthScope(
|
||||
t="ACCESS",
|
||||
a=auth_account,
|
||||
d=None,
|
||||
r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"],
|
||||
)
|
||||
grant = model.AccessGrant(
|
||||
token_type="bearer",
|
||||
access_token=token,
|
||||
expires_in=exp,
|
||||
scope=scope,
|
||||
refresh_token=refresh,
|
||||
)
|
||||
logger.info("Access token generated (%s).", user.username)
|
||||
return grant
|
||||
except Exception as e:
|
||||
logger.error("Token generation failed (%s).", user.username, exc_info=e)
|
||||
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/create",
|
||||
operation_id="createUser",
|
||||
responses={
|
||||
HTTP_200_OK: {"model": model.User},
|
||||
HTTP_400_BAD_REQUEST: {
|
||||
"model": None,
|
||||
"description": "User creation failed (e.g. duplicate username).",
|
||||
},
|
||||
HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"model": None,
|
||||
"description": "Internal server error.",
|
||||
},
|
||||
},
|
||||
)
|
||||
async def create_user(
|
||||
username: typing.Annotated[str, fastapi.Body()],
|
||||
password: typing.Annotated[str, fastapi.Body()],
|
||||
email: typing.Annotated[str, fastapi.Body()],
|
||||
institution: typing.Annotated[str, fastapi.Body()],
|
||||
superadmin: typing.Annotated[bool, fastapi.Body()] = False,
|
||||
):
|
||||
user = logic.create_user(username, password, email, institution, superadmin)
|
||||
if user is None:
|
||||
logger.info("User creation failed for (%s).", username)
|
||||
raise fastapi.HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="User creation failed. Username might already exist."
|
||||
)
|
||||
logger.info("User created successfully (%s).", username)
|
||||
return user
|
||||
@@ -0,0 +1,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)
|
||||
@@ -36,7 +36,10 @@ class Organization(Durable, table=True):
|
||||
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True, nullable=False, description="The name of the organization."
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The unique name of the organization.",
|
||||
)
|
||||
openalex_institution_id: str | None = Field(
|
||||
default=None,
|
||||
@@ -143,6 +146,11 @@ class Token(BaseModel):
|
||||
nullable=False,
|
||||
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||
)
|
||||
raw_token: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The raw token string.",
|
||||
)
|
||||
|
||||
|
||||
class IdToken(Token):
|
||||
@@ -189,3 +197,16 @@ class RefreshToken(AccessToken):
|
||||
const=True,
|
||||
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||
)
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
id_token: IdToken = Field(description="The ID token issued upon successful login.")
|
||||
|
||||
|
||||
class AccessResponse(BaseModel):
|
||||
access_token: AccessToken = Field(
|
||||
description="The access token issued upon successful authentication."
|
||||
)
|
||||
refresh_token: RefreshToken = Field(
|
||||
description="The refresh token issued alongside the access token for obtaining new access tokens."
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Annotated, Dict
|
||||
from typing import Annotated
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Response, status
|
||||
@@ -9,7 +9,13 @@ from inse.tags import Tags
|
||||
|
||||
import inse.auth.service as auth_service
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.auth.model import AccessToken, IdToken, RefreshToken
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
IdToken,
|
||||
LoginResponse,
|
||||
RefreshToken,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -52,7 +58,7 @@ async def login(
|
||||
email_code: Annotated[
|
||||
str, Body(embed=True, description="One-time code sent to user's email")
|
||||
],
|
||||
):
|
||||
) -> LoginResponse:
|
||||
return auth_service.login(
|
||||
session=session, response=response, account_id=account_id, email_code=email_code
|
||||
)
|
||||
@@ -75,7 +81,7 @@ async def get_action_tokens(
|
||||
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||
],
|
||||
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||
) -> Dict[str, str]:
|
||||
) -> AccessResponse:
|
||||
logger.debug(
|
||||
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||
real_account_id,
|
||||
@@ -105,7 +111,7 @@ async def refresh_access_token(
|
||||
refresh_token: Annotated[
|
||||
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||
],
|
||||
) -> str:
|
||||
) -> AccessToken:
|
||||
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
import uuid
|
||||
import logging
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from typing import Annotated, Any, Dict, Literal, Optional
|
||||
|
||||
import jwt
|
||||
@@ -14,9 +12,11 @@ from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatc
|
||||
from fastapi import Depends, HTTPException, Request, Response, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
Account,
|
||||
IdToken,
|
||||
LoginResponse,
|
||||
Organization,
|
||||
RefreshToken,
|
||||
Secret,
|
||||
@@ -26,6 +26,7 @@ from inse.auth.model import (
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
from sqlmodel import Session, select, func
|
||||
from inse.auth.email_service import send_email
|
||||
|
||||
ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days
|
||||
REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
@@ -36,8 +37,8 @@ OTK_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||
EFFECTIVE_ROLE_KEY = "effective_role"
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
|
||||
EPOCH_KEY = "epoch"
|
||||
ORGANIZATION_ID_KEY = "organization_id"
|
||||
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
|
||||
|
||||
ID_FP_COOKIE_KEY = "_Secure-Fgp-ID"
|
||||
@@ -80,9 +81,11 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
data = json.loads(file.read())
|
||||
data: Dict[str, Any] = json.loads(file.read())
|
||||
for organization_data in data.get("organizations", []):
|
||||
organization_id = uuid.UUID(organization_data["id"])
|
||||
organization_id = organization_data.get("id")
|
||||
if organization_id is not None:
|
||||
organization_id = uuid.UUID(organization_id)
|
||||
organization_name = organization_data["name"]
|
||||
organization = Organization(id=organization_id, name=organization_name)
|
||||
session.add(organization)
|
||||
@@ -142,6 +145,7 @@ def _verify_password(password: str, password_hash: str) -> bool:
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def request_otk(session: Session, email: str, password: str):
|
||||
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
|
||||
|
||||
@@ -205,24 +209,30 @@ def request_otk(session: Session, email: str, password: str):
|
||||
|
||||
session.commit()
|
||||
|
||||
if settings.environment == "prod":
|
||||
logger.info(
|
||||
"Saved OTK for account %s with expiration at %s",
|
||||
account.id,
|
||||
expires_at,
|
||||
if settings.send_otk_email:
|
||||
send_email(
|
||||
recipient=account.email,
|
||||
subject="Your SmartGUIDE login code",
|
||||
body=f"Your login code is: {otk_code}",
|
||||
smtp_server=settings.smtp_server,
|
||||
smtp_port=settings.smtp_port,
|
||||
sender=settings.smtp_sender,
|
||||
username=settings.smtp_username,
|
||||
password=settings.smtp_password,
|
||||
use_tls=settings.smtp_use_tls,
|
||||
)
|
||||
logger.info("Sent OTK email for account %s", account.id)
|
||||
elif settings.environment == "dev":
|
||||
logger.info("OTK code for account %s: %s", account.id, otk_code)
|
||||
else:
|
||||
logger.info(
|
||||
"OTK code for account %s: %s, expires at %s",
|
||||
account.id,
|
||||
otk_code,
|
||||
expires_at,
|
||||
)
|
||||
logger.info("OTK generated for account %s", account.id)
|
||||
|
||||
return {"status": "ok", "account_id": str(account.id)}
|
||||
|
||||
|
||||
def login(session: Session, response: Response, account_id: uuid.UUID, email_code: str):
|
||||
def login(
|
||||
session: Session, response: Response, account_id: uuid.UUID, email_code: str
|
||||
) -> LoginResponse:
|
||||
"""Login using a one-time key (OTK) sent to the user's email. Validates the OTK and generates an ID token for the user.
|
||||
|
||||
Args:
|
||||
@@ -234,6 +244,9 @@ def login(session: Session, response: Response, account_id: uuid.UUID, email_cod
|
||||
Raises:
|
||||
HTTPException: If the code is invalid or expired.
|
||||
HTTPException: If the account is not active.
|
||||
|
||||
Returns:
|
||||
LoginResponse: The response containing the ID token issued upon successful login.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
@@ -246,7 +259,18 @@ def login(session: Session, response: Response, account_id: uuid.UUID, email_cod
|
||||
).first()
|
||||
|
||||
if not settings.skip_otk_validation:
|
||||
if secret is None or secret.expires_at <= now:
|
||||
if secret is None:
|
||||
logger.warning("Login failed: invalid or expired code %s", email_code)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired code",
|
||||
)
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
|
||||
if secret_expires <= now:
|
||||
logger.warning("Login failed: invalid or expired code %s", email_code)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -282,7 +306,7 @@ def login(session: Session, response: Response, account_id: uuid.UUID, email_cod
|
||||
|
||||
session.commit()
|
||||
|
||||
return {"id_token": id_token}
|
||||
return LoginResponse(id_token=id_token)
|
||||
|
||||
|
||||
def _get_current_user_access_token_payload(
|
||||
@@ -319,8 +343,11 @@ def _get_current_user_access_token_payload(
|
||||
),
|
||||
epoch=access_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_organization_id=uuid.UUID(access_token_payload[ORGANIZATION_ID_KEY]),
|
||||
effective_organization_id=uuid.UUID(
|
||||
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||
),
|
||||
user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY],
|
||||
raw_token=token,
|
||||
)
|
||||
|
||||
|
||||
@@ -356,8 +383,11 @@ def _get_current_user_refresh_token_payload(
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_organization_id=uuid.UUID(refresh_token_payload[ORGANIZATION_ID_KEY]),
|
||||
effective_organization_id=uuid.UUID(
|
||||
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||
),
|
||||
user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY],
|
||||
raw_token=token,
|
||||
)
|
||||
|
||||
logger.debug("Extracted refresh token payload: %s", refresh_token)
|
||||
@@ -378,7 +408,7 @@ def _get_current_user_id_token_payload(
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the ID token.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The verified ID token payload.
|
||||
IdToken: The verified ID token payload.
|
||||
"""
|
||||
logger.debug(
|
||||
"Verifying ID token for request %s with credentials %s",
|
||||
@@ -403,6 +433,7 @@ def _get_current_user_id_token_payload(
|
||||
),
|
||||
epoch=id_token_payload[EPOCH_KEY],
|
||||
user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY],
|
||||
raw_token=token,
|
||||
)
|
||||
|
||||
|
||||
@@ -507,11 +538,12 @@ def _is_valid_impersonation(
|
||||
]:
|
||||
return True # Admins can impersonate managers and users within the same organization
|
||||
|
||||
if (
|
||||
real_account.role == UserRole.MANAGER
|
||||
and effective_account.role == UserRole.USER
|
||||
):
|
||||
return True # Managers can impersonate users within the same organization
|
||||
# if (
|
||||
# real_account.role == UserRole.MANAGER
|
||||
# and effective_account.role == UserRole.USER
|
||||
# ):
|
||||
# return True # Managers can impersonate users within the same organization
|
||||
# # They can't tho?
|
||||
|
||||
return False
|
||||
|
||||
@@ -522,7 +554,7 @@ def get_access_token(
|
||||
id_token: IdToken,
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: Optional[uuid.UUID] = None,
|
||||
) -> Dict[str, Any]:
|
||||
) -> AccessResponse:
|
||||
"""Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies.
|
||||
|
||||
Args:
|
||||
@@ -537,7 +569,7 @@ def get_access_token(
|
||||
HTTPException: If impersonation is not allowed.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: A dictionary containing the generated access and refresh tokens.
|
||||
AccessResponse: An object containing the generated access and refresh tokens.
|
||||
"""
|
||||
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
@@ -547,7 +579,13 @@ def get_access_token(
|
||||
detail="Real account ID does not match ID token",
|
||||
)
|
||||
|
||||
if effective_account_id:
|
||||
# The new frontend explicitly sends the real account as the effective account.
|
||||
# That is self-access, not impersonation; otherwise normal login fails for users
|
||||
# because they do not have impersonation permissions.
|
||||
if effective_account_id is None:
|
||||
effective_account_id = real_account_id
|
||||
|
||||
elif effective_account_id != real_account_id:
|
||||
if not _is_valid_impersonation(
|
||||
session=session,
|
||||
real_account_id=real_account_id,
|
||||
@@ -557,9 +595,6 @@ def get_access_token(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Impersonation not allowed",
|
||||
)
|
||||
else:
|
||||
# No impersonation, set effective_account_id to real_account_id
|
||||
effective_account_id = real_account_id
|
||||
|
||||
role = _get_account_role(session=session, account_id=effective_account_id)
|
||||
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
|
||||
@@ -569,17 +604,25 @@ def get_access_token(
|
||||
|
||||
user_fingerprint_hash = _set_act_fp_cookie(response=response)
|
||||
|
||||
access_token_payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EPOCH_KEY: epoch,
|
||||
EFFECTIVE_ROLE_KEY: role.value,
|
||||
ORGANIZATION_ID_KEY: str(organization_id),
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
}
|
||||
|
||||
return _build_action_tokens(
|
||||
payload=access_token_payload,
|
||||
access_token = _build_access_token(
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
epoch=epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
)
|
||||
refresh_token = _build_refresh_token(
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
epoch=epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
)
|
||||
return AccessResponse(
|
||||
access_token=access_token,
|
||||
refresh_token=refresh_token,
|
||||
)
|
||||
|
||||
|
||||
@@ -639,7 +682,7 @@ def _set_fingerprint_cookie(
|
||||
return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def refresh_access_token(refresh_token: RefreshToken) -> str:
|
||||
def refresh_access_token(refresh_token: RefreshToken) -> AccessToken:
|
||||
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
|
||||
|
||||
Args:
|
||||
@@ -648,7 +691,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> str:
|
||||
refresh_token (RefreshToken): The refresh token to verify.
|
||||
|
||||
Returns:
|
||||
str: The refreshed access token.
|
||||
AccessToken: The refreshed access token.
|
||||
"""
|
||||
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
@@ -659,7 +702,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> str:
|
||||
|
||||
def _refresh_access_token(
|
||||
refresh_token: RefreshToken,
|
||||
) -> str:
|
||||
) -> AccessToken:
|
||||
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
|
||||
|
||||
Args:
|
||||
@@ -668,97 +711,182 @@ def _refresh_access_token(
|
||||
current_user_epoch (int): The epoch value for the tokens.
|
||||
|
||||
Returns:
|
||||
str: The refreshed access token.
|
||||
AccessToken: The refreshed access token.
|
||||
"""
|
||||
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
access_payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(refresh_token.real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(refresh_token.effective_account_id),
|
||||
EPOCH_KEY: refresh_token.epoch,
|
||||
EFFECTIVE_ROLE_KEY: refresh_token.effective_role,
|
||||
ORGANIZATION_ID_KEY: str(refresh_token.effective_organization_id),
|
||||
USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash,
|
||||
}
|
||||
return _build_token(
|
||||
payload=access_payload,
|
||||
expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.ACCESS_TOKEN,
|
||||
return _build_access_token(
|
||||
real_account_id=refresh_token.real_account_id,
|
||||
effective_account_id=refresh_token.effective_account_id,
|
||||
effective_role=refresh_token.effective_role,
|
||||
effective_organization_id=refresh_token.effective_organization_id,
|
||||
epoch=refresh_token.epoch,
|
||||
user_fingerprint_hash=refresh_token.user_fingerprint_hash,
|
||||
)
|
||||
|
||||
|
||||
def _build_id_token(response: Response, real_account_id: uuid.UUID, epoch: int) -> str:
|
||||
"""Builds an ID token for the specified real account ID and sets the appropriate fingerprint cookie.
|
||||
def _build_id_token(
|
||||
response: Response,
|
||||
real_account_id: uuid.UUID,
|
||||
epoch: int,
|
||||
) -> IdToken:
|
||||
"""Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie.
|
||||
|
||||
Args:
|
||||
response (Response): The FastAPI response object to which the cookie will be added.
|
||||
real_account_id (uuid.UUID): The UUID of the real account.
|
||||
expires_at (datetime.datetime): The expiration time for the token.
|
||||
epoch (int): The epoch value for the tokens.
|
||||
|
||||
Returns:
|
||||
str: The built ID token.
|
||||
IdToken: The generated ID token object.
|
||||
"""
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=ID_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
user_fingerprint_hash = _set_id_fp_cookie(response)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EPOCH_KEY: epoch,
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
}
|
||||
return _build_token(
|
||||
raw_token = _build_token(
|
||||
payload=payload,
|
||||
expiration_min=ID_TOKEN_EXPIRATION_MINUTES,
|
||||
expiration_datetime=expires_at,
|
||||
token_type=TokenType.ID_TOKEN,
|
||||
)
|
||||
return IdToken(
|
||||
real_account_id=real_account_id,
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
raw_token=raw_token,
|
||||
)
|
||||
|
||||
|
||||
def _build_action_tokens(
|
||||
payload: Dict[str, Any],
|
||||
) -> Dict[str, str]:
|
||||
"""Builds both access and refresh tokens for the specified account IDs and sets the appropriate fingerprint cookies.
|
||||
def _build_refresh_token(
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: uuid.UUID,
|
||||
effective_role: UserRole,
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
user_fingerprint_hash: str,
|
||||
) -> RefreshToken:
|
||||
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
Args:
|
||||
response (Response): The FastAPI response object to which the cookies will be added.
|
||||
response (Response): The FastAPI response object to which the cookie will be added.
|
||||
real_account_id (uuid.UUID): The UUID of the real account.
|
||||
effective_account_id (uuid.UUID): The UUID of the effective account.
|
||||
effective_role (UserRole): The role of the effective account.
|
||||
effective_organization_id (uuid.UUID): The UUID of the organization associated with the effective account.
|
||||
epoch (int): The epoch value for the tokens.
|
||||
user_fingerprint_hash (str): The hashed value of the user's fingerprint.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: A dictionary containing the built access and refresh tokens.
|
||||
RefreshToken: The generated refresh token object.
|
||||
"""
|
||||
|
||||
return {
|
||||
"access_token": _build_token(
|
||||
payload=payload,
|
||||
expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.ACCESS_TOKEN,
|
||||
),
|
||||
"refresh_token": _build_token(
|
||||
payload=payload,
|
||||
expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.REFRESH_TOKEN,
|
||||
),
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EFFECTIVE_ROLE_KEY: effective_role.value,
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
|
||||
EPOCH_KEY: epoch,
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
}
|
||||
|
||||
raw_token = _build_token(
|
||||
payload=payload,
|
||||
expiration_datetime=expires_at,
|
||||
token_type=TokenType.REFRESH_TOKEN,
|
||||
)
|
||||
|
||||
return RefreshToken(
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
effective_role=effective_role,
|
||||
effective_organization_id=effective_organization_id,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
raw_token=raw_token,
|
||||
)
|
||||
|
||||
|
||||
def _build_access_token(
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: uuid.UUID,
|
||||
effective_role: UserRole,
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
user_fingerprint_hash: str,
|
||||
) -> AccessToken:
|
||||
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
Args:
|
||||
response (Response): The FastAPI response object to which the cookie will be added.
|
||||
real_account_id (uuid.UUID): The UUID of the real account.
|
||||
effective_account_id (uuid.UUID): The UUID of the effective account.
|
||||
effective_role (UserRole): The role of the effective account.
|
||||
effective_organization_id (uuid.UUID): The UUID of the organization associated with the effective account.
|
||||
epoch (int): The epoch value for the tokens.
|
||||
user_fingerprint_hash (str): The hashed value of the user's fingerprint.
|
||||
|
||||
Returns:
|
||||
AccessToken: The generated access token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EFFECTIVE_ROLE_KEY: effective_role.value,
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
|
||||
EPOCH_KEY: epoch,
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
}
|
||||
|
||||
raw_token = _build_token(
|
||||
payload=payload,
|
||||
expiration_datetime=expires_at,
|
||||
token_type=TokenType.ACCESS_TOKEN,
|
||||
)
|
||||
|
||||
return AccessToken(
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
effective_role=effective_role,
|
||||
effective_organization_id=effective_organization_id,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
raw_token=raw_token,
|
||||
)
|
||||
|
||||
|
||||
def _build_token(
|
||||
payload: Dict[str, Any], expiration_min: int, token_type: TokenType
|
||||
payload: Dict[str, Any],
|
||||
expiration_datetime: datetime.datetime,
|
||||
token_type: TokenType,
|
||||
) -> str:
|
||||
"""Builds a JWT token with the given payload and expiration time.
|
||||
|
||||
Args:
|
||||
payload (Dict[str, Any]): The payload to encode in the JWT.
|
||||
expiration_min (int): The expiration time in minutes.
|
||||
expiration_datetime (datetime.datetime): The expiration time for the token.
|
||||
token_type (TokenType): The type of the token to build.
|
||||
|
||||
Returns:
|
||||
str: The encoded JWT token.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
expiration_date = now + datetime.timedelta(minutes=expiration_min)
|
||||
payload.update(
|
||||
{
|
||||
"exp": expiration_date,
|
||||
"exp": expiration_datetime,
|
||||
"iss": settings.token_issuer_id,
|
||||
"iat": now,
|
||||
"nbf": now,
|
||||
|
||||
@@ -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)
|
||||
@@ -68,6 +68,14 @@ class Settings(BaseSettings):
|
||||
token_hmac_key: Optional[str] = None
|
||||
|
||||
skip_otk_validation: bool = True
|
||||
# SMTP / email config
|
||||
send_otk_email: bool = False
|
||||
smtp_server: str = "localhost"
|
||||
smtp_port: int = 25
|
||||
smtp_sender: str = "no-reply@smartguide.local"
|
||||
smtp_username: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
smtp_use_tls: bool = False
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
@@ -30,13 +30,13 @@ from inse.patents.service import router as patents_service_router
|
||||
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
from inse.auth.service import create_predefined_accounts
|
||||
from . import config
|
||||
from .account.service import router as account_router
|
||||
|
||||
from .service import router as service_router
|
||||
|
||||
@@ -73,7 +73,6 @@ app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
app.include_router(news_service_router)
|
||||
app.include_router(company_connections_router)
|
||||
app.include_router(account_router)
|
||||
app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
@@ -82,6 +81,7 @@ app.include_router(service_router)
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
# middleware/etag_cache.py
|
||||
import hashlib, json, time
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
@@ -22,6 +25,12 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
if request.method != "GET":
|
||||
return await call_next(request)
|
||||
|
||||
if request.url.path.startswith(("/api/auth", "/api/accounts")):
|
||||
return await call_next(request)
|
||||
|
||||
if request.headers.get("authorization"):
|
||||
return await call_next(request)
|
||||
|
||||
key = self._cache_key(request)
|
||||
entry = self.cache.get(key)
|
||||
client_etag = request.headers.get("if-none-match")
|
||||
|
||||
@@ -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"
|
||||
@@ -1,119 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the security-related code.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from typing import List
|
||||
from typing import Callable
|
||||
from typing import Literal
|
||||
from starlette.status import HTTP_403_FORBIDDEN
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPBearer
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
from fastapi import HTTPException
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
import jwt
|
||||
import logging
|
||||
from . import config
|
||||
from . import database
|
||||
|
||||
|
||||
class Account(BaseModel):
|
||||
id: int = Field(description="The id of the account.")
|
||||
login: Optional[str] = Field(description="The optional login of the account.")
|
||||
organization: int = Field(description="The organization id of the account.")
|
||||
|
||||
|
||||
class Principal(BaseModel):
|
||||
account: Account = Field(description="The account of the principal.")
|
||||
delegate: Optional[Account] = Field(
|
||||
default=None, description="The optional delegate of the principal."
|
||||
)
|
||||
roles: List[str] = Field(description="The roles of the principal.")
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
bearer = HTTPBearer(
|
||||
bearerFormat="JWT",
|
||||
scheme_name="bearer",
|
||||
description="JSON Web Token provided via bearer authorization.",
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
|
||||
def principal(
|
||||
db: database.SessionDep,
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer),
|
||||
) -> Optional[Principal]:
|
||||
if config.settings.auth_disabled:
|
||||
account = Account(id=0, login="AUTH_DISABLED", organization=0)
|
||||
return Principal(account=account, delegate=None, roles=["SUPER_ADMIN"])
|
||||
if credentials is None or credentials.credentials is None:
|
||||
return None
|
||||
return _extract_principal(
|
||||
credentials.credentials, config.settings.auth_secret, "HS256"
|
||||
)
|
||||
|
||||
|
||||
def _extract_principal(
|
||||
token: str,
|
||||
secret_key,
|
||||
algorithm: Literal["RS256", "HS256"],
|
||||
token_types: List[Literal["ID", "ACCESS", "REFRESH"]] = ["ACCESS"],
|
||||
) -> Optional[Principal]:
|
||||
try:
|
||||
content = jwt.decode(
|
||||
token,
|
||||
secret_key,
|
||||
verify=True,
|
||||
issuer="my-app",
|
||||
algorithms=[algorithm],
|
||||
options={"require": ["iss", "iat", "nbf", "exp", "inse"]},
|
||||
)
|
||||
except jwt.exceptions.ExpiredSignatureError as e:
|
||||
logger.info(f"Received expired token, ignoring content ({e}).")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.info(f"Received invalid token content, ignoring content ({e}).")
|
||||
return None
|
||||
scope = content.get("inse")
|
||||
if scope is None:
|
||||
return None
|
||||
token_type = scope.get("t")
|
||||
if token_type not in token_types:
|
||||
logger.info(
|
||||
f"Received invalid token type, ignoring content (Type was {token_type})"
|
||||
)
|
||||
return None
|
||||
a = scope.get("a", {})
|
||||
account = Account(id=a.get("i", 0), login=a.get("l"), organization=a.get("o", 0))
|
||||
delegate = None
|
||||
d = scope.get("d")
|
||||
if d is not None:
|
||||
delegate = Account(
|
||||
id=d.get("i", 0), login=d.get("l"), organization=d.get("o", 0)
|
||||
)
|
||||
return Principal(account=account, delegate=delegate, roles=scope.get("r", []))
|
||||
|
||||
|
||||
def roles_allowed(roles: List[str] | str) -> Callable[[Optional[Principal]], Principal]:
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
if len(roles) < 1:
|
||||
raise ValueError("Must specify at least one role in roles_allowed.")
|
||||
|
||||
def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal:
|
||||
if principal is None:
|
||||
logger.info("Rejecting call due to missing principal.")
|
||||
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
for role in roles:
|
||||
if role in principal.roles:
|
||||
return principal
|
||||
logger.info("Rejecting call due to missing roles.")
|
||||
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
|
||||
return verify_roles
|
||||
@@ -11,3 +11,4 @@ class Tags(StrEnum):
|
||||
PROJECTS = "Projects"
|
||||
AUTH = "Auth"
|
||||
ACCOUNT = "Account"
|
||||
ORGANIZATION = "Organization"
|
||||
|
||||
@@ -7,7 +7,6 @@ api/api.ts
|
||||
api/auth.service.ts
|
||||
api/companyConnections.service.ts
|
||||
api/funding.service.ts
|
||||
api/iNSEAccountService.service.ts
|
||||
api/iNSEService.service.ts
|
||||
api/institutions.service.ts
|
||||
api/news.service.ts
|
||||
@@ -21,9 +20,10 @@ configuration.ts
|
||||
encoder.ts
|
||||
git_push.sh
|
||||
index.ts
|
||||
model/accessGrant.ts
|
||||
model/authAccount.ts
|
||||
model/authScope.ts
|
||||
model/accessResponse.ts
|
||||
model/accessToken.ts
|
||||
model/accountPage.ts
|
||||
model/accountProfile.ts
|
||||
model/author.ts
|
||||
model/authorAffiliationsInner.ts
|
||||
model/authorCountsByYearInner.ts
|
||||
@@ -40,7 +40,6 @@ model/autocompleteResponseMeta.ts
|
||||
model/autocompleteResponseResultsInner.ts
|
||||
model/award.ts
|
||||
model/bodyChangePassword.ts
|
||||
model/bodyCreateUser.ts
|
||||
model/bodyGetAccessToken.ts
|
||||
model/bodyLogin.ts
|
||||
model/bodyRequestOtk.ts
|
||||
@@ -56,6 +55,7 @@ model/companyConnectionsResponse.ts
|
||||
model/cordisEuProject.ts
|
||||
model/cordisEuProjectPage.ts
|
||||
model/costUsd.ts
|
||||
model/createAccountRequest.ts
|
||||
model/customAuthor.ts
|
||||
model/customAuthorsListResponse.ts
|
||||
model/dehydratedAuthor.ts
|
||||
@@ -76,7 +76,7 @@ model/fundingProjectPage.ts
|
||||
model/fwci.ts
|
||||
model/groupByResult.ts
|
||||
model/hTTPValidationError.ts
|
||||
model/identityGrant.ts
|
||||
model/idToken.ts
|
||||
model/institution.ts
|
||||
model/institutionFunderSummary.ts
|
||||
model/institutionGeo.ts
|
||||
@@ -88,6 +88,7 @@ model/institutionsListResponse.ts
|
||||
model/keywords.ts
|
||||
model/latitude.ts
|
||||
model/location.ts
|
||||
model/loginResponse.ts
|
||||
model/longitude.ts
|
||||
model/matchedOfficer.ts
|
||||
model/mentionedPerson.ts
|
||||
@@ -98,6 +99,7 @@ model/newsArticle.ts
|
||||
model/newsArticleDetail.ts
|
||||
model/newsPage.ts
|
||||
model/openAccess.ts
|
||||
model/organizationProfile.ts
|
||||
model/patentEntry.ts
|
||||
model/patentsByAuthorResponse.ts
|
||||
model/personBio.ts
|
||||
@@ -108,8 +110,10 @@ model/publicationDetailByFunder.ts
|
||||
model/publicationIdsByAuthorPosition.ts
|
||||
model/publicationsByAuthorResponse.ts
|
||||
model/rankingResponse.ts
|
||||
model/refreshToken.ts
|
||||
model/score.ts
|
||||
model/sortDirection.ts
|
||||
model/tokenType.ts
|
||||
model/topic.ts
|
||||
model/topicCount.ts
|
||||
model/topicDomain.ts
|
||||
@@ -122,7 +126,8 @@ model/topicsByYear.ts
|
||||
model/topicsListResponse.ts
|
||||
model/universityRanking.ts
|
||||
model/universityTopicData.ts
|
||||
model/user.ts
|
||||
model/updateAccountRequest.ts
|
||||
model/userRole.ts
|
||||
model/validationError.ts
|
||||
model/validationErrorLocInner.ts
|
||||
model/value.ts
|
||||
|
||||
@@ -4,8 +4,6 @@ export * from './companyConnections.service';
|
||||
import { CompanyConnectionsService } from './companyConnections.service';
|
||||
export * from './funding.service';
|
||||
import { FundingService } from './funding.service';
|
||||
export * from './iNSEAccountService.service';
|
||||
import { INSEAccountServiceService } from './iNSEAccountService.service';
|
||||
export * from './iNSEService.service';
|
||||
import { INSEServiceService } from './iNSEService.service';
|
||||
export * from './institutions.service';
|
||||
@@ -24,4 +22,4 @@ export * from './topics.service';
|
||||
import { TopicsService } from './topics.service';
|
||||
export * from './works.service';
|
||||
import { WorksService } from './works.service';
|
||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
|
||||
@@ -16,6 +16,14 @@ import { HttpClient, HttpHeaders, HttpParams,
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AccessResponse } from '../model/accessResponse';
|
||||
// @ts-ignore
|
||||
import { AccessToken } from '../model/accessToken';
|
||||
// @ts-ignore
|
||||
import { AccountPage } from '../model/accountPage';
|
||||
// @ts-ignore
|
||||
import { AccountProfile } from '../model/accountProfile';
|
||||
// @ts-ignore
|
||||
import { BodyChangePassword } from '../model/bodyChangePassword';
|
||||
// @ts-ignore
|
||||
@@ -25,7 +33,15 @@ import { BodyLogin } from '../model/bodyLogin';
|
||||
// @ts-ignore
|
||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||
// @ts-ignore
|
||||
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { LoginResponse } from '../model/loginResponse';
|
||||
// @ts-ignore
|
||||
import { OrganizationProfile } from '../model/organizationProfile';
|
||||
// @ts-ignore
|
||||
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
@@ -112,6 +128,132 @@ export class AuthService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Account
|
||||
* @endpoint post /api/accounts
|
||||
* @param createAccountRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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.
|
||||
@@ -120,9 +262,9 @@ export class AuthService extends BaseService {
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<{ [key: string]: string | null; }>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<{ [key: string]: string | null; }>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<{ [key: string]: string | null; }>>;
|
||||
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.');
|
||||
@@ -167,7 +309,7 @@ export class AuthService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/auth/v2/access`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<{ [key: string]: string | null; }>('post', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<AccessResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyGetAccessToken,
|
||||
@@ -181,6 +323,60 @@ export class AuthService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Current Account
|
||||
* @endpoint get /api/accounts/me
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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
|
||||
@@ -232,6 +428,132 @@ export class AuthService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List Organizations
|
||||
* @endpoint get /api/accounts/organizations
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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.
|
||||
@@ -240,9 +562,9 @@ export class AuthService extends BaseService {
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
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.');
|
||||
@@ -284,7 +606,7 @@ export class AuthService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/auth/v2/login`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<LoginResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyLogin,
|
||||
@@ -360,9 +682,9 @@ export class AuthService extends BaseService {
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<string>;
|
||||
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<string>>;
|
||||
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<string>>;
|
||||
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;
|
||||
@@ -395,7 +717,7 @@ export class AuthService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/auth/v2/refresh`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<string>('post', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<AccessToken>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
@@ -474,4 +796,76 @@ export class AuthService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Account
|
||||
* @endpoint put /api/accounts/{account_id}
|
||||
* @param accountId
|
||||
* @param updateAccountRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AccessGrant } from '../model/accessGrant';
|
||||
// @ts-ignore
|
||||
import { BodyCreateUser } from '../model/bodyCreateUser';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { IdentityGrant } from '../model/identityGrant';
|
||||
// @ts-ignore
|
||||
import { User } from '../model/user';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class INSEAccountServiceService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create User
|
||||
* @endpoint post /inse-account/create
|
||||
* @param bodyCreateUser
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<User>;
|
||||
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<User>>;
|
||||
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<User>>;
|
||||
public createUser(bodyCreateUser: BodyCreateUser, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyCreateUser === null || bodyCreateUser === undefined) {
|
||||
throw new Error('Required parameter bodyCreateUser was null or undefined when calling createUser.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/inse-account/create`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<User>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyCreateUser,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Access Grant
|
||||
* @endpoint post /inse-account/auth/access
|
||||
* @param secret
|
||||
* @param account
|
||||
* @param organization
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessGrant>;
|
||||
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessGrant>>;
|
||||
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessGrant>>;
|
||||
public getAccessGrant(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (secret === null || secret === undefined) {
|
||||
throw new Error('Required parameter secret was null or undefined when calling getAccessGrant.');
|
||||
}
|
||||
if (account === null || account === undefined) {
|
||||
throw new Error('Required parameter account was null or undefined when calling getAccessGrant.');
|
||||
}
|
||||
if (organization === null || organization === undefined) {
|
||||
throw new Error('Required parameter organization was null or undefined when calling getAccessGrant.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/x-www-form-urlencoded'
|
||||
];
|
||||
|
||||
const canConsumeForm = this.canConsumeForm(consumes);
|
||||
|
||||
let localVarFormParams: { append(param: string, value: any): any; };
|
||||
let localVarUseForm = false;
|
||||
let localVarConvertFormParamsToString = false;
|
||||
if (localVarUseForm) {
|
||||
localVarFormParams = new FormData();
|
||||
} else {
|
||||
localVarFormParams = new HttpParams({encoder: this.encoder});
|
||||
}
|
||||
|
||||
if (secret !== undefined) {
|
||||
localVarFormParams = localVarFormParams.append('secret', <any>secret) as any || localVarFormParams;
|
||||
}
|
||||
if (account !== undefined) {
|
||||
localVarFormParams = localVarFormParams.append('account', <any>account) as any || localVarFormParams;
|
||||
}
|
||||
if (organization !== undefined) {
|
||||
localVarFormParams = localVarFormParams.append('organization', <any>organization) as any || localVarFormParams;
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/inse-account/auth/access`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccessGrant>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Identity Grant
|
||||
* @endpoint post /inse-account/auth/id
|
||||
* @param username
|
||||
* @param password
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getIdentityGrant(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<IdentityGrant>;
|
||||
public getIdentityGrant(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<IdentityGrant>>;
|
||||
public getIdentityGrant(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<IdentityGrant>>;
|
||||
public getIdentityGrant(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (username === null || username === undefined) {
|
||||
throw new Error('Required parameter username was null or undefined when calling getIdentityGrant.');
|
||||
}
|
||||
if (password === null || password === undefined) {
|
||||
throw new Error('Required parameter password was null or undefined when calling getIdentityGrant.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/x-www-form-urlencoded'
|
||||
];
|
||||
|
||||
const canConsumeForm = this.canConsumeForm(consumes);
|
||||
|
||||
let localVarFormParams: { append(param: string, value: any): any; };
|
||||
let localVarUseForm = false;
|
||||
let localVarConvertFormParamsToString = false;
|
||||
if (localVarUseForm) {
|
||||
localVarFormParams = new FormData();
|
||||
} else {
|
||||
localVarFormParams = new HttpParams({encoder: this.encoder});
|
||||
}
|
||||
|
||||
if (username !== undefined) {
|
||||
localVarFormParams = localVarFormParams.append('username', <any>username) as any || localVarFormParams;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
localVarFormParams = localVarFormParams.append('password', <any>password) as any || localVarFormParams;
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/inse-account/auth/id`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<IdentityGrant>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { AuthScope } from './authScope';
|
||||
|
||||
|
||||
export interface AccessGrant {
|
||||
token_type: string;
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
scope: AuthScope;
|
||||
refresh_token: string;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { AuthScope } from './authScope';
|
||||
import { AccountProfile } from './accountProfile';
|
||||
|
||||
|
||||
export interface IdentityGrant {
|
||||
token_type: string;
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
scope: AuthScope;
|
||||
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,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 {
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -7,13 +7,13 @@
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { IdToken } from './idToken';
|
||||
|
||||
|
||||
export interface BodyCreateUser {
|
||||
username: string;
|
||||
password: string;
|
||||
email: string;
|
||||
institution: string;
|
||||
superadmin?: boolean;
|
||||
export interface LoginResponse {
|
||||
/**
|
||||
* The ID token issued upon successful login.
|
||||
*/
|
||||
id_token: IdToken;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export * from './accessGrant';
|
||||
export * from './authAccount';
|
||||
export * from './authScope';
|
||||
export * from './accessResponse';
|
||||
export * from './accessToken';
|
||||
export * from './accountPage';
|
||||
export * from './accountProfile';
|
||||
export * from './author';
|
||||
export * from './authorAffiliationsInner';
|
||||
export * from './authorCountsByYearInner';
|
||||
@@ -17,7 +18,6 @@ export * from './autocompleteResponseMeta';
|
||||
export * from './autocompleteResponseResultsInner';
|
||||
export * from './award';
|
||||
export * from './bodyChangePassword';
|
||||
export * from './bodyCreateUser';
|
||||
export * from './bodyGetAccessToken';
|
||||
export * from './bodyLogin';
|
||||
export * from './bodyRequestOtk';
|
||||
@@ -33,6 +33,7 @@ export * from './companyConnectionsResponse';
|
||||
export * from './cordisEuProject';
|
||||
export * from './cordisEuProjectPage';
|
||||
export * from './costUsd';
|
||||
export * from './createAccountRequest';
|
||||
export * from './customAuthor';
|
||||
export * from './customAuthorsListResponse';
|
||||
export * from './dehydratedAuthor';
|
||||
@@ -53,7 +54,7 @@ export * from './fundingProjectPage';
|
||||
export * from './fwci';
|
||||
export * from './groupByResult';
|
||||
export * from './hTTPValidationError';
|
||||
export * from './identityGrant';
|
||||
export * from './idToken';
|
||||
export * from './institution';
|
||||
export * from './institutionFunderSummary';
|
||||
export * from './institutionGeo';
|
||||
@@ -65,6 +66,7 @@ export * from './institutionsListResponse';
|
||||
export * from './keywords';
|
||||
export * from './latitude';
|
||||
export * from './location';
|
||||
export * from './loginResponse';
|
||||
export * from './longitude';
|
||||
export * from './matchedOfficer';
|
||||
export * from './mentionedPerson';
|
||||
@@ -74,6 +76,7 @@ export * from './newsArticle';
|
||||
export * from './newsArticleDetail';
|
||||
export * from './newsPage';
|
||||
export * from './openAccess';
|
||||
export * from './organizationProfile';
|
||||
export * from './patentEntry';
|
||||
export * from './patentsByAuthorResponse';
|
||||
export * from './personBio';
|
||||
@@ -84,8 +87,10 @@ export * from './publicationDetailByFunder';
|
||||
export * from './publicationIdsByAuthorPosition';
|
||||
export * from './publicationsByAuthorResponse';
|
||||
export * from './rankingResponse';
|
||||
export * from './refreshToken';
|
||||
export * from './score';
|
||||
export * from './sortDirection';
|
||||
export * from './tokenType';
|
||||
export * from './topic';
|
||||
export * from './topicCount';
|
||||
export * from './topicDomain';
|
||||
@@ -98,7 +103,8 @@ export * from './topicsByYear';
|
||||
export * from './topicsListResponse';
|
||||
export * from './universityRanking';
|
||||
export * from './universityTopicData';
|
||||
export * from './user';
|
||||
export * from './updateAccountRequest';
|
||||
export * from './userRole';
|
||||
export * from './validationError';
|
||||
export * from './validationErrorLocInner';
|
||||
export * from './value';
|
||||
|
||||
+4
-6
@@ -9,11 +9,9 @@
|
||||
*/
|
||||
|
||||
|
||||
export interface AuthAccount {
|
||||
i: number;
|
||||
l: string;
|
||||
o: number;
|
||||
e: string;
|
||||
on: string;
|
||||
export interface OrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
openalex_institution_id?: string | null;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
|
||||
|
||||
@@ -7,13 +7,12 @@
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { AuthAccount } from './authAccount';
|
||||
|
||||
|
||||
export interface AuthScope {
|
||||
t: string;
|
||||
a: AuthAccount;
|
||||
d?: number | null;
|
||||
r?: Array<string>;
|
||||
}
|
||||
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 {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* An entry in the user configuration file.
|
||||
*/
|
||||
export interface User {
|
||||
/**
|
||||
* The username of the user.
|
||||
*/
|
||||
username: string;
|
||||
/**
|
||||
* The password of the user.
|
||||
*/
|
||||
password: string;
|
||||
/**
|
||||
* The email of the user.
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* The account id of the user.
|
||||
*/
|
||||
account: number;
|
||||
/**
|
||||
* The organization id of the user.
|
||||
*/
|
||||
organization: number;
|
||||
/**
|
||||
* The organization name of the user.
|
||||
*/
|
||||
organization_name: string;
|
||||
/**
|
||||
* Indicates whether the user is a superadmin.
|
||||
*/
|
||||
superadmin?: boolean;
|
||||
}
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { userGuard } from './shared/guards/user.guard';
|
||||
import { adminGuard } from './shared/guards/admin.guard';
|
||||
import { superAdminGuard } from './shared/guards/super-admin.guard';
|
||||
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
|
||||
import { personListResolver } from './resolvers/person-list.resolver';
|
||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||
@@ -92,12 +94,20 @@ export const routes: Routes = [
|
||||
},
|
||||
{
|
||||
path: 'accounts',
|
||||
canActivate: [userGuard],
|
||||
canActivate: [adminGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/accounts/accounts.component').then(
|
||||
(mod) => mod.AccountsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'organizations',
|
||||
canActivate: [superAdminGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/organizations/organizations.component').then(
|
||||
(mod) => mod.OrganizationsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
|
||||
@@ -55,9 +55,10 @@ export type AccountDialogResult =
|
||||
standalone: true,
|
||||
})
|
||||
export class AccountDialogComponent {
|
||||
private readonly dialogRef = inject<
|
||||
MatDialogRef<AccountDialogComponent, AccountDialogResult | undefined>
|
||||
>(MatDialogRef);
|
||||
private readonly dialogRef =
|
||||
inject<
|
||||
MatDialogRef<AccountDialogComponent, AccountDialogResult | undefined>
|
||||
>(MatDialogRef);
|
||||
protected readonly data = inject<AccountDialogData>(MAT_DIALOG_DATA);
|
||||
|
||||
protected readonly form = new FormGroup({
|
||||
@@ -73,7 +74,9 @@ export class AccountDialogComponent {
|
||||
]),
|
||||
organizationId: new FormControl<string>(
|
||||
this.data.account?.organization_id ??
|
||||
(this.data.organizations.length === 1 ? this.data.organizations[0].id : ''),
|
||||
(this.data.organizations.length === 1
|
||||
? this.data.organizations[0].id
|
||||
: ''),
|
||||
[Validators.required],
|
||||
),
|
||||
password: new FormControl<string>('', [
|
||||
@@ -104,16 +107,43 @@ export class AccountDialogComponent {
|
||||
return;
|
||||
}
|
||||
|
||||
const account = this.data.account!;
|
||||
const payload: AccountPayload = {};
|
||||
|
||||
const email = (value.email ?? '').trim();
|
||||
const name = (value.name ?? '').trim();
|
||||
const role = value.role ?? account.role;
|
||||
const organizationId = value.organizationId ?? account.organization_id;
|
||||
const password = value.password?.trim() ?? '';
|
||||
|
||||
if (email !== account.email) {
|
||||
payload.email = email;
|
||||
}
|
||||
|
||||
if (name !== account.name) {
|
||||
payload.name = name;
|
||||
}
|
||||
|
||||
if (role !== account.role) {
|
||||
payload.role = role;
|
||||
}
|
||||
|
||||
if (password) {
|
||||
payload.password = password;
|
||||
}
|
||||
|
||||
if (
|
||||
this.data.canSelectOrganization &&
|
||||
organizationId &&
|
||||
organizationId !== account.organization_id
|
||||
) {
|
||||
payload.organization_id = organizationId;
|
||||
}
|
||||
|
||||
this.dialogRef.close({
|
||||
mode: 'edit',
|
||||
accountId: this.data.account!.id,
|
||||
payload: {
|
||||
email: value.email ?? '',
|
||||
name: value.name ?? '',
|
||||
role: value.role ?? 'USER',
|
||||
organization_id: value.organizationId ?? '',
|
||||
password: value.password || undefined,
|
||||
},
|
||||
accountId: account.id,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,11 @@
|
||||
<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()">
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
(click)="startCreate()">
|
||||
<mat-icon>person_add</mat-icon>
|
||||
Neuer Account
|
||||
</button>
|
||||
@@ -16,7 +20,7 @@
|
||||
<input matInput formControlName="search" />
|
||||
</mat-form-field>
|
||||
|
||||
@if (credentialService.superadmin | async) {
|
||||
@if (credentialService.isEffectiveSuperAdmin()) {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Organisation</mat-label>
|
||||
<mat-select formControlName="organizationId">
|
||||
@@ -74,7 +78,9 @@
|
||||
</td>
|
||||
<td>{{ account.email }}</td>
|
||||
<td>{{ account.organization_name }}</td>
|
||||
<td><span class="role">{{ account.role }}</span></td>
|
||||
<td>
|
||||
<span class="role">{{ account.role }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="status" [class.status--deleted]="account.deleted">
|
||||
{{ account.deleted ? 'deleted' : 'active' }}
|
||||
|
||||
@@ -10,9 +10,7 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||
import { Router } from '@angular/router';
|
||||
import { finalize } from 'rxjs';
|
||||
import {
|
||||
AccountManagementService,
|
||||
} from '../../shared/services/account-management.service';
|
||||
import { AccountManagementService } from '../../shared/services/account-management.service';
|
||||
import type {
|
||||
AccountProfile,
|
||||
AccountRole,
|
||||
@@ -48,12 +46,13 @@ export class AccountsComponent implements OnInit {
|
||||
private readonly router = inject(Router);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
|
||||
protected readonly roles: AccountRole[] = [
|
||||
'SUPER_ADMIN',
|
||||
'ADMIN',
|
||||
'MANAGER',
|
||||
'USER',
|
||||
];
|
||||
protected get availableRoles(): AccountRole[] {
|
||||
if (this.credentialService.isEffectiveSuperAdmin()) {
|
||||
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
|
||||
}
|
||||
|
||||
return ['MANAGER', 'USER'];
|
||||
}
|
||||
protected accounts: AccountProfile[] = [];
|
||||
protected organizations: OrganizationProfile[] = [];
|
||||
protected total = 0;
|
||||
@@ -150,14 +149,14 @@ export class AccountsComponent implements OnInit {
|
||||
}): void {
|
||||
import('./account-dialog.component').then(({ AccountDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open<
|
||||
AccountDialogComponent,
|
||||
{
|
||||
mode: 'create' | 'edit';
|
||||
account?: AccountProfile;
|
||||
organizations: OrganizationProfile[];
|
||||
canSelectOrganization: boolean;
|
||||
roles: AccountRole[];
|
||||
},
|
||||
AccountDialogComponent,
|
||||
{
|
||||
mode: 'create' | 'edit';
|
||||
account?: AccountProfile;
|
||||
organizations: OrganizationProfile[];
|
||||
canSelectOrganization: boolean;
|
||||
roles: AccountRole[];
|
||||
},
|
||||
AccountDialogResult | undefined
|
||||
>(AccountDialogComponent, {
|
||||
width: '760px',
|
||||
@@ -165,8 +164,9 @@ export class AccountsComponent implements OnInit {
|
||||
data: {
|
||||
...data,
|
||||
organizations: this.organizations,
|
||||
canSelectOrganization: this.credentialService.superadmin.value,
|
||||
roles: this.roles,
|
||||
canSelectOrganization:
|
||||
this.credentialService.isEffectiveSuperAdmin(),
|
||||
roles: this.availableRoles,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -211,9 +211,13 @@ export class AccountsComponent implements OnInit {
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
this.snackBar.open(
|
||||
'Impersonation konnte nicht gestartet werden.',
|
||||
'OK',
|
||||
{
|
||||
duration: 5000,
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -231,12 +235,12 @@ export class AccountsComponent implements OnInit {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.credentialService.superadmin.value) {
|
||||
if (this.credentialService.isEffectiveSuperAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
this.credentialService.universityadmin.value &&
|
||||
this.credentialService.isEffectiveAdmin() &&
|
||||
(account.role === 'MANAGER' || account.role === 'USER')
|
||||
);
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
checkEnter(): void {
|
||||
if (this.credentialService.authenticated.value) {
|
||||
if (this.credentialService.isAuthenticated.value) {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
);
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.credentialService.logoutAcount();
|
||||
this.credentialService.clearLocalAuthState();
|
||||
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
@@ -169,11 +169,9 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
if (!this.accountId) {
|
||||
this.snackBar.open(
|
||||
'Bitte fordere zuerst einen neuen Code an.',
|
||||
'OK',
|
||||
{ duration: 5000 },
|
||||
);
|
||||
this.snackBar.open('Bitte fordere zuerst einen neuen Code an.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -197,7 +195,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.credentialService.logoutAcount();
|
||||
this.credentialService.clearLocalAuthState();
|
||||
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
|
||||
@@ -95,7 +95,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
}
|
||||
|
||||
checkEnter(): void {
|
||||
if (this.credentialService.authenticated.value) {
|
||||
if (this.credentialService.isAuthenticated.value) {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<h2 mat-dialog-title>
|
||||
{{
|
||||
data.mode === 'create'
|
||||
? 'Organisation erstellen'
|
||||
: 'Organisation bearbeiten'
|
||||
}}
|
||||
</h2>
|
||||
|
||||
<mat-dialog-content>
|
||||
<form class="organization-form" [formGroup]="form" (ngSubmit)="submit()">
|
||||
<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>Externe Institutions-ID</mat-label>
|
||||
<input matInput formControlName="otherInstId" />
|
||||
</mat-form-field>
|
||||
|
||||
@if (data.mode === 'edit') {
|
||||
<mat-checkbox formControlName="deleted">
|
||||
Organisation als gelöscht markieren
|
||||
</mat-checkbox>
|
||||
}
|
||||
</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>
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
.organization-form {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
min-width: min(540px, calc(100vw - 64px));
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.organization-form mat-form-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
mat-dialog-actions {
|
||||
padding: 12px 24px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.organization-form {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
ReactiveFormsModule,
|
||||
Validators,
|
||||
} from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import {
|
||||
MAT_DIALOG_DATA,
|
||||
MatDialogModule,
|
||||
MatDialogRef,
|
||||
} from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import type {
|
||||
CreateOrganizationPayload,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationPayload,
|
||||
} from '../../../shared/services/organization-management.service';
|
||||
|
||||
export interface OrganizationDialogData {
|
||||
mode: 'create' | 'edit';
|
||||
organization?: OrganizationProfile;
|
||||
}
|
||||
|
||||
export type OrganizationDialogResult =
|
||||
| { mode: 'create'; payload: CreateOrganizationPayload }
|
||||
| {
|
||||
mode: 'edit';
|
||||
organizationId: string;
|
||||
payload: UpdateOrganizationPayload;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-organization-dialog',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatCheckboxModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
],
|
||||
templateUrl: './organization-dialog.component.html',
|
||||
styleUrl: './organization-dialog.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class OrganizationDialogComponent {
|
||||
private readonly dialogRef =
|
||||
inject<
|
||||
MatDialogRef<
|
||||
OrganizationDialogComponent,
|
||||
OrganizationDialogResult | undefined
|
||||
>
|
||||
>(MatDialogRef);
|
||||
protected readonly data = inject<OrganizationDialogData>(MAT_DIALOG_DATA);
|
||||
|
||||
protected readonly form = new FormGroup({
|
||||
name: new FormControl(this.data.organization?.name ?? '', {
|
||||
nonNullable: true,
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
otherInstId: new FormControl(
|
||||
this.data.organization?.other_inst_id ?? '',
|
||||
{ nonNullable: true },
|
||||
),
|
||||
deleted: new FormControl(this.data.organization?.deleted ?? false, {
|
||||
nonNullable: true,
|
||||
}),
|
||||
});
|
||||
|
||||
protected submit(): void {
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this.form.getRawValue();
|
||||
const payload = {
|
||||
name: value.name.trim(),
|
||||
other_inst_id: value.otherInstId.trim(),
|
||||
};
|
||||
|
||||
if (this.data.mode === 'create') {
|
||||
this.dialogRef.close({ mode: 'create', payload });
|
||||
return;
|
||||
}
|
||||
|
||||
this.dialogRef.close({
|
||||
mode: 'edit',
|
||||
organizationId: this.data.organization!.id,
|
||||
payload: { ...payload, deleted: value.deleted },
|
||||
});
|
||||
}
|
||||
|
||||
protected close(): void {
|
||||
this.dialogRef.close(undefined);
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,35 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
import { Observable, of, switchMap, takeWhile } from 'rxjs';
|
||||
|
||||
export const adminGuard: CanActivateFn = (route, state) => {
|
||||
let credentialService = inject(CredentialService);
|
||||
let router = inject(Router);
|
||||
return new Observable((subscriber) => {
|
||||
credentialService.validating
|
||||
.pipe(takeWhile((validating) => validating))
|
||||
.subscribe({
|
||||
complete: () => {
|
||||
if (!credentialService.superadmin.value) {
|
||||
router.navigate(['/login']);
|
||||
return subscriber.next(false);
|
||||
} else {
|
||||
return subscriber.next(true);
|
||||
export const adminGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
switchMap(() => {
|
||||
if (
|
||||
!credentialService.isEffectiveSuperAdmin() &&
|
||||
!credentialService.isEffectiveAdmin()
|
||||
) {
|
||||
void router.navigate(['/dashboard']);
|
||||
return of(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return of(true);
|
||||
}),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -1,26 +1,25 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, map, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
import { Observable, of, switchMap, takeWhile } from 'rxjs';
|
||||
|
||||
export const userGuard: CanActivateFn = (route, state) => {
|
||||
let credentialService = inject(CredentialService);
|
||||
let router = inject(Router);
|
||||
return new Observable((subscriber) => {
|
||||
credentialService.validating
|
||||
.pipe(takeWhile((validating) => validating))
|
||||
.subscribe({
|
||||
complete: () => {
|
||||
if (
|
||||
!credentialService.superadmin.value &&
|
||||
!credentialService.universityadmin.value
|
||||
) {
|
||||
router.navigate(['/login']);
|
||||
return subscriber.next(false);
|
||||
} else {
|
||||
return subscriber.next(true);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
export const userGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
map(() => true),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,41 +1,86 @@
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { catchError, switchMap, tap, throwError } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
import { switchMap, throwError } from 'rxjs';
|
||||
import { UiFocusService } from '../services/ui-focus.service';
|
||||
|
||||
export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
if (
|
||||
(req.method == 'POST' &&
|
||||
(req.url.endsWith('/auth/id') ||
|
||||
req.url.endsWith('/auth/access') ||
|
||||
req.url.endsWith('/api/auth/v2/request-otk') ||
|
||||
req.url.endsWith('/api/auth/v2/login') ||
|
||||
req.url.endsWith('/api/auth/v2/access') ||
|
||||
req.url.endsWith('/api/auth/v2/refresh') ||
|
||||
req.url.endsWith('/inse-account/create') ||
|
||||
req.url.endsWith('/auth/v2/request-otk'))) ||
|
||||
req.url.endsWith('/institutions/autocomplete')
|
||||
) {
|
||||
return next(req);
|
||||
} else {
|
||||
const credentialService = inject(CredentialService);
|
||||
const tokenProvider = credentialService.getBearerToken();
|
||||
const url = req.url.split('?')[0];
|
||||
const uiFocusService = inject(UiFocusService);
|
||||
|
||||
return tokenProvider.pipe(
|
||||
switchMap((response) => {
|
||||
if (response == undefined) {
|
||||
return throwError(
|
||||
() =>
|
||||
new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }),
|
||||
);
|
||||
} else {
|
||||
return next(
|
||||
req.clone({
|
||||
headers: req.headers.set('Authorization', 'Bearer ' + response),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
const isPublicAuthRequest =
|
||||
req.method === 'POST' &&
|
||||
(url.endsWith('/api/auth/v2/request-otk') ||
|
||||
url.endsWith('/api/auth/v2/login') ||
|
||||
url.endsWith('/api/auth/v2/access') ||
|
||||
url.endsWith('/api/auth/v2/refresh'));
|
||||
|
||||
if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) {
|
||||
return next(req);
|
||||
}
|
||||
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
const snackBar = inject(MatSnackBar);
|
||||
const tokenProvider = credentialService.getBearerToken();
|
||||
const isLogoutRequest = url.endsWith('/api/auth/v2/logout');
|
||||
|
||||
return tokenProvider.pipe(
|
||||
switchMap((response) => {
|
||||
if (response == undefined) {
|
||||
credentialService.clearLocalAuthState();
|
||||
|
||||
snackBar.open(
|
||||
'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
|
||||
void router.navigate(['/login']);
|
||||
|
||||
return throwError(
|
||||
() => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }),
|
||||
);
|
||||
}
|
||||
|
||||
const authorizedRequest = req.clone({
|
||||
headers: req.headers.set('Authorization', 'Bearer ' + response),
|
||||
});
|
||||
|
||||
return next(authorizedRequest).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401 && !isLogoutRequest) {
|
||||
return credentialService.handleUnauthorized().pipe(
|
||||
tap((result) => {
|
||||
uiFocusService.blurActiveElement();
|
||||
|
||||
if (result === 'stopped-impersonating') {
|
||||
snackBar.open(
|
||||
'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
|
||||
void router.navigate(['/accounts']);
|
||||
} else if (result === 'logged-out') {
|
||||
snackBar.open(
|
||||
'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
|
||||
void router.navigate(['/login']);
|
||||
}
|
||||
}),
|
||||
switchMap(() => throwError(() => error)),
|
||||
);
|
||||
}
|
||||
|
||||
return throwError(() => error);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,143 +1,107 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman
|
||||
import { Observable, of, switchMap, tap, throwError } from 'rxjs'; // review
|
||||
import { BehaviorSubject } from 'rxjs'; //review
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { filter, take, map, catchError, finalize } from 'rxjs/operators';
|
||||
import {
|
||||
BehaviorSubject,
|
||||
Observable,
|
||||
of,
|
||||
switchMap,
|
||||
tap,
|
||||
throwError,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
AuthService,
|
||||
Configuration,
|
||||
INSEAccountServiceService,
|
||||
IdentityGrant as ApiIdentityGrant,
|
||||
AccessGrant as ApiAccessGrant,
|
||||
IdToken,
|
||||
LoginResponse,
|
||||
AccountProfile,
|
||||
} from '../../api';
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
|
||||
export interface AuthAccount {
|
||||
i: string;
|
||||
l: string;
|
||||
o: string;
|
||||
e: string;
|
||||
on: string;
|
||||
}
|
||||
|
||||
export interface AuthScope {
|
||||
t: string;
|
||||
a: AuthAccount;
|
||||
d: number | null;
|
||||
r: string[];
|
||||
}
|
||||
|
||||
export interface IdentityGrant {
|
||||
token_type: string;
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
scope: AuthScope;
|
||||
}
|
||||
|
||||
export interface AccessGrant {
|
||||
token_type: string;
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
scope: AuthScope;
|
||||
refresh_token: string;
|
||||
}
|
||||
|
||||
interface TimedIdentityGrant {
|
||||
grant: IdentityGrant;
|
||||
expiration: number;
|
||||
accountId: string;
|
||||
}
|
||||
|
||||
interface TimedAccessGrant {
|
||||
grant: AccessGrant;
|
||||
expiration: number;
|
||||
realAccountId: string;
|
||||
effectiveAccountId: string;
|
||||
}
|
||||
type LogoutResult = 'logged-out' | 'stopped-impersonating';
|
||||
type UnauthorizedRecoveryResult =
|
||||
| 'logged-out'
|
||||
| 'stopped-impersonating'
|
||||
| 'already-handling';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CredentialService {
|
||||
private accountService = inject(INSEAccountServiceService);
|
||||
private authService = inject(AuthService);
|
||||
private httpClient = inject(HttpClient);
|
||||
private apiConfiguration = inject(Configuration, { optional: true });
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||
private handlingUnauthorized = false;
|
||||
|
||||
private static readonly KEY_GRANT = 'grant';
|
||||
|
||||
public readonly validating = new BehaviorSubject<boolean>(false);
|
||||
public readonly authenticated = new BehaviorSubject<boolean>(false);
|
||||
public readonly superadmin = new BehaviorSubject<boolean>(false);
|
||||
public readonly universityadmin = new BehaviorSubject<boolean>(false);
|
||||
public readonly organization = new BehaviorSubject<string | undefined>(
|
||||
undefined,
|
||||
public readonly isAuthenticated = new BehaviorSubject<boolean>(false);
|
||||
public readonly isEffectiveSuperAdmin = computed(
|
||||
() => this.accessToken()?.effective_role === 'SUPER_ADMIN',
|
||||
);
|
||||
public readonly isEffectiveAdmin = computed(
|
||||
() => this.accessToken()?.effective_role === 'ADMIN',
|
||||
);
|
||||
public readonly effectiveOrganizationId = computed(
|
||||
() => this.accessToken()?.effective_organization_id,
|
||||
);
|
||||
public readonly login = new BehaviorSubject<string>('');
|
||||
public readonly email = new BehaviorSubject<string>('');
|
||||
public readonly organizationName = new BehaviorSubject<string>('');
|
||||
public readonly impersonating = new BehaviorSubject<boolean>(false);
|
||||
public readonly realAccountId = new BehaviorSubject<string>('');
|
||||
public readonly effectiveAccountId = new BehaviorSubject<string>('');
|
||||
|
||||
private readonly identityToken = new BehaviorSubject<
|
||||
TimedIdentityGrant | undefined
|
||||
>(undefined);
|
||||
private readonly accessToken = new BehaviorSubject<
|
||||
TimedAccessGrant | undefined
|
||||
>(undefined);
|
||||
public readonly realAccountId = computed(
|
||||
() => this.accessToken()?.real_account_id ?? '',
|
||||
);
|
||||
public readonly effectiveAccountId = computed(
|
||||
() => this.accessToken()?.effective_account_id ?? '',
|
||||
);
|
||||
public readonly isImpersonating = computed(
|
||||
() => this.realAccountId() !== this.effectiveAccountId(),
|
||||
);
|
||||
|
||||
private readonly identityToken = signal<IdToken | undefined>(undefined);
|
||||
private readonly accessToken = signal<AccessToken | undefined>(undefined);
|
||||
|
||||
private request = 0;
|
||||
|
||||
constructor() {
|
||||
this.accessToken.subscribe((token) => {
|
||||
if (token) {
|
||||
const r = token.grant.scope.r as string[];
|
||||
this.superadmin.next(r.includes('SUPER_ADMIN'));
|
||||
this.universityadmin.next(r.includes('UNI_ADMIN') || r.includes('ADMIN'));
|
||||
this.login.next(token.grant.scope.a?.l ?? '');
|
||||
this.email.next(token.grant.scope.a?.e ?? '');
|
||||
this.organizationName.next(token.grant.scope.a?.on ?? '');
|
||||
this.impersonating.next(token.realAccountId !== token.effectiveAccountId);
|
||||
this.realAccountId.next(token.realAccountId);
|
||||
this.effectiveAccountId.next(token.effectiveAccountId);
|
||||
} else {
|
||||
this.superadmin.next(false);
|
||||
this.universityadmin.next(false);
|
||||
this.login.next('');
|
||||
this.email.next('');
|
||||
this.organizationName.next('');
|
||||
this.impersonating.next(false);
|
||||
this.realAccountId.next('');
|
||||
this.effectiveAccountId.next('');
|
||||
}
|
||||
});
|
||||
const data = localStorage.getItem(CredentialService.KEY_GRANT);
|
||||
const id = data ? (JSON.parse(data) as TimedIdentityGrant) : undefined;
|
||||
if (id && id.expiration && id.expiration >= Date.now()) {
|
||||
this.identityToken.next(id);
|
||||
const id = data ? (JSON.parse(data) as AccessToken) : undefined;
|
||||
if (id && new Date(id.expires_at).getTime() >= Date.now()) {
|
||||
this.identityToken.set(id);
|
||||
this.validating.next(true);
|
||||
setTimeout(() => this.refreshAccessToken(id), 0);
|
||||
}
|
||||
}
|
||||
|
||||
public validateCurrentSession(): Observable<void> {
|
||||
return this.loadCurrentProfile();
|
||||
}
|
||||
|
||||
public requestOtk(email: string, password: string): Observable<string> {
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.authenticated.next(false);
|
||||
this.organization.next(undefined);
|
||||
this.superadmin.next(false);
|
||||
this.universityadmin.next(false);
|
||||
this.identityToken.next(undefined);
|
||||
this.accessToken.next(undefined);
|
||||
this.isAuthenticated.next(false);
|
||||
this.identityToken.set(undefined);
|
||||
this.accessToken.set(undefined);
|
||||
|
||||
return this.authService
|
||||
.requestOtk({ email: email.trim().toLowerCase(), password })
|
||||
.pipe(
|
||||
map((response: { account_id?: string }) => {
|
||||
if (this.request != request) return '';
|
||||
this.validating.next(false);
|
||||
if (this.request !== request) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return response.account_id ?? '';
|
||||
}),
|
||||
finalize(() => {
|
||||
if (this.request === request) {
|
||||
this.validating.next(false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,215 +112,219 @@ export class CredentialService {
|
||||
): Observable<void> {
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.authenticated.next(false);
|
||||
this.organization.next(undefined);
|
||||
this.superadmin.next(false);
|
||||
this.universityadmin.next(false);
|
||||
this.identityToken.next(undefined);
|
||||
this.accessToken.next(undefined);
|
||||
this.isAuthenticated.next(false);
|
||||
|
||||
return this.authService
|
||||
.login({ account_id: accountId, email_code: emailCode.trim() })
|
||||
.pipe(
|
||||
switchMap((response: { id_token: string }) => {
|
||||
switchMap((response: LoginResponse) => {
|
||||
if (this.request != request) return of(undefined);
|
||||
const payload = this.decodeJwtPayload(response.id_token);
|
||||
const token: TimedIdentityGrant = {
|
||||
accountId,
|
||||
grant: {
|
||||
token_type: 'ID',
|
||||
access_token: response.id_token,
|
||||
expires_in: Math.max(payload.exp - Math.floor(Date.now() / 1000), 0),
|
||||
scope: this.buildIdentityScope(accountId, email),
|
||||
},
|
||||
expiration: payload.exp * 1000,
|
||||
};
|
||||
this.identityToken.next(token);
|
||||
|
||||
const idToken = response.id_token;
|
||||
|
||||
this.identityToken.set(idToken);
|
||||
localStorage.setItem(
|
||||
CredentialService.KEY_GRANT,
|
||||
JSON.stringify(token),
|
||||
JSON.stringify(idToken),
|
||||
);
|
||||
return this.getAccessGrantForIdentity(token, request);
|
||||
return this.getAccessGrantForIdentity(idToken, request);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public loginAccount(login: string, password: string) {
|
||||
const request = ++this.request;
|
||||
const now = Date.now();
|
||||
this.validating.next(true);
|
||||
this.authenticated.next(false);
|
||||
this.organization.next(undefined);
|
||||
this.superadmin.next(false);
|
||||
this.universityadmin.next(false);
|
||||
this.identityToken.next(undefined);
|
||||
this.accessToken.next(undefined);
|
||||
|
||||
const body = new URLSearchParams();
|
||||
body.set('username', login);
|
||||
body.set('password', password);
|
||||
|
||||
this.accountService.getIdentityGrant(login, password).subscribe({
|
||||
next: (result) => {
|
||||
if (this.request != request) return;
|
||||
const token: TimedIdentityGrant = {
|
||||
grant: result as any as IdentityGrant,
|
||||
expiration: result.expires_in * 1000 + now,
|
||||
accountId: String((result as any).scope?.a?.i ?? ''),
|
||||
};
|
||||
this.identityToken.next(token);
|
||||
localStorage.setItem(
|
||||
CredentialService.KEY_GRANT,
|
||||
JSON.stringify(token),
|
||||
);
|
||||
this.refreshAccessToken(token);
|
||||
},
|
||||
error: () => {
|
||||
if (this.request != request) return;
|
||||
this.validating.next(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public refreshAccessToken(identityToken: TimedIdentityGrant) {
|
||||
public refreshAccessToken(identityToken: IdToken) {
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.accessToken.next(undefined);
|
||||
this.accessToken.set(undefined);
|
||||
this.getAccessGrantForIdentity(identityToken, request).subscribe({
|
||||
error: () => {
|
||||
if (this.request != request) return;
|
||||
this.identityToken.next(undefined);
|
||||
this.organization.next(undefined);
|
||||
this.authenticated.next(false);
|
||||
this.superadmin.next(false);
|
||||
this.universityadmin.next(false);
|
||||
this.validating.next(false);
|
||||
this.clearLocalAuthState();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public impersonateAccount(accountId: string): Observable<void> {
|
||||
if (!this.identityToken.value) {
|
||||
const idToken = this.identityToken();
|
||||
|
||||
if (!idToken) {
|
||||
return throwError(() => new Error('No identity token available.'));
|
||||
}
|
||||
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.accessToken.next(undefined);
|
||||
return this.getAccessGrantForIdentity(
|
||||
this.identityToken.value,
|
||||
request,
|
||||
accountId,
|
||||
).pipe(tap({ error: () => this.validating.next(false) }));
|
||||
this.accessToken.set(undefined);
|
||||
return this.getAccessGrantForIdentity(idToken, request, accountId).pipe(
|
||||
tap({ error: () => this.validating.next(false) }),
|
||||
);
|
||||
}
|
||||
|
||||
public stopImpersonating(): Observable<void> {
|
||||
if (!this.identityToken.value) {
|
||||
const idToken = this.identityToken();
|
||||
|
||||
if (!idToken) {
|
||||
return throwError(() => new Error('No identity token available.'));
|
||||
}
|
||||
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.accessToken.next(undefined);
|
||||
return this.getAccessGrantForIdentity(
|
||||
this.identityToken.value,
|
||||
request,
|
||||
this.identityToken.value.accountId,
|
||||
).pipe(tap({ error: () => this.validating.next(false) }));
|
||||
this.accessToken.set(undefined);
|
||||
return this.getAccessGrantForIdentity(idToken, request).pipe(
|
||||
tap({ error: () => this.validating.next(false) }),
|
||||
);
|
||||
}
|
||||
|
||||
public logoutAcount() {
|
||||
public logoutAccount(): Observable<LogoutResult> {
|
||||
const wasImpersonating = this.isImpersonating();
|
||||
|
||||
return this.authService
|
||||
.logout('body', false, { transferCache: false })
|
||||
.pipe(
|
||||
catchError((error) => {
|
||||
console.error('Backend logout failed', error);
|
||||
return of(null);
|
||||
}),
|
||||
switchMap(() => {
|
||||
if (!wasImpersonating) {
|
||||
this.clearLocalAuthState();
|
||||
return of('logged-out' as const);
|
||||
}
|
||||
|
||||
return this.stopImpersonating().pipe(
|
||||
map(() => 'stopped-impersonating' as const),
|
||||
catchError((error) => {
|
||||
console.error('Stop impersonating after logout failed', error);
|
||||
this.clearLocalAuthState();
|
||||
return of('logged-out' as const);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public clearLocalAuthState(): void {
|
||||
this.request += 1;
|
||||
localStorage.removeItem(CredentialService.KEY_GRANT);
|
||||
this.authenticated.next(false);
|
||||
this.organization.next(undefined);
|
||||
this.superadmin.next(false);
|
||||
this.universityadmin.next(false);
|
||||
this.identityToken.next(undefined);
|
||||
this.accessToken.next(undefined);
|
||||
this.identityToken.set(undefined);
|
||||
this.accessToken.set(undefined);
|
||||
this.isAuthenticated.next(false);
|
||||
this.validating.next(false);
|
||||
this.login.next('');
|
||||
this.email.next('');
|
||||
this.organizationName.next('');
|
||||
}
|
||||
|
||||
public registerAccount(data: any): Observable<any> {
|
||||
return this.accountService.createUser(data);
|
||||
public handleUnauthorized(): Observable<UnauthorizedRecoveryResult> {
|
||||
if (this.handlingUnauthorized) {
|
||||
return of('already-handling' as const);
|
||||
}
|
||||
|
||||
this.handlingUnauthorized = true;
|
||||
|
||||
const isImpersonating = this.isImpersonating();
|
||||
const identityToken = this.identityToken();
|
||||
|
||||
const recovery$ =
|
||||
isImpersonating && identityToken
|
||||
? this.stopImpersonating().pipe(
|
||||
map(() => 'stopped-impersonating' as const),
|
||||
catchError((error) => {
|
||||
console.error('Failed to stop impersonation after 401', error);
|
||||
this.clearLocalAuthState();
|
||||
return of('logged-out' as const);
|
||||
}),
|
||||
)
|
||||
: of(null).pipe(
|
||||
tap(() => this.clearLocalAuthState()),
|
||||
map(() => 'logged-out' as const),
|
||||
);
|
||||
|
||||
return recovery$.pipe(
|
||||
finalize(() => {
|
||||
this.handlingUnauthorized = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public changePassword(
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
): Observable<void> {
|
||||
return this.httpClient
|
||||
.post(
|
||||
`${this.apiBasePath}/api/auth/v2/change-password`,
|
||||
{
|
||||
current_password: currentPassword,
|
||||
new_password: newPassword,
|
||||
},
|
||||
{ withCredentials: true },
|
||||
)
|
||||
.pipe(
|
||||
tap(() => this.clearLocalAuthState()),
|
||||
map(() => undefined),
|
||||
);
|
||||
}
|
||||
|
||||
public registerAccount(_data: unknown): Observable<never> {
|
||||
return throwError(() => new Error('Registration is temporarily disabled.'));
|
||||
}
|
||||
|
||||
//review: arman (generated fix)
|
||||
public getBearerToken(): Observable<string | undefined> {
|
||||
const accessToken = this.accessToken();
|
||||
const identityToken = this.identityToken();
|
||||
|
||||
// 1. If we have a valid access token, return it immediately and complete.
|
||||
if (
|
||||
this.accessToken.value &&
|
||||
Date.now() < this.accessToken.value.expiration
|
||||
accessToken &&
|
||||
Date.now() < new Date(accessToken.expires_at).getTime()
|
||||
) {
|
||||
return of(this.accessToken.value.grant.access_token);
|
||||
return of(accessToken.raw_token);
|
||||
}
|
||||
|
||||
// 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh.
|
||||
if (!this.validating.value) {
|
||||
if (!this.identityToken.value) {
|
||||
if (!identityToken) {
|
||||
return of(undefined); // No identity token to refresh with.
|
||||
}
|
||||
this.refreshAccessToken(this.identityToken.value);
|
||||
this.refreshAccessToken(identityToken);
|
||||
}
|
||||
|
||||
// 3. Wait for the validation to finish, then return the resulting token.
|
||||
return this.validating.pipe(
|
||||
filter((isValidating) => !isValidating), // Wait until validating becomes false
|
||||
take(1), // Take exactly 1 emission and then automatically complete()
|
||||
map(() =>
|
||||
this.accessToken.value
|
||||
? this.accessToken.value.grant.access_token
|
||||
: undefined,
|
||||
),
|
||||
map(() => this.accessToken()?.raw_token),
|
||||
);
|
||||
}
|
||||
|
||||
private getAccessGrantForIdentity(
|
||||
identityToken: TimedIdentityGrant,
|
||||
idToken: IdToken,
|
||||
request: number,
|
||||
effectiveAccountId?: string,
|
||||
): Observable<void> {
|
||||
const accountId =
|
||||
identityToken.accountId || String(identityToken.grant.scope.a?.i ?? '');
|
||||
const realAccountId = idToken.real_account_id;
|
||||
const headers = new HttpHeaders({
|
||||
Authorization: `Bearer ${identityToken.grant.access_token}`,
|
||||
Authorization: `Bearer ${idToken.raw_token}`,
|
||||
});
|
||||
const payload = {
|
||||
real_account_id: realAccountId,
|
||||
effective_account_id: effectiveAccountId ?? realAccountId,
|
||||
};
|
||||
|
||||
return this.httpClient
|
||||
.post<{ access_token: string; refresh_token: string }>(
|
||||
`${this.apiBasePath}/api/auth/v2/access`,
|
||||
{
|
||||
real_account_id: accountId,
|
||||
effective_account_id: effectiveAccountId ?? accountId,
|
||||
},
|
||||
{ headers, withCredentials: true },
|
||||
)
|
||||
.post<AccessResponse>(`${this.apiBasePath}/api/auth/v2/access`, payload, {
|
||||
headers,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
tap((result) => {
|
||||
tap((result: AccessResponse) => {
|
||||
if (this.request != request) return;
|
||||
const payload = this.decodeJwtPayload(result.access_token);
|
||||
const scope = this.buildAccessScope(
|
||||
payload,
|
||||
identityToken.grant.scope.a?.e ?? '',
|
||||
);
|
||||
const token: TimedAccessGrant = {
|
||||
grant: {
|
||||
token_type: 'ACCESS',
|
||||
access_token: result.access_token,
|
||||
refresh_token: result.refresh_token,
|
||||
expires_in: Math.max(
|
||||
payload.exp - Math.floor(Date.now() / 1000),
|
||||
0,
|
||||
),
|
||||
scope,
|
||||
},
|
||||
expiration: payload.exp * 1000,
|
||||
realAccountId: payload.real_account_id ?? accountId,
|
||||
effectiveAccountId: payload.effective_account_id ?? accountId,
|
||||
};
|
||||
this.accessToken.next(token);
|
||||
this.organization.next(scope.a.o);
|
||||
this.authenticated.next(true);
|
||||
|
||||
const accessToken = result.access_token;
|
||||
|
||||
this.accessToken.set(accessToken);
|
||||
this.isAuthenticated.next(true);
|
||||
this.validating.next(false);
|
||||
}),
|
||||
map(() => undefined),
|
||||
@@ -367,70 +335,18 @@ export class CredentialService {
|
||||
return this.apiConfiguration?.basePath ?? '';
|
||||
}
|
||||
|
||||
private decodeJwtPayload(token: string): any {
|
||||
const payload = token.split('.')[1];
|
||||
return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
|
||||
private loadCurrentProfile(): Observable<void> {
|
||||
return this.httpClient
|
||||
.get<AccountProfile>(`${this.apiBasePath}/api/accounts/me`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
tap((profile) => {
|
||||
this.login.next(profile.name ?? profile.email ?? '');
|
||||
this.email.next(profile.email ?? '');
|
||||
this.organizationName.next(profile.organization_name ?? '');
|
||||
}),
|
||||
map(() => undefined),
|
||||
);
|
||||
}
|
||||
|
||||
private buildIdentityScope(accountId: string, email: string): AuthScope {
|
||||
return {
|
||||
t: 'ID',
|
||||
d: null,
|
||||
r: [],
|
||||
a: {
|
||||
i: accountId,
|
||||
l: email,
|
||||
o: '',
|
||||
e: email,
|
||||
on: '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private buildAccessScope(payload: any, email: string): AuthScope {
|
||||
const accountId = payload.effective_account_id ?? payload.real_account_id ?? '';
|
||||
const organizationId = payload.organization_id ?? '';
|
||||
const role = String(payload.effective_role ?? '');
|
||||
|
||||
return {
|
||||
t: 'ACCESS',
|
||||
d: null,
|
||||
r: role ? [role] : [],
|
||||
a: {
|
||||
i: accountId,
|
||||
l: email || accountId,
|
||||
o: organizationId,
|
||||
e: email,
|
||||
on: organizationId,
|
||||
},
|
||||
};
|
||||
}
|
||||
/* Old version with added complete statements to resolve loading spinner issue
|
||||
public getBearerToken(): Observable<string | undefined> {
|
||||
return new Observable<string | undefined>((observer) => {
|
||||
if (this.validating.value) {
|
||||
this.validating.pipe(takeWhile((validating) => validating)).subscribe({
|
||||
complete: () => {
|
||||
observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined);
|
||||
observer.complete(); // added complete
|
||||
}
|
||||
});
|
||||
} else if (!this.accessToken.value) {
|
||||
observer.next(undefined);
|
||||
observer.complete(); // added complete
|
||||
} else if (Date.now() < this.accessToken.value.expiration) {
|
||||
observer.next(this.accessToken.value.grant.access_token);
|
||||
observer.complete(); // added complete
|
||||
} else {
|
||||
this.refreshAccessToken(this.identityToken.value!);
|
||||
this.validating.pipe(takeWhile((validating) => validating)).subscribe({
|
||||
complete: () => {
|
||||
observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined);
|
||||
observer.complete(); // added complete
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,7 @@
|
||||
<mat-drawer-container
|
||||
class="drawer-container"
|
||||
[autosize]="!mediaQuery.matches">
|
||||
@if (
|
||||
(credentialService.authenticated | async) &&
|
||||
((credentialService.superadmin | async) ||
|
||||
(credentialService.universityadmin | async))
|
||||
) {
|
||||
@if (credentialService.isAuthenticated | async) {
|
||||
<mat-drawer
|
||||
class="drawer"
|
||||
[class.drawer--collapsed]="isSidebarCollapsed()"
|
||||
@@ -22,8 +18,8 @@
|
||||
</mat-drawer>
|
||||
}
|
||||
<mat-drawer-content class="content-shell">
|
||||
@if (credentialService.authenticated | async) {
|
||||
@if (credentialService.impersonating | async) {
|
||||
@if (credentialService.isAuthenticated | async) {
|
||||
@if (credentialService.isImpersonating()) {
|
||||
<div class="impersonation-banner">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
<span>Impersonation aktiv</span>
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
ViewChild,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { CommonModule, Location } from '@angular/common';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
@@ -16,7 +16,6 @@ import { MediaMatcher } from '@angular/cdk/layout';
|
||||
import { AppMenuComponent } from '../app-menu/app-menu.component';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { CredentialService } from '../../services/credential.service';
|
||||
import { Location } from '@angular/common';
|
||||
import { AppSearchbarComponent } from '../app-searchbar/app-searchbar.component';
|
||||
import { ResolverStateService } from '../../services/resolver-state.service';
|
||||
import { LoadingComponent } from '../loading/loading.component';
|
||||
@@ -52,7 +51,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
|
||||
constructor(
|
||||
public credentialService: CredentialService,
|
||||
public router: Router,
|
||||
private location: Location,
|
||||
private readonly location: Location,
|
||||
public changeDetector: ChangeDetectorRef,
|
||||
media: MediaMatcher,
|
||||
) {
|
||||
@@ -104,8 +103,15 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.credentialService.logoutAcount();
|
||||
this.router.navigate(['/']);
|
||||
this.credentialService.logoutAccount().subscribe({
|
||||
next: (result) => {
|
||||
if (result === 'stopped-impersonating') {
|
||||
this.router.navigate(['/accounts']);
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
stopImpersonating(): void {
|
||||
|
||||
@@ -42,31 +42,39 @@
|
||||
|
||||
<mat-nav-list class="nav-list">
|
||||
@for (item of navItems; track item.label) {
|
||||
@if (collapsed()) {
|
||||
<a
|
||||
mat-icon-button
|
||||
class="nav-icon-button"
|
||||
[routerLink]="item.disabled ? null : item.route"
|
||||
[queryParams]="item.queryParams || null"
|
||||
routerLinkActive="active"
|
||||
[routerLinkActiveOptions]="navLinkActiveOptions"
|
||||
[class.disabled]="item.disabled"
|
||||
[matTooltip]="item.label"
|
||||
matTooltipPosition="right"
|
||||
[attr.aria-label]="item.label">
|
||||
<mat-icon>{{ item.icon }}</mat-icon>
|
||||
</a>
|
||||
} @else {
|
||||
<a
|
||||
mat-list-item
|
||||
[routerLink]="item.disabled ? null : item.route"
|
||||
[queryParams]="item.queryParams || null"
|
||||
routerLinkActive="active"
|
||||
[routerLinkActiveOptions]="navLinkActiveOptions"
|
||||
[class.disabled]="item.disabled">
|
||||
<mat-icon matListItemIcon>{{ item.icon }}</mat-icon>
|
||||
<span matListItemTitle>{{ item.label }}</span>
|
||||
</a>
|
||||
@if (
|
||||
(!item.adminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin() ||
|
||||
credentialService.isEffectiveAdmin()) &&
|
||||
(!item.superAdminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin())
|
||||
) {
|
||||
@if (collapsed()) {
|
||||
<a
|
||||
mat-icon-button
|
||||
class="nav-icon-button"
|
||||
[routerLink]="item.disabled ? null : item.route"
|
||||
[queryParams]="item.queryParams || null"
|
||||
routerLinkActive="active"
|
||||
[routerLinkActiveOptions]="navLinkActiveOptions"
|
||||
[class.disabled]="item.disabled"
|
||||
[matTooltip]="item.label"
|
||||
matTooltipPosition="right"
|
||||
[attr.aria-label]="item.label">
|
||||
<mat-icon>{{ item.icon }}</mat-icon>
|
||||
</a>
|
||||
} @else {
|
||||
<a
|
||||
mat-list-item
|
||||
[routerLink]="item.disabled ? null : item.route"
|
||||
[queryParams]="item.queryParams || null"
|
||||
routerLinkActive="active"
|
||||
[routerLinkActiveOptions]="navLinkActiveOptions"
|
||||
[class.disabled]="item.disabled">
|
||||
<mat-icon matListItemIcon>{{ item.icon }}</mat-icon>
|
||||
<span matListItemTitle>{{ item.label }}</span>
|
||||
</a>
|
||||
}
|
||||
}
|
||||
}
|
||||
</mat-nav-list>
|
||||
@@ -102,7 +110,6 @@
|
||||
(credentialService.login | async) || 'Max Mustermann'
|
||||
}}</strong>
|
||||
<strong>{{ credentialService.organizationName | async }}</strong>
|
||||
<span>Startup Coach</span>
|
||||
</div>
|
||||
<mat-icon>expand_more</mat-icon>
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,16 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
|
||||
|
||||
type NavItem = {
|
||||
label: string;
|
||||
icon: string;
|
||||
route: string;
|
||||
disabled: boolean;
|
||||
queryParams?: Record<string, string | number | boolean>;
|
||||
adminOnly?: boolean;
|
||||
superAdminOnly?: boolean;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu',
|
||||
imports: [
|
||||
@@ -41,7 +51,7 @@ export class AppMenuComponent {
|
||||
matrixParams: 'ignored',
|
||||
fragment: 'ignored',
|
||||
};
|
||||
navItems = [
|
||||
navItems: NavItem[] = [
|
||||
{
|
||||
label: 'Dashboard',
|
||||
icon: 'dashboard',
|
||||
@@ -95,6 +105,14 @@ export class AppMenuComponent {
|
||||
icon: 'manage_accounts',
|
||||
route: '/accounts',
|
||||
disabled: false,
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
label: 'Organisationen',
|
||||
icon: 'domain',
|
||||
route: '/organizations',
|
||||
disabled: false,
|
||||
superAdminOnly: true,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -117,8 +135,15 @@ export class AppMenuComponent {
|
||||
});
|
||||
|
||||
dialogRef.componentInstance.confirmDelete.subscribe(() => {
|
||||
this.credentialService.logoutAcount();
|
||||
this.router.navigate(['/login']);
|
||||
this.credentialService.logoutAccount().subscribe({
|
||||
next: (result) => {
|
||||
if (result === 'stopped-impersonating') {
|
||||
this.router.navigate(['/accounts']);
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user