Files
smartguide/service/src/main/inse/auth/model.py
T
2026-08-11 11:48:18 +02:00

357 lines
11 KiB
Python

import uuid
from datetime import datetime
from enum import StrEnum
from pydantic import BaseModel, model_validator
from sqlalchemy import JSON, Column, UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
class UserRole(StrEnum):
SUPER_ADMIN = "SUPER_ADMIN"
ADMIN = "ADMIN"
MANAGER = "MANAGER"
USER = "USER"
ROLE_PRIORITY = {
UserRole.SUPER_ADMIN: 0,
UserRole.ADMIN: 1,
UserRole.MANAGER: 2,
UserRole.USER: 3,
}
def normalize_roles(
roles: list[UserRole] | list[str] | UserRole | str | None,
) -> list[UserRole]:
if roles is None:
return [UserRole.USER]
if isinstance(roles, (str, UserRole)):
roles = [roles]
normalized = []
seen = set()
for role in roles:
user_role = role if isinstance(role, UserRole) else UserRole(role)
if user_role not in seen:
normalized.append(user_role)
seen.add(user_role)
return sorted(normalized or [UserRole.USER], key=lambda role: ROLE_PRIORITY[role])
def effective_role_for_roles(
roles: list[UserRole] | list[str] | UserRole | str | None,
) -> UserRole:
return normalize_roles(roles)[0]
class TokenType(StrEnum):
ID_TOKEN = "ID_TOKEN"
REFRESH_TOKEN = "REFRESH_TOKEN"
ACCESS_TOKEN = "ACCESS_TOKEN"
class SecretPurpose(StrEnum):
LOGIN_OTK = "LOGIN_OTK"
PASSWORD_RESET = "PASSWORD_RESET"
class Durable(SQLModel):
deleted: bool = Field(
default=False,
nullable=False,
index=True,
description="Indicates whether the record is marked as deleted.",
)
class Organization(Durable, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the organization. Generated automatically if not provided.",
)
name: str = Field(
index=True,
unique=True,
nullable=False,
description="The unique name of the organization.",
)
openalex_institution_id: str | None = Field(
default=None,
index=True,
description="The OpenAlex ID of the institution associated with the organization.",
)
accounts: list["Account"] = Relationship(back_populates="organization")
class OrganizationInstitution(SQLModel, table=True):
__tablename__ = "organization_institution"
__table_args__ = (
UniqueConstraint(
"organization_id",
"position",
name="uq_organization_institution_position",
),
)
organization_id: uuid.UUID = Field(
foreign_key="organization.id",
primary_key=True,
index=True,
)
openalex_institution_id: str = Field(primary_key=True, index=True)
position: int = Field(nullable=False)
class Account(Durable, table=True):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the account. Generated automatically if not provided.",
)
email: str = Field(
index=True,
unique=True,
nullable=False,
description="The email address associated with the account.",
)
name: str = Field(
index=True,
nullable=False,
description="The name of the account holder.",
)
openalex_person_id: str | None = Field(
default=None,
index=True,
description="The OpenAlex ID of the person associated with the account.",
)
epoch: int = Field(
default=0,
nullable=False,
description="The epoch value for the account. Used for versioning of tokens.",
)
activated: bool = Field(
default=True,
nullable=False,
index=True,
description="Indicates whether the account is allowed to authenticate.",
)
password_hash: str = Field(
index=False,
nullable=False,
description="The hashed password for the account using Argon2id algorithm.",
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
)
organization_id: uuid.UUID = Field(
foreign_key="organization.id",
nullable=False,
description="The unique identifier of the organization strictly associated with this account.",
)
roles: list[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
description="The roles this account holds within its organization.",
)
organization: Organization = Relationship(back_populates="accounts")
@property
def role(self) -> UserRole:
return effective_role_for_roles(self.roles)
@role.setter
def role(self, value: UserRole) -> None:
self.roles = normalize_roles(value)
class Secret(SQLModel, table=True):
__table_args__ = (
UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
)
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the secret. Generated automatically if not provided.",
)
account_id: uuid.UUID = Field(
foreign_key="account.id",
index=True,
nullable=False,
description="The unique identifier of the account associated with this secret.",
)
purpose: SecretPurpose = Field(
default=SecretPurpose.LOGIN_OTK,
index=True,
nullable=False,
description="The purpose of the secret, such as login OTK or password reset.",
)
secret_value: str = Field(
index=False,
nullable=False,
description="The actual secret value. This should be stored securely and encrypted.",
)
expires_at: datetime = Field(
index=True,
nullable=False,
description="The timestamp indicating when the secret will expire.",
)
request_count: int = Field(
default=0,
nullable=False,
description="The number of password reset requests in the current rate-limit window.",
)
request_window_started_at: datetime | None = Field(
default=None,
index=True,
description="The start timestamp of the current password reset request window.",
)
class BaseTokenData(BaseModel):
real_account_id: uuid.UUID = Field(
description="The unique identifier of the real account associated with this token.",
)
expires_at: datetime = Field(
description="The timestamp indicating when the token will expire.",
)
epoch: int = Field(
default=0,
description="The epoch value for the token. Used for versioning of tokens.",
)
class IdTokenMetadata(BaseTokenData):
token_type: TokenType = Field(
default=TokenType.ID_TOKEN,
const=True,
description="The type of the token, which is always ID_TOKEN for this class.",
)
class AccessTokenMetadata(BaseTokenData):
@model_validator(mode="before")
@classmethod
def _effective_role_to_roles(cls, values):
if (
isinstance(values, dict)
and "effective_roles" not in values
and "effective_role" in values
):
values = {**values, "effective_roles": [values["effective_role"]]}
return values
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
description="The type of the token, which is always ACCESS_TOKEN for this class.",
)
user_fingerprint_hash: str = Field(
description="A unique fingerprint of the user, used for additional security checks.",
)
effective_account_id: uuid.UUID = Field(
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
)
effective_role: UserRole = Field(
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: list[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
effective_institution_id: str | None = Field(
default=None,
description="The OpenAlex institution ID associated with this access token, if applicable.",
)
def is_impersonating(self) -> bool:
"""Determine if the access token is being used for impersonation.
Returns:
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
"""
return self.effective_account_id != self.real_account_id
class AccessToken(AccessTokenMetadata):
raw_token: str = Field(
description="The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.",
)
class RefreshTokenMetadata(BaseTokenData):
@model_validator(mode="before")
@classmethod
def _effective_role_to_roles(cls, values):
if (
isinstance(values, dict)
and "effective_roles" not in values
and "effective_role" in values
):
values = {**values, "effective_roles": [values["effective_role"]]}
return values
token_type: TokenType = Field(
default=TokenType.REFRESH_TOKEN,
const=True,
description="The type of the token, which is always REFRESH_TOKEN for this class.",
)
effective_account_id: uuid.UUID = Field(
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
)
effective_role: UserRole = Field(
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: list[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
effective_institution_id: str | None = Field(
default=None,
description="The OpenAlex institution ID associated with this access token, if applicable.",
)
class RefreshToken(RefreshTokenMetadata):
raw_token: str = Field(
description="The raw string representation of the refresh token. This is the actual token that can be used to obtain new access tokens.",
)
class LoginResponse(BaseModel):
id_token: IdTokenMetadata = Field(
description="The ID token issued upon successful login."
)
class AccessResponse(BaseModel):
access_token: AccessToken = Field(
description="The access token issued upon successful authentication."
)
class OtkResponse(BaseModel):
status: str = Field(description="The status of the one-time code (OTC) request.")
account_id: uuid.UUID = Field(
description="The unique identifier of the account for which the OTC was requested."
)