|
1 | | -"""The [AuthUserMixin][crudauth.models.mixin.AuthUserMixin] - inherit it and get every column crudauth needs. |
2 | | -
|
3 | | -Your own columns coexist freely. If you have an existing table with different |
4 | | -column names, don't rename your schema - map the contract via |
5 | | -``column_map=`` on [CRUDAuth][crudauth.crud_auth.CRUDAuth] instead. |
| 1 | +"""The auth user-model columns, emitted by [make_auth_identity] |
| 2 | +[crudauth.models.mixin.make_auth_identity]. |
| 3 | +
|
| 4 | +Inherit [AuthUserMixin][crudauth.models.mixin.AuthUserMixin] (the default output) |
| 5 | +and get every column crudauth needs. Your own columns coexist freely. For a |
| 6 | +different account shape (username-only login, phone recovery, no recovery at all) |
| 7 | +call the factory yourself. If you have an existing table with different column |
| 8 | +names, don't rename your schema - map the contract via ``column_map=`` on |
| 9 | +[CRUDAuth][crudauth.crud_auth.CRUDAuth] instead. |
6 | 10 | """ |
7 | 11 |
|
8 | 12 | from __future__ import annotations |
9 | 13 |
|
10 | 14 | from datetime import datetime, timezone |
| 15 | +from typing import Any, Iterable |
11 | 16 |
|
12 | 17 | from sqlalchemy import DateTime, String |
13 | 18 | from sqlalchemy.orm import Mapped, mapped_column |
14 | 19 |
|
15 | | -__all__ = ["AuthUserMixin"] |
| 20 | +__all__ = ["AuthUserMixin", "make_auth_identity"] |
16 | 21 |
|
17 | 22 |
|
18 | 23 | def _utcnow() -> datetime: |
19 | 24 | return datetime.now(timezone.utc) |
20 | 25 |
|
21 | 26 |
|
22 | | -class AuthUserMixin: |
23 | | - """Declarative mixin supplying the full set of columns crudauth relies on. |
24 | | -
|
25 | | - Note: |
26 | | - ``token_version`` is a monotonic credential epoch: bearer tokens embed it |
27 | | - as the ``ver`` claim and a password reset bumps it, so a reset rejects |
28 | | - every outstanding bearer token. See |
29 | | - [BearerTransport][crudauth.transports.bearer.transport.BearerTransport]. |
| 27 | +def make_auth_identity( |
| 28 | + *, |
| 29 | + identifiers: Iterable[str] = ("email", "username"), |
| 30 | + recovery: str | None = "email", |
| 31 | + oauth: bool = True, |
| 32 | +) -> type[Any]: |
| 33 | + """Build a declarative mixin carrying crudauth's user columns for one account shape. |
| 34 | +
|
| 35 | + The model is the source of truth for shape: this emits the columns, and |
| 36 | + [CRUDAuth][crudauth.crud_auth.CRUDAuth] reads them back at construction, so the |
| 37 | + two can't disagree. ``username``, ``hashed_password``, the status flags, |
| 38 | + ``token_version``, and the timestamps are always emitted; ``email`` and the |
| 39 | + oauth-linkage columns are conditional. |
| 40 | +
|
| 41 | + Args: |
| 42 | + identifiers: Logical fields a user may log in with. Each becomes a |
| 43 | + ``NOT NULL`` unique column. ``email`` here makes the email column |
| 44 | + required. |
| 45 | + recovery: The single field recovery (verify/reset/change) is delivered |
| 46 | + against, or ``None`` for an account shape with no recovery. ``"email"`` |
| 47 | + (and not an identifier) makes the email column nullable but unique. |
| 48 | + oauth: Emit the oauth-linkage columns (``oauth_provider`` / ``google_id`` / |
| 49 | + ``github_id`` / timestamps). Required for OAuth login. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + A declarative mixin class. Inherit it on your model alongside ``Base``. |
30 | 53 |
|
31 | 54 | Example: |
32 | 55 | ```python |
| 56 | + # the default - email + username login, email recovery (today's shape) |
33 | 57 | class User(Base, AuthUserMixin): |
34 | 58 | __tablename__ = "users" |
35 | | - full_name: Mapped[str | None] = mapped_column(default=None) |
| 59 | +
|
| 60 | + # username-only login, phone recovery |
| 61 | + Identity = make_auth_identity(identifiers=["username"], recovery="phone") |
| 62 | + class User(Base, Identity): |
| 63 | + __tablename__ = "users" |
| 64 | + phone: Mapped[str | None] = mapped_column(unique=True, default=None) |
36 | 65 | ``` |
37 | 66 | """ |
38 | | - |
39 | | - # --- core identity ------------------------------------------------------- |
40 | | - id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) |
41 | | - email: Mapped[str] = mapped_column(String(320), unique=True, index=True) |
42 | | - username: Mapped[str] = mapped_column(String(64), unique=True, index=True) |
43 | | - hashed_password: Mapped[str] = mapped_column(String(255)) |
44 | | - |
45 | | - # --- status flags -------------------------------------------------------- |
46 | | - is_active: Mapped[bool] = mapped_column(default=True) |
47 | | - is_superuser: Mapped[bool] = mapped_column(default=False) |
48 | | - email_verified: Mapped[bool] = mapped_column(default=False) |
49 | | - |
50 | | - token_version: Mapped[int] = mapped_column(default=0) |
51 | | - |
52 | | - # --- oauth linkage ------------------------------------------------------- |
53 | | - oauth_provider: Mapped[str | None] = mapped_column(String(32), default=None) |
54 | | - google_id: Mapped[str | None] = mapped_column(String(64), unique=True, index=True, default=None) |
55 | | - github_id: Mapped[str | None] = mapped_column(String(64), unique=True, index=True, default=None) |
56 | | - oauth_created_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), default=None) |
57 | | - oauth_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), default=None) |
58 | | - |
59 | | - # --- timestamps ---------------------------------------------------------- |
60 | | - created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow) |
61 | | - updated_at: Mapped[datetime | None] = mapped_column( |
62 | | - DateTime(timezone=True), default=None, onupdate=_utcnow |
| 67 | + ns: dict[str, Any] = {} |
| 68 | + ann: dict[str, Any] = {} |
| 69 | + |
| 70 | + def add(name: str, annotation: Any, column: Any) -> None: |
| 71 | + ann[name] = annotation |
| 72 | + ns[name] = column |
| 73 | + |
| 74 | + identifier_set = set(identifiers) |
| 75 | + email_is_identifier = "email" in identifier_set |
| 76 | + email_is_recovery = recovery == "email" |
| 77 | + |
| 78 | + add("id", Mapped[int], mapped_column(primary_key=True, autoincrement=True)) |
| 79 | + if email_is_identifier: |
| 80 | + add("email", Mapped[str], mapped_column(String(320), unique=True, index=True)) |
| 81 | + elif email_is_recovery: |
| 82 | + add( |
| 83 | + "email", |
| 84 | + Mapped[str | None], |
| 85 | + mapped_column(String(320), unique=True, index=True, default=None), |
| 86 | + ) |
| 87 | + add("username", Mapped[str], mapped_column(String(64), unique=True, index=True)) |
| 88 | + add("hashed_password", Mapped[str], mapped_column(String(255))) |
| 89 | + |
| 90 | + add("is_active", Mapped[bool], mapped_column(default=True)) |
| 91 | + add("is_superuser", Mapped[bool], mapped_column(default=False)) |
| 92 | + add("email_verified", Mapped[bool], mapped_column(default=False)) |
| 93 | + add("token_version", Mapped[int], mapped_column(default=0)) |
| 94 | + |
| 95 | + if oauth: |
| 96 | + add("oauth_provider", Mapped[str | None], mapped_column(String(32), default=None)) |
| 97 | + add( |
| 98 | + "google_id", |
| 99 | + Mapped[str | None], |
| 100 | + mapped_column(String(64), unique=True, index=True, default=None), |
| 101 | + ) |
| 102 | + add( |
| 103 | + "github_id", |
| 104 | + Mapped[str | None], |
| 105 | + mapped_column(String(64), unique=True, index=True, default=None), |
| 106 | + ) |
| 107 | + add( |
| 108 | + "oauth_created_at", |
| 109 | + Mapped[datetime | None], |
| 110 | + mapped_column(DateTime(timezone=True), default=None), |
| 111 | + ) |
| 112 | + add( |
| 113 | + "oauth_updated_at", |
| 114 | + Mapped[datetime | None], |
| 115 | + mapped_column(DateTime(timezone=True), default=None), |
| 116 | + ) |
| 117 | + |
| 118 | + add("created_at", Mapped[datetime], mapped_column(DateTime(timezone=True), default=_utcnow)) |
| 119 | + add( |
| 120 | + "updated_at", |
| 121 | + Mapped[datetime | None], |
| 122 | + mapped_column(DateTime(timezone=True), default=None, onupdate=_utcnow), |
63 | 123 | ) |
| 124 | + |
| 125 | + ns["__annotations__"] = ann |
| 126 | + return type("AuthUserMixin", (), ns) |
| 127 | + |
| 128 | + |
| 129 | +AuthUserMixin = make_auth_identity() |
| 130 | +"""Default identity columns: email + username login, email recovery, oauth enabled. |
| 131 | +
|
| 132 | +Inherit this for the standard account shape (it is exactly |
| 133 | +``make_auth_identity()``): |
| 134 | +
|
| 135 | +```python |
| 136 | +class User(Base, AuthUserMixin): |
| 137 | + __tablename__ = "users" |
| 138 | + full_name: Mapped[str | None] = mapped_column(default=None) |
| 139 | +``` |
| 140 | +
|
| 141 | +``token_version`` is a monotonic credential epoch: bearer tokens embed it as the |
| 142 | +``ver`` claim and a password reset bumps it, so a reset rejects every outstanding |
| 143 | +bearer token. |
| 144 | +""" |
0 commit comments