Skip to content

Authentication & Permissions

HyperAdmin has two auth modes. With built-in auth the admin keeps its own users, groups and permissions in the hyperadmin_* tables (User, Group, Permission) and signs users in with SessionAuthBackend. With bring your own auth you pass Admin(auth=ExternalAuth(...)) and the host application decides who the user is and what they may do; see Bring Your Own Auth.

from hyperadmin import Admin
from hyperadmin.auth.permissions import ModelPermissionChecker, PermissionSyncService
from hyperadmin.auth.session import SessionAuthBackend

admin = Admin(
    app,
    engine=engine,
    auth_backend=SessionAuthBackend(engine),
    permission_checker=ModelPermissionChecker(engine),
    permission_registry=PermissionSyncService(engine),
)

hyperadmin.auth.metadata() returns the built-in tables as an Alembic target_metadata.

Permission codenames

The admin asks for view_<model>, add_<model>, change_<model>, delete_<model>, export_<model> (the list's Export menu, see Import and export) and, for a custom action, action_<name>_<model> (for example action_archive_order). <model> is the lowercased model class name, so two models with an action of the same name have separate permissions.

A detail-page panel checks view_<model>_panel_<slug>, or the permission= it was declared with.

At startup PermissionSyncService creates, for every registered model:

  • the five view_, add_, change_, delete_ and export_ codenames;
  • one action_<name>_<model> codename per @action method of its ModelAdmin;
  • the codename of every detail panel (AdminOptions.panels and @panel methods);
  • the extra codenames listed in ModelAdmin.permissions.

Existing rows are never changed or removed. Grant the new codenames to a group or a user like the defaults. export_<model> is granted to no one: until you grant it, only superusers can export a list.

Earlier docs said action_<name>

The model-level check has always been action_<name>_<model>; earlier versions of these pages named it action_<name>. The object-level check (AdminOptions.object_permission_checker) receives action_<name>, without the model, because the checker is already given the object.

Extra codenames: ModelAdmin.permissions

A ModelAdmin can declare codenames of its own, for checks you make in your own code (an action handler, a custom view, a template). Set permissions to a list of (codename, name) pairs; PermissionSyncService creates them at startup and the permissions matrix shows them as extra columns of the model's row:

class OrderAdmin(ModelAdmin):
    permissions = [
        ("approve_order", "Can approve orders"),
        ("refund_order", "Can refund orders"),
    ]

Check one with the admin's permission checker, for example await admin.permission_checker.has_permission(user, "refund_order").

Permissions matrix

With built-in auth (or bring-your-own-auth with register_auth_models=True), the "Access" sidebar group has a permissions matrix at {prefix}/permissions-matrix/: one row per model, one column per codename, for the group you pick. A save writes only the cells that changed. When someone else saved the same group in the meantime, the page shows a conflict banner instead of overwriting their change. Every change is written to the hyperadmin_permission_audit table.

Permission matrix: view, add, change and delete grants per model for the Bookkeepers group

Superusers can always open it; other users need the permissions_matrix_codename permission (change_groups_permissions by default). permissions_matrix_enabled=False leaves the page out. The tables it needs are listed in Upgrading the built-in auth tables.

Caches

ModelPermissionChecker remembers the permission set it read on the user object for the rest of the request; call forget_user_permissions(user) after a write that changes it. With user_cache_ttl set, the signed-in user is also cached per worker; call invalidate_user(user_id) after you change a user outside the admin.

API Reference

hyperadmin.auth.ExternalAuth dataclass

Bring-your-own-auth configuration for Admin(auth=...).

Only get_user is required. Every other field has a fail-safe default; see docs/specs/bring-your-own-app.md section B.3.

Source code in src/hyperadmin/auth/bridge.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
@dataclass(frozen=True, slots=True, kw_only=True)
class ExternalAuth:
    """Bring-your-own-auth configuration for ``Admin(auth=...)``.

    Only ``get_user`` is required. Every other field has a fail-safe default;
    see ``docs/specs/bring-your-own-app.md`` section B.3.
    """

    #: Any FastAPI dependency resolving the current host user, or ``None`` for
    #: an anonymous request. Resolved as a sub-dependency of
    #: :func:`build_admin_dependency`, so host overrides, ``yield`` dependencies
    #: and ``request.app.state`` reads all work normally.
    get_user: Callable[..., Any]
    can_access: Callable[[Any], MaybeAwaitable[bool]] = default_can_access
    has_permission: Callable[[Any, str], MaybeAwaitable[bool]] | PermissionChecker | None = None
    login_url: str | None = None
    logout_url: str | None = None
    next_param: str = "next"
    display_name: Callable[[Any], str] = default_display_name
    user_key: Callable[[Any], Hashable] = default_user_key
    token_cookie: TokenCookie | None = None
    websocket_user: Callable[[WebSocket], Awaitable[Any | None]] | None = None
    #: Without ``has_permission``: ``False`` (default) means the fail-safe
    #: default grants a superuser everything and everyone else ``view_*`` only.
    #: ``True`` grants every permission to anyone who already passed
    #: ``can_access``. See :class:`BridgeDefaultPermissionChecker`.
    allow_full_access: bool = False

hyperadmin.auth.TokenCookie dataclass

Bridges a bearer token into an HttpOnly cookie for bearer-only hosts.

Opt-in: set ExternalAuth(token_cookie=TokenCookie()). See docs/specs/bring-your-own-app.md section B.4.

Source code in src/hyperadmin/auth/bridge.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@dataclass(frozen=True, slots=True, kw_only=True)
class TokenCookie:
    """Bridges a bearer token into an ``HttpOnly`` cookie for bearer-only hosts.

    Opt-in: set ``ExternalAuth(token_cookie=TokenCookie())``. See
    ``docs/specs/bring-your-own-app.md`` section B.4.
    """

    name: str = "hyperadmin_token"
    scheme: str = "Bearer"
    max_age: int | None = 8 * 3600
    handoff_path: str = "/auth/session"
    #: Opt-in admin login form for bearer-only hosts (B.4): a token URL, or an
    #: ``issue_token(username, password) -> token | None`` callable.
    token_endpoint: str | Callable[[str, str], MaybeAwaitable[str | None]] | None = None

hyperadmin.auth.session.SessionAuthBackend

Cookie-session authentication backed by an async engine or session factory.

Source code in src/hyperadmin/auth/session.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class SessionAuthBackend:
    """Cookie-session authentication backed by an async engine or session factory."""

    def __init__(
        self, engine: AsyncEngine | None = None, *, session_factory: SessionFactory | None = None
    ) -> None:
        require_engine_or_session_factory("SessionAuthBackend", engine, session_factory)
        self.engine = engine
        self.session_factory = session_factory

    def _session(self) -> AbstractAsyncContextManager[AsyncSessionLike]:
        """Open a session from whichever of ``engine`` / ``session_factory`` was given."""
        return open_session(self.engine, self.session_factory)

    async def authenticate(self, username: str, password: str) -> User | None:
        """Return the user if credentials are valid, else ``None``."""
        async with self._session() as session:
            stmt = select(User).where(User.username == username)
            user = (await session.execute(stmt)).scalar_one_or_none()
            if user is None:
                return None
            if not user.is_active:
                return None
            if not verify_password(password, user.password_hash):
                return None
            return user

    async def login(self, request: Any, user: User) -> None:
        """Start a fresh session holding only the user ID.

        Pre-login state (a stale partial-auth marker, OTP records, or keys
        planted in the cookie) is dropped, so a privilege change never
        carries it into the authenticated session.
        """
        request.session.clear()
        request.session["user_id"] = user.id

    async def logout(self, request: Any) -> None:
        """Clear the whole session, not just the user ID."""
        request.session.clear()

    async def get_current_user(self, request: Any) -> User | None:
        """Resolve the current user from the session, or ``None``."""
        user_id = request.session.get("user_id")
        if user_id is None:
            return None
        async with self._session() as session:
            # The per-request auth load needs only the user row. ``noload`` skips the
            # model's ``lazy="selectin"`` group/permission queries (3 SELECTs -> 1);
            # permissions are resolved by id in ``ModelPermissionChecker``.
            stmt = (
                select(User)
                .where(User.id == user_id)
                .options(noload(User.user_groups), noload(User.user_permissions))  # type: ignore[arg-type]
            )
            return (await session.execute(stmt)).scalar_one_or_none()

authenticate(username, password) async

Return the user if credentials are valid, else None.

Source code in src/hyperadmin/auth/session.py
40
41
42
43
44
45
46
47
48
49
50
51
async def authenticate(self, username: str, password: str) -> User | None:
    """Return the user if credentials are valid, else ``None``."""
    async with self._session() as session:
        stmt = select(User).where(User.username == username)
        user = (await session.execute(stmt)).scalar_one_or_none()
        if user is None:
            return None
        if not user.is_active:
            return None
        if not verify_password(password, user.password_hash):
            return None
        return user

get_current_user(request) async

Resolve the current user from the session, or None.

Source code in src/hyperadmin/auth/session.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
async def get_current_user(self, request: Any) -> User | None:
    """Resolve the current user from the session, or ``None``."""
    user_id = request.session.get("user_id")
    if user_id is None:
        return None
    async with self._session() as session:
        # The per-request auth load needs only the user row. ``noload`` skips the
        # model's ``lazy="selectin"`` group/permission queries (3 SELECTs -> 1);
        # permissions are resolved by id in ``ModelPermissionChecker``.
        stmt = (
            select(User)
            .where(User.id == user_id)
            .options(noload(User.user_groups), noload(User.user_permissions))  # type: ignore[arg-type]
        )
        return (await session.execute(stmt)).scalar_one_or_none()

login(request, user) async

Start a fresh session holding only the user ID.

Pre-login state (a stale partial-auth marker, OTP records, or keys planted in the cookie) is dropped, so a privilege change never carries it into the authenticated session.

Source code in src/hyperadmin/auth/session.py
53
54
55
56
57
58
59
60
61
async def login(self, request: Any, user: User) -> None:
    """Start a fresh session holding only the user ID.

    Pre-login state (a stale partial-auth marker, OTP records, or keys
    planted in the cookie) is dropped, so a privilege change never
    carries it into the authenticated session.
    """
    request.session.clear()
    request.session["user_id"] = user.id

logout(request) async

Clear the whole session, not just the user ID.

Source code in src/hyperadmin/auth/session.py
63
64
65
async def logout(self, request: Any) -> None:
    """Clear the whole session, not just the user ID."""
    request.session.clear()

hyperadmin.auth.permissions.ModelPermissionChecker

Checks user permissions via direct grants and group inheritance.

Source code in src/hyperadmin/auth/permissions.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
class ModelPermissionChecker:
    """Checks user permissions via direct grants and group inheritance."""

    def __init__(
        self, engine: AsyncEngine | None = None, *, session_factory: SessionFactory | None = None
    ) -> None:
        require_engine_or_session_factory("ModelPermissionChecker", engine, session_factory)
        self.engine = engine
        self.session_factory = session_factory

    def _session(self) -> AbstractAsyncContextManager[AsyncSessionLike]:
        """Open a session from whichever of ``engine`` / ``session_factory`` was given."""
        return open_session(self.engine, self.session_factory)

    async def has_permission(self, user: User, codename: str) -> bool:
        """Return ``True`` if the user holds the given permission."""
        if user.is_superuser:
            return True
        return codename in await self._resolve(user)

    async def get_user_permissions(self, user: User) -> set[str]:
        """Return the union of direct + group-inherited permission codenames.

        The set is read once per user object and remembered on it, so every later check
        for the same object (one request) costs no query. The caller gets its own copy.
        """
        return set(await self._resolve(user))

    async def _resolve(self, user: User) -> frozenset[str]:
        """Return the user's permission set, reading it at most once per user object."""
        store = _resolved_store(user)
        # Keyed by checker too, so two checkers on different databases never share a set.
        resolved = store.get(_RESOLVED_KEY) if store is not None else None
        if resolved is not None and resolved[0] is self:
            permissions: frozenset[str] = resolved[1]
            return permissions
        permissions = await self._load(user.id)
        if store is not None:
            store[_RESOLVED_KEY] = (self, permissions)
        return permissions

    async def _load(self, user_id: Any) -> frozenset[str]:
        """Read direct and group-inherited codenames in one session (two statements)."""
        async with self._session() as session:
            # Direct permissions
            stmt = (
                select(Permission.codename)
                .join(
                    UserPermission,
                    UserPermission.permission_id == Permission.id,  # type: ignore[arg-type]
                )
                .where(UserPermission.user_id == user_id)
            )
            direct = set((await session.execute(stmt)).scalars().all())

            # Group-inherited permissions
            stmt = (
                select(Permission.codename)
                .join(
                    GroupPermission,
                    GroupPermission.permission_id == Permission.id,  # type: ignore[arg-type]
                )
                .join(Group, Group.id == GroupPermission.group_id)  # type: ignore[arg-type]
                .join(UserGroup, UserGroup.group_id == Group.id)  # type: ignore[arg-type]
                .where(UserGroup.user_id == user_id)
            )
            inherited = set((await session.execute(stmt)).scalars().all())

            return frozenset(direct | inherited)

get_user_permissions(user) async

Return the union of direct + group-inherited permission codenames.

The set is read once per user object and remembered on it, so every later check for the same object (one request) costs no query. The caller gets its own copy.

Source code in src/hyperadmin/auth/permissions.py
186
187
188
189
190
191
192
async def get_user_permissions(self, user: User) -> set[str]:
    """Return the union of direct + group-inherited permission codenames.

    The set is read once per user object and remembered on it, so every later check
    for the same object (one request) costs no query. The caller gets its own copy.
    """
    return set(await self._resolve(user))

has_permission(user, codename) async

Return True if the user holds the given permission.

Source code in src/hyperadmin/auth/permissions.py
180
181
182
183
184
async def has_permission(self, user: User, codename: str) -> bool:
    """Return ``True`` if the user holds the given permission."""
    if user.is_superuser:
        return True
    return codename in await self._resolve(user)

hyperadmin.auth.permissions.PermissionSyncService

Syncs auto-generated and custom permissions to the database on startup.

Source code in src/hyperadmin/auth/permissions.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
class PermissionSyncService:
    """Syncs auto-generated and custom permissions to the database on startup."""

    def __init__(
        self, engine: AsyncEngine | None = None, *, session_factory: SessionFactory | None = None
    ) -> None:
        require_engine_or_session_factory("PermissionSyncService", engine, session_factory)
        self.engine = engine
        self.session_factory = session_factory

    def _session(self) -> AbstractAsyncContextManager[AsyncSessionLike]:
        """Open a session from whichever of ``engine`` / ``session_factory`` was given."""
        return open_session(self.engine, self.session_factory)

    async def sync_permissions(self, registered_models: list[Any]) -> None:
        """Create missing permissions for all registered models.

        Args:
            registered_models: List of ``(model_name, admin_class)`` tuples.
        """
        async with self._session() as session:
            existing = (await session.execute(select(Permission.codename))).scalars().all()
            existing_set = set(existing)

            to_create: list[Permission] = []
            for model_name, admin_class in registered_models:
                # Default CRUD permissions
                for codename, name in generate_default_permissions(model_name):
                    if codename not in existing_set:
                        to_create.append(
                            Permission(codename=codename, name=name, content_type=model_name)
                        )
                        existing_set.add(codename)

                # ModelAdmin.permissions, @action and detail-panel codenames
                for codename, name in generate_admin_permissions(model_name, admin_class):
                    if codename not in existing_set:
                        to_create.append(
                            Permission(codename=codename, name=name, content_type=model_name)
                        )
                        existing_set.add(codename)

            if to_create:
                session.add_all(to_create)
                await session.commit()

    async def sync_codenames(self, permissions: Iterable[tuple[str, str, str | None]]) -> None:
        """Create missing permissions that belong to no model (e.g. plugin codenames).

        Args:
            permissions: ``(codename, name, content_type)`` tuples; existing
                codenames are left untouched.
        """
        async with self._session() as session:
            existing = set((await session.execute(select(Permission.codename))).scalars().all())
            to_create: list[Permission] = []
            for codename, name, content_type in permissions:
                if codename not in existing:
                    to_create.append(
                        Permission(codename=codename, name=name, content_type=content_type)
                    )
                    existing.add(codename)
            if to_create:
                session.add_all(to_create)
                await session.commit()

sync_codenames(permissions) async

Create missing permissions that belong to no model (e.g. plugin codenames).

Parameters:

Name Type Description Default
permissions Iterable[tuple[str, str, str | None]]

(codename, name, content_type) tuples; existing codenames are left untouched.

required
Source code in src/hyperadmin/auth/permissions.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
async def sync_codenames(self, permissions: Iterable[tuple[str, str, str | None]]) -> None:
    """Create missing permissions that belong to no model (e.g. plugin codenames).

    Args:
        permissions: ``(codename, name, content_type)`` tuples; existing
            codenames are left untouched.
    """
    async with self._session() as session:
        existing = set((await session.execute(select(Permission.codename))).scalars().all())
        to_create: list[Permission] = []
        for codename, name, content_type in permissions:
            if codename not in existing:
                to_create.append(
                    Permission(codename=codename, name=name, content_type=content_type)
                )
                existing.add(codename)
        if to_create:
            session.add_all(to_create)
            await session.commit()

sync_permissions(registered_models) async

Create missing permissions for all registered models.

Parameters:

Name Type Description Default
registered_models list[Any]

List of (model_name, admin_class) tuples.

required
Source code in src/hyperadmin/auth/permissions.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
async def sync_permissions(self, registered_models: list[Any]) -> None:
    """Create missing permissions for all registered models.

    Args:
        registered_models: List of ``(model_name, admin_class)`` tuples.
    """
    async with self._session() as session:
        existing = (await session.execute(select(Permission.codename))).scalars().all()
        existing_set = set(existing)

        to_create: list[Permission] = []
        for model_name, admin_class in registered_models:
            # Default CRUD permissions
            for codename, name in generate_default_permissions(model_name):
                if codename not in existing_set:
                    to_create.append(
                        Permission(codename=codename, name=name, content_type=model_name)
                    )
                    existing_set.add(codename)

            # ModelAdmin.permissions, @action and detail-panel codenames
            for codename, name in generate_admin_permissions(model_name, admin_class):
                if codename not in existing_set:
                    to_create.append(
                        Permission(codename=codename, name=name, content_type=model_name)
                    )
                    existing_set.add(codename)

        if to_create:
            session.add_all(to_create)
            await session.commit()

hyperadmin.auth.permissions.forget_user_permissions(user)

Drop the permission set remembered on user; the next check reads it again.

Call it after a write that may change what this user object holds while the object is still in use (the permissions matrix does, after a save).

Source code in src/hyperadmin/auth/permissions.py
56
57
58
59
60
61
62
63
64
def forget_user_permissions(user: Any) -> None:
    """Drop the permission set remembered on ``user``; the next check reads it again.

    Call it after a write that may change what this user object holds while the object
    is still in use (the permissions matrix does, after a save).
    """
    store = _resolved_store(user)
    if store is not None:
        store.pop(_RESOLVED_KEY, None)

hyperadmin.auth.user_cache.invalidate_user(user_id)

Drop user_id from every cache in this process.

Source code in src/hyperadmin/auth/user_cache.py
125
126
127
128
def invalidate_user(user_id: Any) -> None:
    """Drop ``user_id`` from every cache in this process."""
    for cache in list(_CACHES):
        cache.invalidate(user_id)

hyperadmin.auth.metadata()

Return a new MetaData holding only the built-in hyperadmin_* tables.

Intended as an Alembic target_metadata (or one of several) for hosts that use built-in auth (Admin(auth_backend=...))::

import hyperadmin.auth

target_metadata = [Base.metadata, hyperadmin.auth.metadata()]

The returned object is a copy: host tables are never included, and changing it does not affect SQLModel.metadata.

Note

Calling this imports hyperadmin.auth.models. SQLModel table classes register on the global SQLModel.metadata when they are imported, so after this call the hyperadmin_* tables are also part of that process's SQLModel.metadata (and of any autogenerate target built from it). Hosts that bring their own auth should not call it; doing so after a bridge-mode Admin was built logs a WARNING.

Source code in src/hyperadmin/auth/__init__.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def metadata() -> MetaData:
    """Return a new ``MetaData`` holding only the built-in ``hyperadmin_*`` tables.

    Intended as an Alembic ``target_metadata`` (or one of several) for hosts
    that use **built-in auth** (``Admin(auth_backend=...)``)::

        import hyperadmin.auth

        target_metadata = [Base.metadata, hyperadmin.auth.metadata()]

    The returned object is a copy: host tables are never included, and changing
    it does not affect ``SQLModel.metadata``.

    Note:
        Calling this imports ``hyperadmin.auth.models``. SQLModel table classes
        register on the global ``SQLModel.metadata`` when they are imported, so
        after this call the ``hyperadmin_*`` tables are also part of that
        process's ``SQLModel.metadata`` (and of any autogenerate target built
        from it). Hosts that bring their own auth should not call it; doing so
        after a bridge-mode ``Admin`` was built logs a WARNING.
    """
    if _bridge_admin_constructed:
        _logger.warning(
            "hyperadmin.auth.metadata() called while an Admin in bridge mode (auth=) "
            "exists: the built-in hyperadmin_* tables are now registered on "
            "SQLModel.metadata and will appear in Alembic autogenerate. Bridge-mode "
            "hosts do not need them."
        )
    importlib.import_module(_MODELS_MODULE)
    # The filter library's saved-views table (v0.5.6) is a hyperadmin_* table
    # every mounted admin uses, in both auth modes; register it here too so
    # init-db and Alembic hosts see it without having imported the views.
    importlib.import_module("hyperadmin.filters.saved_views")
    # The sidebar pins table (v0.5.9), used whenever auth is configured.
    importlib.import_module("hyperadmin.navigation.pins")
    target = MetaData()
    for table in SQLModel.metadata.sorted_tables:
        if table.name.startswith(_TABLE_PREFIX):
            table.to_metadata(target)
    return target

hyperadmin.auth.User

Bases: SQLModel

User model for authentication.

Source code in src/hyperadmin/auth/models.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class User(SQLModel, table=True):
    """User model for authentication."""

    __tablename__ = "hyperadmin_users"  # type: ignore[reportIncompatibleVariableOverride]

    id: int | None = Field(default=None, primary_key=True)
    username: str = Field(index=True, max_length=50, unique=True)
    email: str = Field(index=True, max_length=100, unique=True)
    password_hash: str = Field(
        max_length=255, schema_extra={"json_schema_extra": {"hyperadmin_sensitive": True}}
    )
    first_name: str = Field(default="", max_length=50)
    last_name: str = Field(default="", max_length=50)
    is_active: bool = Field(default=True)
    is_superuser: bool = Field(default=False)
    # MFA fields (additive, backward compatible — existing rows default to disabled, no
    # migration required). ``mfa_method`` is a free-form string rather than an Enum so
    # future methods (totp/sms/webauthn) can be added without a breaking schema change;
    # validation of allowed values lives in the service layer. For the MVP only "email"
    # is wired end-to-end — see docs/specs/object-permissions-mfa.md (Track B).
    mfa_enabled: bool = Field(default=False)
    mfa_method: str | None = Field(default=None, max_length=32)
    created_at: datetime = Field(default_factory=utc_now, sa_type=UTCNaiveDateTime)
    updated_at: datetime | None = Field(default=None, sa_type=UTCNaiveDateTime)

    user_groups: list["UserGroup"] = Relationship(
        back_populates="user",
        sa_relationship_kwargs={
            "foreign_keys": "UserGroup.user_id",
            "lazy": "selectin",
        },
    )
    user_permissions: list["UserPermission"] = Relationship(
        back_populates="user",
        sa_relationship_kwargs={
            "foreign_keys": "UserPermission.user_id",
            "lazy": "selectin",
        },
    )

    @property
    def oauth_only(self) -> bool:
        """``True`` when no password can sign this user in (created by an OAuth sign-in)."""
        return not is_password_usable(self.password_hash)

    def __str__(self) -> str:
        if self.first_name or self.last_name:
            return f"{self.first_name} {self.last_name}".strip()
        return self.username

oauth_only property

True when no password can sign this user in (created by an OAuth sign-in).

hyperadmin.auth.Group

Bases: SQLModel

Group model for organizing users and assigning permissions.

Source code in src/hyperadmin/auth/models.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Group(SQLModel, table=True):
    """Group model for organizing users and assigning permissions."""

    __tablename__ = "hyperadmin_groups"  # type: ignore[reportIncompatibleVariableOverride]

    id: int | None = Field(default=None, primary_key=True)
    name: str = Field(index=True, max_length=80, unique=True)
    description: str | None = Field(default=None, max_length=255)
    is_active: bool = Field(default=True)
    created_at: datetime = Field(default_factory=utc_now, sa_type=UTCNaiveDateTime)
    # Optimistic-concurrency stamp of the permission matrix; see docs/specs/permission-matrix-ui.md
    permissions_version: int = Field(default=0, sa_column_kwargs={"server_default": "0"})

    user_groups: list["UserGroup"] = Relationship(
        back_populates="group",
        sa_relationship_kwargs={
            "foreign_keys": "UserGroup.group_id",
            "lazy": "selectin",
        },
    )
    group_permissions: list["GroupPermission"] = Relationship(
        back_populates="group",
        sa_relationship_kwargs={
            "foreign_keys": "GroupPermission.group_id",
            "lazy": "selectin",
        },
    )

    def __str__(self) -> str:
        return self.name

hyperadmin.auth.Permission

Bases: SQLModel

Permission model with unique codename for authorization checks.

Source code in src/hyperadmin/auth/models.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class Permission(SQLModel, table=True):
    """Permission model with unique codename for authorization checks."""

    __tablename__ = "hyperadmin_permissions"  # type: ignore[reportIncompatibleVariableOverride]

    id: int | None = Field(default=None, primary_key=True)
    codename: str = Field(index=True, max_length=100, unique=True)
    name: str = Field(max_length=200)
    content_type: str | None = Field(default=None, max_length=100)
    created_at: datetime = Field(default_factory=utc_now, sa_type=UTCNaiveDateTime)

    user_permissions: list["UserPermission"] = Relationship(
        back_populates="permission",
        sa_relationship_kwargs={
            "foreign_keys": "UserPermission.permission_id",
            "lazy": "selectin",
        },
    )
    group_permissions: list["GroupPermission"] = Relationship(
        back_populates="permission",
        sa_relationship_kwargs={
            "foreign_keys": "GroupPermission.permission_id",
            "lazy": "selectin",
        },
    )

    def __str__(self) -> str:
        return self.name

OAuth sign-in

These names need the oauth extra and are imported from hyperadmin on first access.

hyperadmin.auth.oauth.OAuthBackend

OAuth2/OIDC sign-in for the built-in users.

Pass it to Admin(oauth_backend=...) next to auth_backend=::

Admin(
    app,
    engine=engine,
    auth_backend=SessionAuthBackend(engine=engine),
    oauth_backend=OAuthBackend(
        providers={"google": google_provider(client_id, client_secret)}
    ),
)

Parameters:

Name Type Description Default
providers Mapping[str, OAuthProviderConfig]

Provider configurations by name; each key must equal its configuration's name.

required
session_factory SessionFactory | None

Session factory to store users and tokens with. When neither it nor engine is given, Admin binds its own.

None
engine Any

An async SQLAlchemy engine, as an alternative to session_factory.

None
tenant_resolver Callable[[Any], Any] | None

Maps the value of a provider's tenant_id_claim to a tenant id when a user is created; return None for "no tenant".

None
transport Any

httpx transport for every provider call (tests, proxies).

None
timeout float

Seconds a provider call may take.

10.0

Raises:

Type Description
OAuthConfigError

No provider, a key that differs from its provider name, or the oauth extra is not installed.

Source code in src/hyperadmin/auth/oauth/backend.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
class OAuthBackend:
    """OAuth2/OIDC sign-in for the built-in users.

    Pass it to ``Admin(oauth_backend=...)`` next to ``auth_backend=``::

        Admin(
            app,
            engine=engine,
            auth_backend=SessionAuthBackend(engine=engine),
            oauth_backend=OAuthBackend(
                providers={"google": google_provider(client_id, client_secret)}
            ),
        )

    Args:
        providers: Provider configurations by name; each key must equal its
            configuration's ``name``.
        session_factory: Session factory to store users and tokens with. When
            neither it nor ``engine`` is given, ``Admin`` binds its own.
        engine: An async SQLAlchemy engine, as an alternative to ``session_factory``.
        tenant_resolver: Maps the value of a provider's ``tenant_id_claim`` to a
            tenant id when a user is created; return ``None`` for "no tenant".
        transport: ``httpx`` transport for every provider call (tests, proxies).
        timeout: Seconds a provider call may take.

    Raises:
        OAuthConfigError: No provider, a key that differs from its provider name,
            or the ``oauth`` extra is not installed.
    """

    def __init__(
        self,
        providers: Mapping[str, OAuthProviderConfig],
        session_factory: SessionFactory | None = None,
        *,
        engine: Any = None,
        tenant_resolver: Callable[[Any], Any] | None = None,
        transport: Any = None,
        timeout: float = 10.0,
    ) -> None:
        if not providers:
            msg = "OAuthBackend needs at least one provider."
            raise OAuthConfigError(msg)
        for key, config in providers.items():
            if key != config.name:
                msg = f"OAuth provider key {key!r} must equal its name {config.name!r}."
                raise OAuthConfigError(msg)
        self.providers: dict[str, OAuthProviderConfig] = dict(providers)
        self.session_factory = session_factory
        self.engine = engine
        self.tenant_resolver = tenant_resolver
        self._clients = {
            name: _build_client(config, transport, timeout)
            for name, config in self.providers.items()
        }
        self._refresh_locks: weakref.WeakValueDictionary[tuple[int, str], asyncio.Lock] = (
            weakref.WeakValueDictionary()
        )

    # ── Wiring ────────────────────────────────────────────────────────────

    def bind(self, *, engine: Any = None, session_factory: SessionFactory | None = None) -> None:
        """Use ``engine`` / ``session_factory`` unless the backend already has its own."""
        if self.engine is None and self.session_factory is None:
            self.engine = engine
            self.session_factory = session_factory

    def provider(self, name: str) -> OAuthProviderConfig | None:
        """Return the provider configured as ``name``, or ``None``."""
        return self.providers.get(name)

    def _config(self, name: str) -> OAuthProviderConfig:
        config = self.providers.get(name)
        if config is None:
            msg = f"OAuth provider {name!r} is not configured."
            raise OAuthConfigError(msg)
        return config

    def _session(self) -> AbstractAsyncContextManager[AsyncSessionLike]:
        if self.engine is None and self.session_factory is None:
            msg = (
                "OAuthBackend has no database: pass engine= or session_factory=, or hand "
                "it to Admin(oauth_backend=...)."
            )
            raise OAuthConfigError(msg)
        return open_session(self.engine, self.session_factory)

    # ── Provider calls ────────────────────────────────────────────────────

    async def authorization_url(
        self, provider: str, redirect_uri: str, state: str, code_verifier: str
    ) -> str:
        """Return the provider URL the browser is sent to, with ``state`` and PKCE."""
        config = self._config(provider)
        return await self._clients[provider].get_authorization_url(
            redirect_uri,
            state=state,
            code_challenge=pkce_challenge(code_verifier),
            code_challenge_method="S256",
            extras_params=dict(config.authorize_params) or None,
        )

    async def exchange_code(
        self, provider: str, code: str, redirect_uri: str, code_verifier: str | None = None
    ) -> dict[str, Any]:
        """Exchange an authorization ``code`` for tokens.

        Returns:
            The token response: ``access_token``, and when the provider sends them
            ``refresh_token``, ``expires_at`` (epoch seconds) and ``scope``.

        Raises:
            OAuthProviderError: The provider rejected the code or was unreachable.
        """
        self._config(provider)
        from httpx_oauth.oauth2 import GetAccessTokenError  # noqa: PLC0415

        try:
            token = await self._clients[provider].get_access_token(
                code, redirect_uri, code_verifier
            )
        except GetAccessTokenError as exc:
            raise self._request_error(provider, "Token exchange failed", exc) from exc
        return self._checked_token(provider, token, "Token exchange failed")

    async def get_userinfo(self, provider: str, access_token: str) -> dict[str, Any]:
        """Return the provider's profile of the token's user.

        When the profile has no email and the provider has an ``emails_url``
        (GitHub), the primary verified address is looked up and added.

        Raises:
            OAuthProviderError: The provider refused the token or was unreachable.
        """
        config = self._config(provider)
        claims = await self._get_json(provider, config.userinfo_url, access_token)
        if not isinstance(claims, dict):
            raise OAuthProviderError(provider, "Userinfo is not a JSON object")
        if not claims.get(config.email_claim) and config.emails_url:
            emails = await self._get_json(provider, config.emails_url, access_token)
            email = _primary_email(emails)
            if email:
                claims[config.email_claim] = email
        return claims

    async def _get_json(self, provider: str, url: str, access_token: str) -> Any:
        import httpx  # noqa: PLC0415

        headers = {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
        try:
            async with self._clients[provider].get_httpx_client() as http:
                response = await http.get(url, headers=headers)
        except httpx.HTTPError as exc:
            detail = "Userinfo request failed: provider unreachable"
            raise OAuthProviderError(provider, detail, transient=True) from exc
        if response.is_error:
            raise OAuthProviderError(
                provider,
                f"Userinfo request failed (HTTP {response.status_code})",
                error_code=_error_code(response),
                transient=response.status_code >= _SERVER_ERROR,
            )
        try:
            return response.json()
        except ValueError as exc:
            raise OAuthProviderError(provider, "Userinfo is not valid JSON") from exc

    @staticmethod
    def _request_error(provider: str, what: str, exc: Any) -> OAuthProviderError:
        """Turn an ``httpx-oauth`` request error into an :class:`OAuthProviderError`."""
        response = getattr(exc, "response", None)
        if response is None:
            return OAuthProviderError(provider, f"{what}: provider unreachable", transient=True)
        code = _error_code(response)
        detail = f"{what} (HTTP {response.status_code}{f', {code}' if code else ''})"
        return OAuthProviderError(
            provider,
            detail,
            error_code=code,
            transient=response.status_code >= _SERVER_ERROR,
        )

    @staticmethod
    def _checked_token(provider: str, token: Mapping[str, Any], what: str) -> dict[str, Any]:
        """Reject a 200 answer that is an error document (GitHub) or has no access token."""
        error = token.get("error")
        if error or not token.get("access_token"):
            code = error if isinstance(error, str) else None
            detail = f"{what} ({code})" if code else f"{what}: no access token returned"
            raise OAuthProviderError(provider, detail, error_code=code)
        return dict(token)

    # ── Identity ──────────────────────────────────────────────────────────

    def identity(self, provider: str, userinfo: Mapping[str, Any]) -> OAuthIdentity:
        """Validate ``userinfo`` and return the identity it describes.

        Raises:
            OAuthProviderError: No stable id, no usable email, an unverified
                email or a ``required_claims`` mismatch.
        """
        config = self._config(provider)
        sub = userinfo.get(config.sub_claim)
        if sub is None or sub == "":
            raise OAuthProviderError(provider, f"Userinfo has no {config.sub_claim!r} claim")
        email = userinfo.get(config.email_claim)
        if not isinstance(email, str) or "@" not in email or len(email) > _EMAIL_MAX:
            raise OAuthProviderError(provider, "Email required")
        if userinfo.get("email_verified") in (False, "false"):
            raise OAuthProviderError(provider, "Email address is not verified")
        for claim, expected in config.required_claims:
            if userinfo.get(claim) != expected:
                raise OAuthProviderError(provider, f"Account is not allowed ({claim} mismatch)")
        return OAuthIdentity(provider, str(sub), email.strip(), userinfo)

    # ── Users and tokens ──────────────────────────────────────────────────

    async def provision_user(
        self, provider: str, userinfo: Mapping[str, Any], token: Mapping[str, Any]
    ) -> User:
        """Return the user of this identity, creating it on the first sign-in.

        A known ``(provider, sub)`` returns its user and stores the new tokens.
        An unknown identity creates a user with no usable password, unless its
        email already belongs to a user: accounts are never linked by email.

        Raises:
            AccountLinkRequiredError: The email belongs to an existing user.
            AccountDisabledError: The identity's user is not active.
            OAuthSignupDisabledError: Unknown identity and ``allow_signup=False``.
            OAuthProviderError: ``userinfo`` is unusable (see :meth:`identity`).
        """
        identity = self.identity(provider, userinfo)
        try:
            return await self._provision(identity, token)
        except IntegrityError:
            # A concurrent callback of the same identity created the rows first:
            # this one is now a returning sign-in (or an email conflict).
            return await self._provision(identity, token)

    async def _provision(self, identity: OAuthIdentity, token: Mapping[str, Any]) -> User:
        config = self._config(identity.provider)
        async with self._session() as session:
            row = await self._row_by_sub(session, identity)
            if row is not None:
                user = await session.get(User, row.user_id)
                if user is None or not user.is_active:
                    raise AccountDisabledError(identity.email)
                self._store_token(row, config, token)
                session.add(row)
                await session.commit()
                await session.refresh(user)
                return user
            taken = select(User.id).where(func.lower(User.email) == identity.email.lower())
            if (await session.execute(taken)).first() is not None:
                raise AccountLinkRequiredError(identity.provider, identity.email)
            if not config.allow_signup:
                raise OAuthSignupDisabledError(identity.provider)
            first_name, last_name = _names(identity.claims)
            user = User(
                username=await self._free_username(session, identity.email),
                email=identity.email,
                password_hash=make_unusable_password(),
                first_name=first_name,
                last_name=last_name,
            )
            self._apply_tenant(user, config, identity.claims)
            row = OAuthToken(provider=identity.provider, sub=identity.sub, user=user)
            self._store_token(row, config, token)
            session.add_all([user, row])
            await session.commit()
            await session.refresh(user)
            return user

    async def link_identity(
        self, provider: str, user_id: int, userinfo: Mapping[str, Any], token: Mapping[str, Any]
    ) -> None:
        """Link this identity to the signed-in user ``user_id`` and store its tokens.

        A provider the user linked before is re-pointed to the new identity.

        Raises:
            AccountLinkRequiredError: The identity is linked to another user.
            OAuthProviderError: ``userinfo`` is unusable (see :meth:`identity`).
        """
        identity = self.identity(provider, userinfo)
        config = self._config(provider)
        async with self._session() as session:
            row = await self._row_by_sub(session, identity)
            if row is not None and row.user_id != user_id:
                raise AccountLinkRequiredError(provider, identity.email)
            if row is None:
                row = await self._row_by_user(session, user_id, provider)
            if row is None:
                row = OAuthToken(user_id=user_id, provider=provider, sub=identity.sub)
            row.sub = identity.sub
            self._store_token(row, config, token)
            session.add(row)
            await session.commit()

    async def unlink_identity(self, provider: str, user_id: int) -> bool:
        """Delete the user's link to ``provider``; ``False`` when there was none.

        Raises:
            LastSignInMethodError: The user has no usable password and no other
                linked provider.
        """
        async with self._session() as session:
            stmt = select(OAuthToken).where(OAuthToken.user_id == user_id).options(_NO_USER)
            rows = list((await session.execute(stmt)).scalars())
            row = next((candidate for candidate in rows if candidate.provider == provider), None)
            if row is None:
                return False
            user = await session.get(User, user_id)
            if len(rows) == 1 and (user is None or user.oauth_only):
                raise LastSignInMethodError(provider)
            await session.delete(row)
            await session.commit()
            return True

    async def linked_providers(self, user_id: int) -> set[str]:
        """Return the names of the providers ``user_id`` has linked."""
        async with self._session() as session:
            stmt = select(OAuthToken.provider).where(OAuthToken.user_id == user_id)
            return set((await session.execute(stmt)).scalars())

    async def refresh_token(self, provider: str, user_id: int, *, leeway: float) -> float | None:
        """Make sure the user's access token outlives ``leeway`` seconds.

        Asks the provider for a new access token when the stored one expires within
        ``leeway`` seconds. Concurrent calls for one user and provider run one after
        another, so a rotating refresh token is used once.

        Returns:
            The expiry of the (possibly new) access token as epoch seconds, or
            ``None`` when there is nothing to refresh: no link, no expiry or no
            refresh token.

        Raises:
            OAuthProviderError: The refresh failed. ``transient`` tells a network
                or server failure from a refusal (a revoked refresh token).
        """
        config = self._config(provider)
        key = (user_id, provider)
        lock = self._refresh_locks.get(key)
        if lock is None:
            lock = self._refresh_locks[key] = asyncio.Lock()
        async with lock, self._session() as session:
            row = await self._row_by_user(session, user_id, provider)
            if row is None or row.expires_at is None:
                return None
            if row.expires_at - utc_now() > timedelta(seconds=leeway):
                return _epoch(row.expires_at)
            try:
                refresh_token = row.refresh_token
            except OAuthConfigError as exc:
                raise OAuthProviderError(provider, "Stored token cannot be decrypted") from exc
            if refresh_token is None:
                return None
            token = await self._request_refresh(provider, refresh_token)
            self._store_token(row, config, token)
            session.add(row)
            await session.commit()
            return token.get("expires_at")

    async def _request_refresh(self, provider: str, refresh_token: str) -> dict[str, Any]:
        from httpx_oauth.oauth2 import RefreshTokenError  # noqa: PLC0415

        try:
            token = await self._clients[provider].refresh_token(refresh_token)
        except RefreshTokenError as exc:
            raise self._request_error(provider, "Token refresh failed", exc) from exc
        return self._checked_token(provider, token, "Token refresh failed")

    # ── Helpers ───────────────────────────────────────────────────────────

    @staticmethod
    async def _row_by_sub(session: AsyncSessionLike, identity: OAuthIdentity) -> OAuthToken | None:
        stmt = (
            select(OAuthToken)
            .where(OAuthToken.provider == identity.provider, OAuthToken.sub == identity.sub)
            .options(_NO_USER)
        )
        return (await session.execute(stmt)).scalar_one_or_none()

    @staticmethod
    async def _row_by_user(
        session: AsyncSessionLike, user_id: int, provider: str
    ) -> OAuthToken | None:
        stmt = (
            select(OAuthToken)
            .where(OAuthToken.user_id == user_id, OAuthToken.provider == provider)
            .options(_NO_USER)
        )
        return (await session.execute(stmt)).scalar_one_or_none()

    @staticmethod
    def _store_token(
        row: OAuthToken, config: OAuthProviderConfig, token: Mapping[str, Any]
    ) -> None:
        """Copy a token response onto ``row`` (encrypting the tokens)."""
        row.access_token = str(token["access_token"])
        # Providers send a refresh token on the first consent only (Google) or on
        # every refresh (rotation); without a new one the stored one stays valid.
        if token.get("refresh_token"):
            row.refresh_token = str(token["refresh_token"])
        expires_at = token.get("expires_at")
        row.expires_at = (
            datetime.fromtimestamp(float(expires_at), tz=timezone.utc)
            if expires_at is not None
            else None
        )
        row.scopes = _split_scopes(token.get("scope"), config.scopes)
        row.updated_at = utc_now()

    @staticmethod
    async def _free_username(session: AsyncSessionLike, email: str) -> str:
        """Derive a unique username from the email's local part."""
        base = _USERNAME_UNSAFE.sub("", email.partition("@")[0])[: _USERNAME_MAX - 10] or "user"
        stmt = select(User.username).where(col(User.username).startswith(base, autoescape=True))
        taken = set((await session.execute(stmt)).scalars())
        candidate, suffix = base, 1
        while candidate in taken:
            suffix += 1
            candidate = f"{base}-{suffix}"
        return candidate

    def _apply_tenant(
        self, user: Any, config: OAuthProviderConfig, claims: Mapping[str, Any]
    ) -> None:
        """Set ``user.tenant_id`` from the provider's tenant claim, when one maps.

        The built-in ``User`` has no ``tenant_id`` column before multi-tenancy
        (v0.5.3); the resolved value is then only logged.
        """
        if config.tenant_id_claim is None:
            return
        value = claims.get(config.tenant_id_claim)
        resolver = self.tenant_resolver
        tenant_id = resolver(value) if resolver is not None and value is not None else None
        if tenant_id is None:
            logger.info(
                "OAuth provider %s: no tenant for claim %s=%r; the new user has no tenant.",
                config.name,
                config.tenant_id_claim,
                value,
            )
            return
        if not hasattr(user, "tenant_id"):
            logger.info(
                "OAuth provider %s: tenant %r resolved, but the user model has no tenant_id.",
                config.name,
                tenant_id,
            )
            return
        user.tenant_id = tenant_id

authorization_url(provider, redirect_uri, state, code_verifier) async

Return the provider URL the browser is sent to, with state and PKCE.

Source code in src/hyperadmin/auth/oauth/backend.py
221
222
223
224
225
226
227
228
229
230
231
232
async def authorization_url(
    self, provider: str, redirect_uri: str, state: str, code_verifier: str
) -> str:
    """Return the provider URL the browser is sent to, with ``state`` and PKCE."""
    config = self._config(provider)
    return await self._clients[provider].get_authorization_url(
        redirect_uri,
        state=state,
        code_challenge=pkce_challenge(code_verifier),
        code_challenge_method="S256",
        extras_params=dict(config.authorize_params) or None,
    )

bind(*, engine=None, session_factory=None)

Use engine / session_factory unless the backend already has its own.

Source code in src/hyperadmin/auth/oauth/backend.py
193
194
195
196
197
def bind(self, *, engine: Any = None, session_factory: SessionFactory | None = None) -> None:
    """Use ``engine`` / ``session_factory`` unless the backend already has its own."""
    if self.engine is None and self.session_factory is None:
        self.engine = engine
        self.session_factory = session_factory

exchange_code(provider, code, redirect_uri, code_verifier=None) async

Exchange an authorization code for tokens.

Returns:

Type Description
dict[str, Any]

The token response: access_token, and when the provider sends them

dict[str, Any]

refresh_token, expires_at (epoch seconds) and scope.

Raises:

Type Description
OAuthProviderError

The provider rejected the code or was unreachable.

Source code in src/hyperadmin/auth/oauth/backend.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
async def exchange_code(
    self, provider: str, code: str, redirect_uri: str, code_verifier: str | None = None
) -> dict[str, Any]:
    """Exchange an authorization ``code`` for tokens.

    Returns:
        The token response: ``access_token``, and when the provider sends them
        ``refresh_token``, ``expires_at`` (epoch seconds) and ``scope``.

    Raises:
        OAuthProviderError: The provider rejected the code or was unreachable.
    """
    self._config(provider)
    from httpx_oauth.oauth2 import GetAccessTokenError  # noqa: PLC0415

    try:
        token = await self._clients[provider].get_access_token(
            code, redirect_uri, code_verifier
        )
    except GetAccessTokenError as exc:
        raise self._request_error(provider, "Token exchange failed", exc) from exc
    return self._checked_token(provider, token, "Token exchange failed")

get_userinfo(provider, access_token) async

Return the provider's profile of the token's user.

When the profile has no email and the provider has an emails_url (GitHub), the primary verified address is looked up and added.

Raises:

Type Description
OAuthProviderError

The provider refused the token or was unreachable.

Source code in src/hyperadmin/auth/oauth/backend.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
async def get_userinfo(self, provider: str, access_token: str) -> dict[str, Any]:
    """Return the provider's profile of the token's user.

    When the profile has no email and the provider has an ``emails_url``
    (GitHub), the primary verified address is looked up and added.

    Raises:
        OAuthProviderError: The provider refused the token or was unreachable.
    """
    config = self._config(provider)
    claims = await self._get_json(provider, config.userinfo_url, access_token)
    if not isinstance(claims, dict):
        raise OAuthProviderError(provider, "Userinfo is not a JSON object")
    if not claims.get(config.email_claim) and config.emails_url:
        emails = await self._get_json(provider, config.emails_url, access_token)
        email = _primary_email(emails)
        if email:
            claims[config.email_claim] = email
    return claims

identity(provider, userinfo)

Validate userinfo and return the identity it describes.

Raises:

Type Description
OAuthProviderError

No stable id, no usable email, an unverified email or a required_claims mismatch.

Source code in src/hyperadmin/auth/oauth/backend.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def identity(self, provider: str, userinfo: Mapping[str, Any]) -> OAuthIdentity:
    """Validate ``userinfo`` and return the identity it describes.

    Raises:
        OAuthProviderError: No stable id, no usable email, an unverified
            email or a ``required_claims`` mismatch.
    """
    config = self._config(provider)
    sub = userinfo.get(config.sub_claim)
    if sub is None or sub == "":
        raise OAuthProviderError(provider, f"Userinfo has no {config.sub_claim!r} claim")
    email = userinfo.get(config.email_claim)
    if not isinstance(email, str) or "@" not in email or len(email) > _EMAIL_MAX:
        raise OAuthProviderError(provider, "Email required")
    if userinfo.get("email_verified") in (False, "false"):
        raise OAuthProviderError(provider, "Email address is not verified")
    for claim, expected in config.required_claims:
        if userinfo.get(claim) != expected:
            raise OAuthProviderError(provider, f"Account is not allowed ({claim} mismatch)")
    return OAuthIdentity(provider, str(sub), email.strip(), userinfo)

Link this identity to the signed-in user user_id and store its tokens.

A provider the user linked before is re-pointed to the new identity.

Raises:

Type Description
AccountLinkRequiredError

The identity is linked to another user.

OAuthProviderError

userinfo is unusable (see :meth:identity).

Source code in src/hyperadmin/auth/oauth/backend.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
async def link_identity(
    self, provider: str, user_id: int, userinfo: Mapping[str, Any], token: Mapping[str, Any]
) -> None:
    """Link this identity to the signed-in user ``user_id`` and store its tokens.

    A provider the user linked before is re-pointed to the new identity.

    Raises:
        AccountLinkRequiredError: The identity is linked to another user.
        OAuthProviderError: ``userinfo`` is unusable (see :meth:`identity`).
    """
    identity = self.identity(provider, userinfo)
    config = self._config(provider)
    async with self._session() as session:
        row = await self._row_by_sub(session, identity)
        if row is not None and row.user_id != user_id:
            raise AccountLinkRequiredError(provider, identity.email)
        if row is None:
            row = await self._row_by_user(session, user_id, provider)
        if row is None:
            row = OAuthToken(user_id=user_id, provider=provider, sub=identity.sub)
        row.sub = identity.sub
        self._store_token(row, config, token)
        session.add(row)
        await session.commit()

linked_providers(user_id) async

Return the names of the providers user_id has linked.

Source code in src/hyperadmin/auth/oauth/backend.py
452
453
454
455
456
async def linked_providers(self, user_id: int) -> set[str]:
    """Return the names of the providers ``user_id`` has linked."""
    async with self._session() as session:
        stmt = select(OAuthToken.provider).where(OAuthToken.user_id == user_id)
        return set((await session.execute(stmt)).scalars())

provider(name)

Return the provider configured as name, or None.

Source code in src/hyperadmin/auth/oauth/backend.py
199
200
201
def provider(self, name: str) -> OAuthProviderConfig | None:
    """Return the provider configured as ``name``, or ``None``."""
    return self.providers.get(name)

provision_user(provider, userinfo, token) async

Return the user of this identity, creating it on the first sign-in.

A known (provider, sub) returns its user and stores the new tokens. An unknown identity creates a user with no usable password, unless its email already belongs to a user: accounts are never linked by email.

Raises:

Type Description
AccountLinkRequiredError

The email belongs to an existing user.

AccountDisabledError

The identity's user is not active.

OAuthSignupDisabledError

Unknown identity and allow_signup=False.

OAuthProviderError

userinfo is unusable (see :meth:identity).

Source code in src/hyperadmin/auth/oauth/backend.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
async def provision_user(
    self, provider: str, userinfo: Mapping[str, Any], token: Mapping[str, Any]
) -> User:
    """Return the user of this identity, creating it on the first sign-in.

    A known ``(provider, sub)`` returns its user and stores the new tokens.
    An unknown identity creates a user with no usable password, unless its
    email already belongs to a user: accounts are never linked by email.

    Raises:
        AccountLinkRequiredError: The email belongs to an existing user.
        AccountDisabledError: The identity's user is not active.
        OAuthSignupDisabledError: Unknown identity and ``allow_signup=False``.
        OAuthProviderError: ``userinfo`` is unusable (see :meth:`identity`).
    """
    identity = self.identity(provider, userinfo)
    try:
        return await self._provision(identity, token)
    except IntegrityError:
        # A concurrent callback of the same identity created the rows first:
        # this one is now a returning sign-in (or an email conflict).
        return await self._provision(identity, token)

refresh_token(provider, user_id, *, leeway) async

Make sure the user's access token outlives leeway seconds.

Asks the provider for a new access token when the stored one expires within leeway seconds. Concurrent calls for one user and provider run one after another, so a rotating refresh token is used once.

Returns:

Type Description
float | None

The expiry of the (possibly new) access token as epoch seconds, or

float | None

None when there is nothing to refresh: no link, no expiry or no

float | None

refresh token.

Raises:

Type Description
OAuthProviderError

The refresh failed. transient tells a network or server failure from a refusal (a revoked refresh token).

Source code in src/hyperadmin/auth/oauth/backend.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
async def refresh_token(self, provider: str, user_id: int, *, leeway: float) -> float | None:
    """Make sure the user's access token outlives ``leeway`` seconds.

    Asks the provider for a new access token when the stored one expires within
    ``leeway`` seconds. Concurrent calls for one user and provider run one after
    another, so a rotating refresh token is used once.

    Returns:
        The expiry of the (possibly new) access token as epoch seconds, or
        ``None`` when there is nothing to refresh: no link, no expiry or no
        refresh token.

    Raises:
        OAuthProviderError: The refresh failed. ``transient`` tells a network
            or server failure from a refusal (a revoked refresh token).
    """
    config = self._config(provider)
    key = (user_id, provider)
    lock = self._refresh_locks.get(key)
    if lock is None:
        lock = self._refresh_locks[key] = asyncio.Lock()
    async with lock, self._session() as session:
        row = await self._row_by_user(session, user_id, provider)
        if row is None or row.expires_at is None:
            return None
        if row.expires_at - utc_now() > timedelta(seconds=leeway):
            return _epoch(row.expires_at)
        try:
            refresh_token = row.refresh_token
        except OAuthConfigError as exc:
            raise OAuthProviderError(provider, "Stored token cannot be decrypted") from exc
        if refresh_token is None:
            return None
        token = await self._request_refresh(provider, refresh_token)
        self._store_token(row, config, token)
        session.add(row)
        await session.commit()
        return token.get("expires_at")

Delete the user's link to provider; False when there was none.

Raises:

Type Description
LastSignInMethodError

The user has no usable password and no other linked provider.

Source code in src/hyperadmin/auth/oauth/backend.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
async def unlink_identity(self, provider: str, user_id: int) -> bool:
    """Delete the user's link to ``provider``; ``False`` when there was none.

    Raises:
        LastSignInMethodError: The user has no usable password and no other
            linked provider.
    """
    async with self._session() as session:
        stmt = select(OAuthToken).where(OAuthToken.user_id == user_id).options(_NO_USER)
        rows = list((await session.execute(stmt)).scalars())
        row = next((candidate for candidate in rows if candidate.provider == provider), None)
        if row is None:
            return False
        user = await session.get(User, user_id)
        if len(rows) == 1 and (user is None or user.oauth_only):
            raise LastSignInMethodError(provider)
        await session.delete(row)
        await session.commit()
        return True

hyperadmin.auth.oauth.OAuthProviderConfig dataclass

One OAuth2/OIDC identity provider.

Attributes:

Name Type Description
name str

Lower-case name used in URLs and stored on OAuthToken.provider.

client_id str

OAuth client id issued by the provider.

client_secret str

OAuth client secret (left out of repr).

scopes tuple[str, ...]

Scopes requested at authorization.

authorize_url str

Authorization endpoint.

token_url str

Token endpoint (code exchange and refresh).

userinfo_url str

Endpoint returning the signed-in user's profile as JSON.

sub_claim str

Userinfo key of the stable user id (OIDC sub, GitHub id).

email_claim str

Userinfo key of the email address.

tenant_id_claim str | None

Userinfo key (Google hd) handed to the backend's tenant_resolver when a user is created; None skips it.

button_label str | None

Text after "Sign in with" on the login page; defaults to the capitalised name.

button_icon str | None

URL of an image shown on the button, used as is.

redirect_uri str | None

Callback URL registered at the provider. None builds it from the request ({admin}/oauth/callback/{name}); set it when the admin sits behind a proxy that hides the public host.

emails_url str | None

Endpoint listing the user's addresses, asked when userinfo carries no email (GitHub accounts with a private address).

authorize_params tuple[tuple[str, str], ...]

Extra query parameters of the authorization request.

required_claims tuple[tuple[str, str], ...]

Userinfo (key, value) pairs that must match, or the sign-in is refused (Google hd for a Workspace domain).

allow_signup bool

False refuses identities that are not linked to a user yet, so only existing users who linked the provider can sign in.

Raises:

Type Description
OAuthConfigError

A required value is empty or malformed (a ValueError).

Source code in src/hyperadmin/auth/oauth/providers.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@dataclass(frozen=True, slots=True)
class OAuthProviderConfig:
    """One OAuth2/OIDC identity provider.

    Attributes:
        name: Lower-case name used in URLs and stored on ``OAuthToken.provider``.
        client_id: OAuth client id issued by the provider.
        client_secret: OAuth client secret (left out of ``repr``).
        scopes: Scopes requested at authorization.
        authorize_url: Authorization endpoint.
        token_url: Token endpoint (code exchange and refresh).
        userinfo_url: Endpoint returning the signed-in user's profile as JSON.
        sub_claim: Userinfo key of the stable user id (OIDC ``sub``, GitHub ``id``).
        email_claim: Userinfo key of the email address.
        tenant_id_claim: Userinfo key (Google ``hd``) handed to the backend's
            ``tenant_resolver`` when a user is created; ``None`` skips it.
        button_label: Text after "Sign in with" on the login page; defaults to the
            capitalised ``name``.
        button_icon: URL of an image shown on the button, used as is.
        redirect_uri: Callback URL registered at the provider. ``None`` builds it
            from the request (``{admin}/oauth/callback/{name}``); set it when the
            admin sits behind a proxy that hides the public host.
        emails_url: Endpoint listing the user's addresses, asked when userinfo
            carries no email (GitHub accounts with a private address).
        authorize_params: Extra query parameters of the authorization request.
        required_claims: Userinfo ``(key, value)`` pairs that must match, or the
            sign-in is refused (Google ``hd`` for a Workspace domain).
        allow_signup: ``False`` refuses identities that are not linked to a user
            yet, so only existing users who linked the provider can sign in.

    Raises:
        OAuthConfigError: A required value is empty or malformed (a ``ValueError``).
    """

    name: str
    client_id: str
    client_secret: str = field(repr=False)
    scopes: tuple[str, ...]
    authorize_url: str
    token_url: str
    userinfo_url: str
    sub_claim: str = "sub"
    email_claim: str = "email"
    tenant_id_claim: str | None = None
    button_label: str | None = None
    button_icon: str | None = None
    redirect_uri: str | None = None
    emails_url: str | None = None
    authorize_params: tuple[tuple[str, str], ...] = ()
    required_claims: tuple[tuple[str, str], ...] = ()
    allow_signup: bool = True

    def __post_init__(self) -> None:
        if not _NAME.fullmatch(self.name or ""):
            msg = (
                f"OAuth provider name {self.name!r} is invalid: use 1-32 lower-case "
                "letters, digits, '_' or '-'."
            )
            raise OAuthConfigError(msg)
        for attribute in ("client_id", "client_secret"):
            if not getattr(self, attribute):
                msg = f"OAuth provider {self.name!r}: {attribute} is required."
                raise OAuthConfigError(msg)
        for attribute in ("authorize_url", "token_url", "userinfo_url"):
            self._check_url(attribute, optional=False)
        for attribute in ("emails_url", "redirect_uri"):
            self._check_url(attribute, optional=True)
        # A list is a natural way to write scopes; keep the frozen value hashable.
        object.__setattr__(self, "scopes", tuple(self.scopes))

    def _check_url(self, attribute: str, *, optional: bool) -> None:
        value = getattr(self, attribute)
        if value is None and optional:
            return
        if not value or not _URL.fullmatch(value):
            msg = f"OAuth provider {self.name!r}: {attribute} must be an http(s) URL."
            raise OAuthConfigError(msg)

    @property
    def label(self) -> str:
        """The provider's display name on the login button (``"Google"``)."""
        return self.button_label or self.name.replace("_", " ").replace("-", " ").title()

label property

The provider's display name on the login button ("Google").

hyperadmin.auth.oauth.github_provider(client_id, client_secret, *, scopes=GITHUB_SCOPES, redirect_uri=None, allow_signup=True)

Build the GitHub provider (OAuth2 with GitHub's own userinfo API).

GitHub is not OIDC: the stable user id is the numeric id of /user, and an account with a private email is resolved through /user/emails.

Parameters:

Name Type Description Default
client_id str

Client id of the GitHub OAuth app.

required
client_secret str

Its client secret.

required
scopes tuple[str, ...]

Scopes to request; user:email is needed for private addresses.

GITHUB_SCOPES
redirect_uri str | None

See :class:OAuthProviderConfig.

None
allow_signup bool

See :class:OAuthProviderConfig.

True
Source code in src/hyperadmin/auth/oauth/providers.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def github_provider(
    client_id: str,
    client_secret: str,
    *,
    scopes: tuple[str, ...] = GITHUB_SCOPES,
    redirect_uri: str | None = None,
    allow_signup: bool = True,
) -> OAuthProviderConfig:
    """Build the GitHub provider (OAuth2 with GitHub's own userinfo API).

    GitHub is not OIDC: the stable user id is the numeric ``id`` of ``/user``, and
    an account with a private email is resolved through ``/user/emails``.

    Args:
        client_id: Client id of the GitHub OAuth app.
        client_secret: Its client secret.
        scopes: Scopes to request; ``user:email`` is needed for private addresses.
        redirect_uri: See :class:`OAuthProviderConfig`.
        allow_signup: See :class:`OAuthProviderConfig`.
    """
    return OAuthProviderConfig(
        name="github",
        client_id=client_id,
        client_secret=client_secret,
        scopes=scopes,
        authorize_url=GITHUB_AUTHORIZE_URL,
        token_url=GITHUB_TOKEN_URL,
        userinfo_url=GITHUB_USERINFO_URL,
        sub_claim="id",
        button_label="GitHub",
        redirect_uri=redirect_uri,
        emails_url=GITHUB_EMAILS_URL,
        allow_signup=allow_signup,
    )

hyperadmin.auth.oauth.google_provider(client_id, client_secret, *, hosted_domain=None, tenant_id_claim=None, scopes=GOOGLE_SCOPES, redirect_uri=None, allow_signup=True)

Build the Google (OIDC) provider.

Parameters:

Name Type Description Default
client_id str

OAuth client id from the Google Cloud console.

required
client_secret str

Its client secret.

required
hosted_domain str | None

A Google Workspace domain ("acme.com"). Google is asked to show only its accounts, and a sign-in whose hd claim differs is refused.

None
tenant_id_claim str | None

See :class:OAuthProviderConfig (usually "hd").

None
scopes tuple[str, ...]

Scopes to request.

GOOGLE_SCOPES
redirect_uri str | None

See :class:OAuthProviderConfig.

None
allow_signup bool

See :class:OAuthProviderConfig.

True
Source code in src/hyperadmin/auth/oauth/providers.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def google_provider(
    client_id: str,
    client_secret: str,
    *,
    hosted_domain: str | None = None,
    tenant_id_claim: str | None = None,
    scopes: tuple[str, ...] = GOOGLE_SCOPES,
    redirect_uri: str | None = None,
    allow_signup: bool = True,
) -> OAuthProviderConfig:
    """Build the Google (OIDC) provider.

    Args:
        client_id: OAuth client id from the Google Cloud console.
        client_secret: Its client secret.
        hosted_domain: A Google Workspace domain (``"acme.com"``). Google is asked
            to show only its accounts, and a sign-in whose ``hd`` claim differs is
            refused.
        tenant_id_claim: See :class:`OAuthProviderConfig` (usually ``"hd"``).
        scopes: Scopes to request.
        redirect_uri: See :class:`OAuthProviderConfig`.
        allow_signup: See :class:`OAuthProviderConfig`.
    """
    # access_type=offline makes Google issue a refresh token on the first consent.
    authorize_params: tuple[tuple[str, str], ...] = (("access_type", "offline"),)
    required_claims: tuple[tuple[str, str], ...] = ()
    if hosted_domain:
        authorize_params = (*authorize_params, ("hd", hosted_domain))
        required_claims = (("hd", hosted_domain),)
    return OAuthProviderConfig(
        name="google",
        client_id=client_id,
        client_secret=client_secret,
        scopes=scopes,
        authorize_url=GOOGLE_AUTHORIZE_URL,
        token_url=GOOGLE_TOKEN_URL,
        userinfo_url=GOOGLE_USERINFO_URL,
        tenant_id_claim=tenant_id_claim,
        button_label="Google",
        redirect_uri=redirect_uri,
        authorize_params=authorize_params,
        required_claims=required_claims,
        allow_signup=allow_signup,
    )

hyperadmin.auth.oauth.OAuthProviderError

Bases: HyperAdminAuthError

An identity provider refused a request, answered garbage or was unreachable.

Attributes:

Name Type Description
provider

Name of the provider ("google").

detail

Human-readable description; never contains a token or a secret.

error_code

The provider's OAuth error code ("invalid_grant") when it sent one.

transient

True for a network failure or a 5xx answer, where a retry may work.

Source code in src/hyperadmin/auth/exceptions.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class OAuthProviderError(HyperAdminAuthError):
    """An identity provider refused a request, answered garbage or was unreachable.

    Attributes:
        provider: Name of the provider (``"google"``).
        detail: Human-readable description; never contains a token or a secret.
        error_code: The provider's OAuth ``error`` code (``"invalid_grant"``) when it sent one.
        transient: ``True`` for a network failure or a 5xx answer, where a retry may work.
    """

    def __init__(
        self,
        provider: str,
        detail: str,
        *,
        error_code: str | None = None,
        transient: bool = False,
    ) -> None:
        self.provider = provider
        self.detail = detail
        self.error_code = error_code
        self.transient = transient
        super().__init__(f"OAuth provider {provider!r}: {detail}")

hyperadmin.auth.oauth.AccountLinkRequiredError

Bases: HyperAdminAuthError

The identity cannot be used as is: an account conflict needs an explicit link.

HyperAdmin never links an identity to an existing account by email alone.

Attributes:

Name Type Description
provider

Name of the provider the identity comes from.

email

The email address the provider reported.

Source code in src/hyperadmin/auth/exceptions.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class AccountLinkRequiredError(HyperAdminAuthError):
    """The identity cannot be used as is: an account conflict needs an explicit link.

    HyperAdmin never links an identity to an existing account by email alone.

    Attributes:
        provider: Name of the provider the identity comes from.
        email: The email address the provider reported.
    """

    def __init__(self, provider: str, email: str) -> None:
        self.provider = provider
        self.email = email
        super().__init__(
            f"An account already exists for {email!r}; sign in with your password and "
            f"link {provider!r} from settings."
        )