| 1 |
""" |
| 2 |
Copyright 2024-2024 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 |
|
| 16 |
# mypy: disable-error-code="assignment" |
| 17 |
# pyright: reportAssignmentType = false, reportIncompatibleVariableOverride=false |
| 18 |
|
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
import datetime |
| 22 |
|
| 23 |
from sqlalchemy import ( |
| 24 |
Column, |
| 25 |
LargeBinary, |
| 26 |
String, |
| 27 |
Table, |
| 28 |
Text, |
| 29 |
ForeignKey, |
| 30 |
) |
| 31 |
from sqlalchemy.ext.declarative import declared_attr |
| 32 |
from sqlalchemy.ext.mutable import MutableList |
| 33 |
from sqlalchemy.sql import func |
| 34 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship |
| 35 |
|
| 36 |
from flask_security import AsaList, RoleMixin, UserMixin, WebAuthnMixin, naive_utcnow |
| 37 |
|
| 38 |
|
| 39 |
class FsModels: |
| 40 |
""" |
| 41 |
Helper class for model mixins when utilizing the pre-packaged models |
| 42 |
for Flask-SQLAlchemy-Lite. |
| 43 |
""" |
| 44 |
|
| 45 |
roles_users = None |
| 46 |
fs_model_version = 1 |
| 47 |
base_model: DeclarativeBase |
| 48 |
user_table_name = "user" |
| 49 |
role_table_name = "role" |
| 50 |
webauthn_table_name = "webauthn" |
| 51 |
|
| 52 |
@classmethod |
| 53 |
def set_db_info( |
| 54 |
cls, |
| 55 |
*, |
| 56 |
base_model, |
| 57 |
user_table_name="user", |
| 58 |
role_table_name="role", |
| 59 |
webauthn_table_name="webauthn", |
| 60 |
): |
| 61 |
"""Initialize Model. |
| 62 |
This MUST be called PRIOR to declaring your User/Role/WebAuthn model in order |
| 63 |
for table name altering to work. |
| 64 |
|
| 65 |
.. note:: |
| 66 |
This should only be used if you are utilizing the sqla data |
| 67 |
models. With your own models you would need similar but slightly |
| 68 |
different code. |
| 69 |
""" |
| 70 |
cls.base_model = base_model |
| 71 |
cls.user_table_name = user_table_name |
| 72 |
cls.role_table_name = role_table_name |
| 73 |
cls.webauthn_table_name = webauthn_table_name |
| 74 |
cls.roles_users = Table( |
| 75 |
"roles_users", |
| 76 |
cls.base_model.metadata, |
| 77 |
Column( |
| 78 |
"user_id", ForeignKey(f"{cls.user_table_name}.id"), primary_key=True |
| 79 |
), |
| 80 |
Column( |
| 81 |
"role_id", ForeignKey(f"{cls.role_table_name}.id"), primary_key=True |
| 82 |
), |
| 83 |
) |
| 84 |
|
| 85 |
|
| 86 |
class FsRoleMixin(RoleMixin): |
| 87 |
id: Mapped[int] = mapped_column(primary_key=True) |
| 88 |
name: Mapped[str] = mapped_column(String(80), unique=True) |
| 89 |
description: Mapped[str | None] = mapped_column(String(255)) |
| 90 |
# A comma separated list of strings |
| 91 |
permissions: Mapped[list[str] | None] = mapped_column( # type: ignore[assignment] |
| 92 |
MutableList.as_mutable(AsaList()), |
| 93 |
) |
| 94 |
update_datetime: Mapped[datetime.datetime] = mapped_column( |
| 95 |
server_default=func.now(), |
| 96 |
onupdate=naive_utcnow, |
| 97 |
) |
| 98 |
|
| 99 |
@declared_attr |
| 100 |
def users(cls): |
| 101 |
return relationship( |
| 102 |
"User", |
| 103 |
secondary="roles_users", |
| 104 |
back_populates="roles", |
| 105 |
) |
| 106 |
|
| 107 |
|
| 108 |
class FsUserMixin(UserMixin): |
| 109 |
"""User information""" |
| 110 |
|
| 111 |
# flask_security basic fields |
| 112 |
id: Mapped[int] = mapped_column(primary_key=True) |
| 113 |
email: Mapped[str] = mapped_column(String(255), unique=True) |
| 114 |
# Make username unique but not required. |
| 115 |
username: Mapped[str | None] = mapped_column(String(255), unique=True) |
| 116 |
# Change password to nullable so we can tell after registration whether |
| 117 |
# a user has a password or not. |
| 118 |
password: Mapped[str | None] = mapped_column(String(255)) |
| 119 |
active: Mapped[bool] = mapped_column() |
| 120 |
|
| 121 |
# Flask-Security user identifier |
| 122 |
fs_uniquifier: Mapped[str] = mapped_column(String(64), unique=True) |
| 123 |
|
| 124 |
# confirmable |
| 125 |
confirmed_at: Mapped[datetime.datetime | None] = mapped_column() |
| 126 |
|
| 127 |
# trackable |
| 128 |
last_login_at: Mapped[datetime.datetime | None] = mapped_column() |
| 129 |
current_login_at: Mapped[datetime.datetime | None] = mapped_column() |
| 130 |
last_login_ip: Mapped[str | None] = mapped_column(String(64)) |
| 131 |
current_login_ip: Mapped[str | None] = mapped_column(String(64)) |
| 132 |
login_count: Mapped[int | None] = mapped_column() |
| 133 |
|
| 134 |
# 2FA |
| 135 |
tf_primary_method: Mapped[str | None] = mapped_column(String(64)) |
| 136 |
tf_totp_secret: Mapped[str | None] = mapped_column(String(255)) |
| 137 |
tf_phone_number: Mapped[str | None] = mapped_column(String(128)) |
| 138 |
|
| 139 |
# unified sign in |
| 140 |
us_totp_secrets: Mapped[str | None] = mapped_column(Text) |
| 141 |
# since phone can be used to authenticate - must be unique. |
| 142 |
us_phone_number: Mapped[str | None] = mapped_column(String(128), unique=True) |
| 143 |
|
| 144 |
try: |
| 145 |
import webauthn as webauthn_pkg |
| 146 |
|
| 147 |
# List of WebAuthn registrations |
| 148 |
@declared_attr |
| 149 |
def webauthn(cls): |
| 150 |
return relationship( |
| 151 |
"WebAuthn", back_populates="user", cascade="all, delete" |
| 152 |
) |
| 153 |
|
| 154 |
except ImportError: # pragma: no cover |
| 155 |
pass |
| 156 |
|
| 157 |
# The user handle as required during registration. |
| 158 |
# Note max length 64 as specified in spec. |
| 159 |
fs_webauthn_user_handle: Mapped[str | None] = mapped_column(String(64), unique=True) |
| 160 |
|
| 161 |
# MFA - one time recovery codes - comma separated. |
| 162 |
mf_recovery_codes: Mapped[list[str] | None] = mapped_column( |
| 163 |
MutableList.as_mutable(AsaList()) |
| 164 |
) |
| 165 |
|
| 166 |
@declared_attr |
| 167 |
def roles(cls): |
| 168 |
# The first arg is a class name, the backref is a column name |
| 169 |
return relationship( |
| 170 |
"Role", |
| 171 |
secondary="roles_users", |
| 172 |
back_populates="users", |
| 173 |
) |
| 174 |
|
| 175 |
create_datetime: Mapped[datetime.datetime] = mapped_column( |
| 176 |
server_default=func.now() |
| 177 |
) |
| 178 |
update_datetime: Mapped[datetime.datetime] = mapped_column( |
| 179 |
server_default=func.now(), |
| 180 |
onupdate=naive_utcnow, |
| 181 |
) |
| 182 |
|
| 183 |
|
| 184 |
class FsWebAuthnMixin(WebAuthnMixin): |
| 185 |
"""WebAuthn""" |
| 186 |
|
| 187 |
id: Mapped[int] = mapped_column(primary_key=True) |
| 188 |
credential_id: Mapped[bytes] = mapped_column( |
| 189 |
LargeBinary(1024), index=True, unique=True |
| 190 |
) |
| 191 |
public_key: Mapped[bytes] = mapped_column(LargeBinary) |
| 192 |
sign_count: Mapped[int | None] = mapped_column(default=0) |
| 193 |
transports: Mapped[list[str] | None] = mapped_column( |
| 194 |
MutableList.as_mutable(AsaList()) |
| 195 |
) |
| 196 |
backup_state: Mapped[bool] = mapped_column() # Upcoming post V3 spec |
| 197 |
device_type: Mapped[str] = mapped_column(String(64)) |
| 198 |
|
| 199 |
# a JSON string as returned from registration |
| 200 |
extensions: Mapped[str | None] = mapped_column(String(255)) |
| 201 |
create_datetime: Mapped[datetime.datetime] = mapped_column( |
| 202 |
server_default=func.now() |
| 203 |
) |
| 204 |
lastuse_datetime: Mapped[datetime.datetime] = mapped_column() |
| 205 |
# name is provided by user - we make sure is unique per user |
| 206 |
name: Mapped[str] = mapped_column(String(64)) |
| 207 |
|
| 208 |
# Usage - a credential can EITHER be for first factor or secondary factor |
| 209 |
usage: Mapped[str] = mapped_column(String(64)) |
| 210 |
|
| 211 |
try: |
| 212 |
import webauthn as webauthn_pkg |
| 213 |
|
| 214 |
@declared_attr |
| 215 |
def user(cls): |
| 216 |
return relationship("User", back_populates="webauthn") |
| 217 |
|
| 218 |
except ImportError: # pragma: no cover |
| 219 |
pass |
| 220 |
|
| 221 |
@declared_attr |
| 222 |
def user_id(cls) -> Mapped[int]: |
| 223 |
return mapped_column( |
| 224 |
ForeignKey(f"{FsModels.user_table_name}.id", ondelete="CASCADE") |
| 225 |
) |