Support multiple roles in account services

This commit is contained in:
spsaefan
2026-07-13 11:03:57 +02:00
parent 1c535a872f
commit 13507c2ae8
2 changed files with 53 additions and 15 deletions
@@ -5,7 +5,13 @@ from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
from inse.auth.model import (
AccessTokenMetadata,
Account,
Organization,
UserRole,
normalize_roles,
)
from .model import (
AccountPage,
@@ -28,13 +34,17 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
return False
def _roles_allowed_for_editor(editor_role: UserRole, roles: list[UserRole]) -> bool:
return all(_role_allowed_for_editor(editor_role, role) for role in roles)
def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
organization_name = account.organization.name if account.organization else ""
return AccountProfile(
id=account.id,
email=account.email,
name=account.name,
role=account.role,
roles=normalize_roles(account.roles),
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
@@ -175,7 +185,7 @@ def create_account(
detail="Admins can only create accounts in their own organization.",
)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
@@ -194,7 +204,7 @@ def create_account(
account = Account(
email=email,
name=payload.name.strip(),
role=payload.role,
roles=payload.roles,
organization_id=payload.organization_id,
password_hash=auth_service._hash_password(payload.password),
openalex_person_id=payload.openalex_person_id,
@@ -261,15 +271,15 @@ def update_account(
if payload.openalex_person_id is not None:
account.openalex_person_id = payload.openalex_person_id
if payload.role is not None:
if payload.roles is not None:
if not can_admin_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
account.role = payload.role
account.roles = payload.roles
account.epoch += 1
if payload.organization_id is not None:
+36 -8
View File
@@ -28,6 +28,8 @@ from inse.auth.model import (
SecretPurpose,
TokenType,
UserRole,
effective_role_for_roles,
normalize_roles,
)
from inse.config import get_settings
from inse.database import get_session
@@ -44,6 +46,7 @@ PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
REAL_ACCOUNT_ID_KEY = "real_account_id"
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
EFFECTIVE_ROLE_KEY = "effective_role"
EFFECTIVE_ROLES_KEY = "effective_roles"
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EPOCH_KEY = "epoch"
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
@@ -110,14 +113,14 @@ def create_predefined_accounts(session: Session, file_path: str):
session.add(organization)
for account_data in data.get("accounts", []):
organization_id = uuid.UUID(account_data["organization_id"])
role = UserRole(account_data["role"])
roles = normalize_roles(account_data.get("roles", account_data.get("role")))
email = account_data["email"]
password_hash = _hash_password(account_data["password"])
account = Account(
email=email,
name=account_data["name"],
organization_id=organization_id,
role=role,
roles=roles,
password_hash=password_hash,
epoch=0,
)
@@ -609,6 +612,11 @@ def _get_current_user_access_token_payload(
),
epoch=access_token_payload[EPOCH_KEY],
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
effective_roles=normalize_roles(
access_token_payload.get(
EFFECTIVE_ROLES_KEY, access_token_payload[EFFECTIVE_ROLE_KEY]
)
),
effective_organization_id=uuid.UUID(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
@@ -649,6 +657,11 @@ def _get_current_user_refresh_token_payload(
),
epoch=refresh_token_payload[EPOCH_KEY],
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
effective_roles=normalize_roles(
refresh_token_payload.get(
EFFECTIVE_ROLES_KEY, refresh_token_payload[EFFECTIVE_ROLE_KEY]
)
),
effective_organization_id=uuid.UUID(
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
@@ -728,7 +741,7 @@ def _get_account_epoch(
return account.epoch
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
def _get_account_roles(session: Session, account_id: uuid.UUID) -> list[UserRole]:
"""Retrieves the role for the given account ID.
Args:
@@ -736,14 +749,14 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
Returns:
UserRole: The role associated with the given account ID.
list[UserRole]: The roles associated with the given account ID.
"""
account = session.get(Account, account_id)
if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.role
return normalize_roles(account.roles)
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
@@ -794,13 +807,16 @@ def _is_valid_impersonation(
):
raise AccountNotFoundException
if real_account.role == UserRole.SUPER_ADMIN:
real_account_role = effective_role_for_roles(real_account.roles)
effective_account_role = effective_role_for_roles(effective_account.roles)
if real_account_role == UserRole.SUPER_ADMIN:
return True # Super admins can impersonate any account
if real_account.organization_id != effective_account.organization_id:
return False # Cannot impersonate accounts from different organizations
if real_account.role == UserRole.ADMIN and effective_account.role in [
if real_account_role == UserRole.ADMIN and effective_account_role in [
UserRole.MANAGER,
UserRole.USER,
]:
@@ -847,7 +863,8 @@ def get_access_token(
detail="Impersonation not allowed",
)
role = _get_account_role(session=session, account_id=effective_account_id)
roles = _get_account_roles(session=session, account_id=effective_account_id)
role = effective_role_for_roles(roles)
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
organization_id = _get_account_organization(
session=session, account_id=effective_account_id
@@ -862,6 +879,7 @@ def get_access_token(
effective_organization_id=organization_id,
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=roles,
)
_set_refresh_token(
response=response,
@@ -870,6 +888,7 @@ def get_access_token(
effective_role=role,
effective_organization_id=organization_id,
epoch=epoch,
effective_roles=roles,
)
return AccessResponse(
access_token=access_token,
@@ -974,6 +993,7 @@ def refresh_access_token(
effective_organization_id=refresh_token.effective_organization_id,
epoch=refresh_token.epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=refresh_token.effective_roles,
)
@@ -1020,6 +1040,7 @@ def _set_refresh_token(
effective_role: UserRole,
effective_organization_id: uuid.UUID,
epoch: int,
effective_roles: list[UserRole] | None = None,
) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1038,10 +1059,12 @@ def _set_refresh_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
}
@@ -1058,6 +1081,7 @@ def _set_refresh_token(
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
)
@@ -1069,6 +1093,7 @@ def _build_access_token(
effective_organization_id: uuid.UUID,
epoch: int,
user_fingerprint_hash: str,
effective_roles: list[UserRole] | None = None,
) -> AccessToken:
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1087,10 +1112,12 @@ def _build_access_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
@@ -1108,6 +1135,7 @@ def _build_access_token(
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
user_fingerprint_hash=user_fingerprint_hash,
raw_token=raw_token,