Debian Codegraph @

flask_security/models/sqla.py

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