| 1 |
""" |
| 2 |
Copyright 2026-2026 by J. Christopher Wagner (jwag). All rights reserved. |
| 3 |
:license: MIT, see LICENSE for more details. |
| 4 |
|
| 5 |
|
| 6 |
Complete models for all features when using SqlAlchemy. |
| 7 |
These are pure sqlalchemy declarative models - so should work with Flask-SQLAlchemy-Lite |
| 8 |
as well as just sqlalchemy (such as using a scoped session). |
| 9 |
|
| 10 |
You can change the table names by passing them in to the set_db_info() method. |
| 11 |
|
| 12 |
BE AWARE: Once any version of this is shipped no changes can be made - instead |
| 13 |
a new version needs to be created. |
| 14 |
|
| 15 |
This is Version 2: |
| 16 |
- Add support for refresh tokens |
| 17 |
""" |
| 18 |
|
| 19 |
# mypy: disable-error-code="assignment" |
| 20 |
# pyright: reportAssignmentType = false, reportIncompatibleVariableOverride=false |
| 21 |
|
| 22 |
from __future__ import annotations |
| 23 |
|
| 24 |
import datetime |
| 25 |
|
| 26 |
from sqlalchemy import ( |
| 27 |
String, |
| 28 |
ForeignKey, |
| 29 |
func, |
| 30 |
) |
| 31 |
from sqlalchemy.ext.declarative import declared_attr |
| 32 |
from sqlalchemy.orm import Mapped, mapped_column, relationship |
| 33 |
|
| 34 |
from flask_security import RefreshTrackerMixin |
| 35 |
|
| 36 |
from .sqla import FsModels |
| 37 |
from .sqla import FsUserMixin as FsUserMixinV1 |
| 38 |
from .sqla import FsRoleMixin as FsRoleMixinV1 |
| 39 |
from .sqla import FsWebAuthnMixin as FsWebauthnMixinV1 |
| 40 |
|
| 41 |
FsModels.fs_model_version = 2 |
| 42 |
|
| 43 |
|
| 44 |
class FsRoleMixin(FsRoleMixinV1): |
| 45 |
pass |
| 46 |
|
| 47 |
|
| 48 |
class FsUserMixin(FsUserMixinV1): |
| 49 |
"""User information""" |
| 50 |
|
| 51 |
# List of Refresh Token trackers |
| 52 |
@declared_attr |
| 53 |
def refresh_trackers(cls): |
| 54 |
return relationship("FsRefreshTracker", cascade="all, delete") |
| 55 |
|
| 56 |
|
| 57 |
class FsWebAuthnMixin(FsWebauthnMixinV1): |
| 58 |
pass |
| 59 |
|
| 60 |
|
| 61 |
class FsRefreshTrackerMixin(RefreshTrackerMixin): |
| 62 |
"""Refresh Token Tracker""" |
| 63 |
|
| 64 |
id: Mapped[int] = mapped_column(primary_key=True) |
| 65 |
# family and gen track refresh rotation |
| 66 |
refresh_family: Mapped[str] = mapped_column(String(64), unique=True) |
| 67 |
gen: Mapped[int] = mapped_column() |
| 68 |
expires_at: Mapped[datetime.datetime] = mapped_column() |
| 69 |
revoked_at: Mapped[datetime.datetime | None] = mapped_column() |
| 70 |
last_used_at: Mapped[datetime.datetime] = mapped_column() |
| 71 |
create_datetime: Mapped[datetime.datetime] = mapped_column( |
| 72 |
server_default=func.now() |
| 73 |
) |
| 74 |
# name TODO - how to use/initialize it |
| 75 |
name: Mapped[str] = mapped_column(String(64)) |
| 76 |
|
| 77 |
@declared_attr |
| 78 |
def user_id(cls) -> Mapped[int]: |
| 79 |
return mapped_column( |
| 80 |
ForeignKey(f"{FsModels.user_table_name}.id", ondelete="CASCADE") |
| 81 |
) |