Debian Codegraph @

flask_security/models/fsqla.py

raw
1 """
2 Copyright 2019-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 Flask-SqlAlchemy.
7
8 You can change the table names by passing them in to the set_db_info() method.
9
10 BE AWARE: Once any version of this is shipped no changes can be made - instead
11 a new version needs to be created.
12 """
13
14 # mypy: disable-error-code="assignment"
15 # pyright: reportAssignmentType = false, reportIncompatibleVariableOverride=false
16
17 from typing import cast
18 from sqlalchemy import (
19 Boolean,
20 DateTime,
21 Column,
22 Integer,
23 String,
24 ForeignKey,
25 )
26 from sqlalchemy.ext.declarative import declared_attr
27 from sqlalchemy.ext.mutable import MutableList
28 from sqlalchemy.sql import func
29
30 from flask_security import AsaList, RoleMixin, UserMixin, naive_utcnow
31
32
33 class FsModels:
34 """
35 Helper class for model mixins.
36 This records the ``db`` (which is a Flask-SqlAlchemy object) for use in
37 mixins.
38 """
39
40 roles_users = None
41 db = None
42 fs_model_version = 1
43 user_table_name = "user"
44 role_table_name = "role"
45 webauthn_table_name = "webauthn"
46
47 @classmethod
48 def set_db_info(
49 cls,
50 appdb,
51 user_table_name="user",
52 role_table_name="role",
53 webauthn_table_name="webauthn",
54 ):
55 """Initialize Model.
56 This needs to be called after the DB object has been created
57 (e.g. db = Sqlalchemy()).
58
59 .. note::
60 This should only be used if you are utilizing the fsqla data
61 models. With your own models you would need similar but slightly
62 different code.
63 """
64 cls.db = appdb
65 cls.user_table_name = user_table_name
66 cls.role_table_name = role_table_name
67 cls.webauthn_table_name = webauthn_table_name
68 cls.roles_users = appdb.Table(
69 "roles_users",
70 Column("user_id", Integer(), ForeignKey(f"{cls.user_table_name}.id")),
71 Column("role_id", Integer(), ForeignKey(f"{cls.role_table_name}.id")),
72 )
73
74
75 class FsRoleMixin(RoleMixin):
76 id = Column(Integer(), primary_key=True)
77 name = Column(String(80), unique=True, nullable=False)
78 description = Column(String(255))
79 # A comma separated list of strings
80 permissions = Column(
81 MutableList.as_mutable(AsaList()), nullable=True # type: ignore
82 )
83 update_datetime = Column(
84 type_=DateTime,
85 nullable=False,
86 server_default=func.now(),
87 onupdate=naive_utcnow,
88 )
89
90
91 class FsUserMixin(UserMixin):
92 """User information"""
93
94 # flask_security basic fields
95 id = Column(Integer, primary_key=True)
96 email = Column(String(255), unique=True, nullable=False)
97 # Username is important since shouldn't expose email to other users in most cases.
98 username = Column(String(255))
99 password = Column(String(255), nullable=False)
100 active = cast(bool, Column(Boolean(), nullable=False))
101
102 # Flask-Security user identifier
103 fs_uniquifier = Column(String(64), unique=True, nullable=False)
104
105 # confirmable
106 confirmed_at = Column(DateTime())
107
108 # trackable
109 last_login_at = Column(DateTime())
110 current_login_at = Column(DateTime())
111 last_login_ip = Column(String(64))
112 current_login_ip = Column(String(64))
113 login_count = Column(Integer)
114
115 # 2FA
116 tf_primary_method = Column(String(64), nullable=True)
117 tf_totp_secret = Column(String(255), nullable=True)
118 tf_phone_number = Column(String(128), nullable=True)
119
120 @declared_attr
121 def roles(cls):
122 # The first arg is a class name, the backref is a column name
123 return FsModels.db.relationship(
124 "Role",
125 secondary=FsModels.roles_users,
126 backref=FsModels.db.backref(
127 "users", lazy="dynamic", cascade_backrefs=False
128 ),
129 )
130
131 create_datetime = Column(type_=DateTime, nullable=False, server_default=func.now())
132 update_datetime = Column(
133 type_=DateTime,
134 nullable=False,
135 server_default=func.now(),
136 onupdate=naive_utcnow,
137 )