Debian Codegraph @

docs/models.rst

raw
1 .. _models_topic:
2
3 Models
4 ======
5
6 Basics
7 ------
8
9 Flask-Security assumes you'll be using libraries such as SQLAlchemy,
10 MongoEngine or, Peewee to define a `User`
11 and `Role` data model. The fields on your models must follow a particular convention
12 depending on the functionality your app requires. Aside from this, you're free
13 to add any additional fields to your model(s) if you want.
14
15 .. note::
16 The User, Role, WebAuthn, and RefreshTracker models MUST subclass their respective mixin (along
17 with any other mixin the datastore requires). The pre-packaged models described
18 below do this for you.
19
20 .. code-block:: python
21
22 from flask_security import UserMixin, RoleMixin, WebAuthMixin, RefreshTrackerMixin
23
24 class User(<db specific base>, UserMixin):
25 ... define columns here
26
27 ... same for Role and WebAuthn
28
29 Packaged Models
30 ----------------
31 As more features are added to Flask-Security, the list of required fields and tables grow.
32 As you use these features, and therefore require these fields and tables, database migrations are required;
33 which are a bit of a pain. To make things easier - Flask-Security includes mixins that
34 contain ALL the fields and tables required for all features. They also contain
35 various `best practice` fields - such as update and create times. These mixins can
36 be easily extended to add any sort of custom fields and can be found in the
37 `models` module.
38
39 The provided models are versioned since they represent actual DB models, and any
40 changes require a schema migration (and perhaps a data migration). Applications
41 must specifically import the version they want (and handle any required migration).
42
43 There are two available models - one when using Flask-SQLAlchemy and one when
44 using 'raw' sqlalchemy or Flask-SQLAlchemy-Lite.
45
46 .. note::
47 Using these models, you can override the tables names (and provide them to .set_db_info()
48 however your model class names MUST be `User`, `Role`, `WebAuthn`, and `RefreshTracker`.
49
50 Flask-SQLAlchemy
51 ^^^^^^^^^^^^^^^^
52 Your application code should import just the required version e.g.:
53
54 .. code-block:: python
55
56 from flask_security.models import fsqla_v2 as fsqla
57 from flask_sqlalchemy import SQLAlchemy
58
59 db = SQLAlchemy(app)
60
61 # Define models
62 fsqla.FsModels.set_db_info(db)
63
64 class Role(db.Model, fsqla.FsRoleMixin):
65 pass
66
67 class User(db.Model, fsqla.FsUserMixin):
68 pass
69
70
71 A single method ``fsqla.FsModels.set_db_info`` is provided to glue the supplied models to your
72 DB instance. This is only needed if you use the packaged models.
73
74 Flask-SQLAlchemy-Lite
75 ^^^^^^^^^^^^^^^^^^^^^
76 Your application code should import just the required version e.g.:
77
78 .. code-block:: python
79
80 from flask_security.models import sqla as sqla
81 from flask_sqlalchemy_lite import SQLAlchemy
82
83 db = SQLAlchemy(app)
84
85 # Define models
86 class Model(DeclarativeBase):
87 pass
88
89 # NOTE: call this PRIOR to declaring models
90 sqla.FsModels.set_db_info(base_model=Model)
91
92 class Role(Model, sqla.FsRoleMixin):
93 __tablename__ = "Role"
94 pass
95
96 class User(Model, sqla.FsUserMixin):
97 __tablename__ = "User"
98 pass
99
100 A single method ``sqla.FsModels.set_db_info`` is provided to glue the supplied mixins to your
101 models. This is only needed if you use the packaged models.
102
103 .. note::
104 This model requires Python >= 3.10.
105
106 Model Specification
107 -------------------
108
109 Your `User` model needs a Primary Key - Flask-Security doesn't actually reference
110 this - so it can be any name or type your application needs. It should be used in the
111 foreign relationship between `User` and `Role`. The `WebAuthn` model also
112 references this primary key (which can be overridden by providing a
113 suitable implementation of :py:meth:`flask_security.WebAuthnMixin.get_user_mapping`).
114
115 At the bare minimum your `User` and `Role` model must include the following fields:
116
117 **User**
118
119 * primary key
120 * ``email`` (for most features - unique, non-nullable)
121 * ``password`` (string, nullable)
122 * ``active`` (boolean, non-nullable)
123 * ``fs_uniquifier`` (string, 64 bytes, unique, non-nullable)
124 * a many-to-many relationship to table Role
125
126
127 **Role**
128
129 * primary key
130 * ``name`` (unique, non-nullable)
131 * ``description`` (string)
132 * a many-to-many relationship to table User
133
134
135 Additional Functionality
136 ------------------------
137
138 Depending on the application's configuration, additional fields may need to be
139 added to your database models. Note some fields are specified as 'list of string'
140 the ORM you are using is responsible for translating the list of string to a suitable
141 DB data type. For standard SQL-like databases, Flask-Security provides a utility
142 method :class:`.AsaList`.
143
144 Confirmable
145 ^^^^^^^^^^^
146
147 If you enable account confirmation by setting your application's
148 :py:data:`SECURITY_CONFIRMABLE` or :py:data:`SECURITY_CHANGE_EMAIL` configuration value to `True`,
149 your `User` model will require the following additional field:
150
151 * ``confirmed_at`` (datetime)
152
153 Trackable
154 ^^^^^^^^^
155
156 If you enable user tracking by setting your application's :py:data:`SECURITY_TRACKABLE`
157 configuration value to `True`, your `User` model will require the following
158 additional fields:
159
160 * ``last_login_at`` (datetime)
161 * ``current_login_at`` (datetime)
162 * ``last_login_ip`` (string)
163 * ``current_login_ip`` (string)
164 * ``login_count`` (integer)
165
166 Two_Factor
167 ^^^^^^^^^^
168
169 If you enable two-factor by setting your application's :py:data:`SECURITY_TWO_FACTOR`
170 configuration value to `True`, your `User` model will require the following
171 additional fields:
172
173 * ``tf_totp_secret`` (string, 255 bytes, nullable)
174 * ``tf_primary_method`` (string)
175
176 If you include 'sms' in :py:data:`SECURITY_TWO_FACTOR_ENABLED_METHODS`, your `User` model
177 will require the following additional field:
178
179 * ``tf_phone_number`` (string, 128 bytes, nullable)
180
181 Unified Sign In
182 ^^^^^^^^^^^^^^^
183
184 If you enable unified sign in by setting your application's :py:data:`SECURITY_UNIFIED_SIGNIN`
185 configuration value to `True`, your `User` model will require the following
186 additional fields:
187
188 * ``us_totp_secrets`` (an arbitrarily long Text field)
189
190 If you include 'sms' in :py:data:`SECURITY_US_ENABLED_METHODS`, your `User` model
191 will require the following additional field:
192
193 * ``us_phone_number`` (string, 64 bytes, nullable, unique)
194
195 Separate Identity Domains
196 ^^^^^^^^^^^^^^^^^^^^^^^^^
197 If you want authentication and refresh tokens to not be invalidated when the user changes their
198 password add the following to your `User` model:
199
200 * ``fs_token_uniquifier`` (string, 64 bytes, unique, non-nullable)
201
202 Username
203 ^^^^^^^^
204 If you set :py:data:`SECURITY_USERNAME_ENABLE` to `True`, then your `User` model
205 requires the following additional field:
206
207 * ``username`` (string, 64 bytes, unique, nullable)
208
209 Permissions
210 ^^^^^^^^^^^
211 If you want to protect endpoints with permissions, and assign permissions to roles
212 that are then assigned to users, the ``Role`` model requires:
213
214 * ``permissions`` (list of UnicodeText, nullable)
215
216 .. _webauthn_model:
217
218 WebAuthn
219 ^^^^^^^^
220 Flask Security can act as a WebAuthn Relying Party by enabling
221 :py:data:`SECURITY_WEBAUTHN`. This requires an additional table as well as
222 references from the User model. Users can have many WebAuthn credentials, and
223 Flask-Security must be able to locate a User record based on a credential id.
224
225 .. important::
226 It is important that you maintain data consistency when deleting WebAuthn
227 records or users.
228
229 The `User` model needs the following additional field:
230
231 * ``fs_webauthn_user_handle`` (string, 64 bytes, unique).
232 This is used as the `PublicKeyCredentialUserEntity` `id` value.
233
234 The `WebAuthn` model requires the following fields:
235
236 * ``id`` (primary key)
237 * ``credential_id`` (binary, 1024 bytes, indexed, non-nullable, unique)
238 * ``public_key`` (binary, 1024 bytes, non-nullable)
239 * ``sign_count`` (integer, default=0, non-nullable)
240 * ``transports`` (list of string/UnicodeText, nullable)
241 * ``extensions`` (string, 255 bytes)
242 * ``lastuse_datetime`` (datetime, non-nullable)
243 * ``name`` (string, 64 bytes, non-nullable)
244 * ``usage`` (string, 64 bytes, non-nullable)
245 * ``backup_state`` (boolean, non-nullable)
246 * ``device_type`` (string, 64 bytes, non-nullable) (The spec calls this ``Backup Eligibility``)
247
248 There needs to be a bi-directional relationship between the WebAuthn record and
249 the User record (since we need to look up the ``User`` based on a WebAuthn ``credential_id``.
250
251 **For SQLAlchemy**:
252
253 - Add the following to the WebAuthn model (assuming your primary key is named ``id``):
254
255 .. code-block:: python
256
257 @declared_attr
258 def user_id(cls) -> Mapped[int]:
259 return mapped_column(
260 ForeignKey("user.id", ondelete="CASCADE")
261 )
262
263 - Add the following to the User model:
264
265 .. code-block:: python
266
267 @declared_attr
268 def webauthn(cls):
269 return relationship(
270 "WebAuthn", back_populates="user", cascade="all, delete"
271 )
272
273 **For mongoengine**:
274
275 - Add the following to the WebAuthn model:
276
277 .. code-block:: python
278
279 user = ReferenceField("User")
280 def get_user_mapping(self) -> dict[str, str]:
281 """Return the mapping from webauthn back to User"""
282 return dict(id=self.user.id)
283
284 - Add the following to the User model:
285
286 .. code-block:: python
287
288 webauthn = ListField(ReferenceField(WebAuthn, reverse_delete_rule=PULL), default=[])
289
290 - To make sure all WebAuthn objects are deleted if the User is deleted:
291
292 .. code-block:: python
293
294 User.register_delete_rule(WebAuthn, "user", CASCADE)
295
296
297 **For peewee**:
298
299 Add the following to the WebAuthn model:
300
301 .. code-block:: python
302
303 user = ForeignKeyField(User, backref="webauthn")
304
305 This will add a column called ``user_id`` that references the User model's
306 ``id`` primary key field. It will also create a virtual column ``webauthn``
307 as part of the User model. Note that the default Peewee datastore implementation
308 calls ``delete_instance(recursive=True)`` which correctly deals with ensuring
309 that WebAuthn records get deleted if a User is deleted.
310
311 .. _refresh_tracker_model:
312
313 Refresh Tokens
314 ^^^^^^^^^^^^^^
315 Flask Security supports refresh tokens by enabling
316 :py:data:`SECURITY_REFRESH_TOKEN`. Internal to Flask-Security, refresh tokens
317 are tracked using a ``refresh_tracker`` table. This requires an additional table as well as
318 references from the User model. Users can have many refresh trackers/tokens.
319
320 .. important::
321 It is important that you maintain data consistency when deleting refresh_tracker
322 records or users.
323
324 The `FsRefreshTracker` model requires the following fields:
325
326 * ``id`` (primary key)
327 * ``refresh_family`` (string, 64 bytes, indexed, non-nullable, unique)
328 * ``gen`` (integer, non-nullable)
329 * ``expires_at`` (datetime, non-nullable)
330 * ``revoked_at`` (datetime)
331 * ``last_used_at`` (datetime, non-nullable)
332 * ``name`` (string, 64 bytes, non-nullable)
333
334 The User record needs to have a list of refresh trackers.
335
336 **For SQLAlchemy**:
337
338 - Add the following to the FsRefreshTracker model (assuming your primary key is named ``id``):
339
340 .. code-block:: python
341
342 @declared_attr
343 def user_id(cls) -> Mapped[int]:
344 return mapped_column(
345 ForeignKey("user.id", ondelete="CASCADE")
346 )
347
348 - Add the following to the User model:
349
350 .. code-block:: python
351
352 @declared_attr
353 def refresh_trackers(cls):
354 return relationship(
355 "FsRefreshTracker", cascade="all, delete"
356 )
357
358 **For mongoengine**:
359
360 - Add the following to the FsRefreshTracker model:
361
362 .. code-block:: python
363
364 user = ReferenceField("User")
365
366 - Add the following to the User model:
367
368 .. code-block:: python
369
370 refresh_trackers = ListField(ReferenceField(FsRefreshTracker, reverse_delete_rule=PULL), default=[])
371
372 - To make sure all FsRefreshTracker objects are deleted if the User is deleted:
373
374 .. code-block:: python
375
376 User.register_delete_rule(FsRefreshTracker, "user", CASCADE)
377
378 **For peewee**:
379
380 Add the following to the FsRefreshTracker model:
381
382 .. code-block:: python
383
384 user = ForeignKeyField(User, backref="refresh_trackers")
385
386 This will add a column called ``user_id`` that references the User model's
387 ``id`` primary key field. It will also create a virtual column ``refresh_trackers``
388 as part of the User model. Note that the default Peewee datastore implementation
389 calls ``delete_instance(recursive=True)`` which correctly deals with ensuring
390 that FsRefreshTracker records get deleted if a User is deleted.
391
392
393 Recovery Codes
394 ^^^^^^^^^^^^^^^
395 If :py:data:`SECURITY_MULTI_FACTOR_RECOVERY_CODES` is set to ``True`` then
396 the `User` model needs the following field:
397
398 * ``mf_recovery_codes`` (list of string/UnicodeText, nullable)
399
400 A recovery code can be used in place of any configured second-factor authenticator
401 (e.g. SMS, WebAuthn, ...).
402
403 Custom User Payload
404 ^^^^^^^^^^^^^^^^^^^
405
406 If you want a custom payload for JSON API responses, define
407 the method `get_security_payload` in your User model. The method must return a
408 serializable object:
409
410 .. code-block:: python
411
412 class User(db.Model, UserMixin):
413 # ... define columns ...
414
415 # Custom User Payload
416 def get_security_payload(self):
417 rv = super().get_security_payload()
418 # :meth:`User.calc_username`
419 rv["username"] = self.calc_username()
420 rv["confirmation_needed"] = self.confirmed_at is None
421 return rv