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 refresh_table_name = "fs_refresh"
47
48 @classmethod
49 def set_db_info(
50 cls,
51 appdb,
52 user_table_name="user",
53 role_table_name="role",
54 webauthn_table_name="webauthn",
55 refresh_table_name="fs_refresh",
56 ):
57 """Initialize Model.
58 This needs to be called after the DB object has been created
59 (e.g., db = Sqlalchemy()).
60
61 .. note::
62 This should only be used if you are using the fsqla data
63 models. With your own models you would need similar but slightly
64 different code.
65 """
66 cls.db = appdb
67 cls.user_table_name = user_table_name
68 cls.role_table_name = role_table_name
69 cls.webauthn_table_name = webauthn_table_name
70 cls.refresh_table_name = refresh_table_name
71 cls.roles_users = appdb.Table(
72 "roles_users",
73 Column("user_id", Integer(), ForeignKey(f"{cls.user_table_name}.id")),
74 Column("role_id", Integer(), ForeignKey(f"{cls.role_table_name}.id")),
75 )
76
77
78 class FsRoleMixin(RoleMixin):
79 id = Column(Integer(), primary_key=True)
80 name = Column(String(80), unique=True, nullable=False)
81 description = Column(String(255))
82 # A comma separated list of strings
83 permissions = Column(
84 MutableList.as_mutable(AsaList()), nullable=True # type: ignore
85 )
86 update_datetime = Column(
87 type_=DateTime,
88 nullable=False,
89 server_default=func.now(),
90 onupdate=naive_utcnow,
91 )
92
93
94 class FsUserMixin(UserMixin):
95 """User information"""
96
97 # flask_security basic fields
98 id = Column(Integer, primary_key=True)
99 email = Column(String(255), unique=True, nullable=False)
100 # Username is important since shouldn't expose email to other users in most cases.
101 username = Column(String(255))
102 password = Column(String(255), nullable=False)
103 active = cast(bool, Column(Boolean(), nullable=False))
104
105 # Flask-Security user identifier
106 fs_uniquifier = Column(String(64), unique=True, nullable=False)
107
108 # confirmable
109 confirmed_at = Column(DateTime())
110
111 # trackable
112 last_login_at = Column(DateTime())
113 current_login_at = Column(DateTime())
114 last_login_ip = Column(String(64))
115 current_login_ip = Column(String(64))
116 login_count = Column(Integer)
117
118 # 2FA
119 tf_primary_method = Column(String(64), nullable=True)
120 tf_totp_secret = Column(String(255), nullable=True)
121 tf_phone_number = Column(String(128), nullable=True)
122
123 @declared_attr
124 def roles(cls):
125 # The first arg is a class name, the backref is a column name
126 return FsModels.db.relationship(
127 "Role",
128 secondary=FsModels.roles_users,
129 backref=FsModels.db.backref(
130 "users", lazy="dynamic", cascade_backrefs=False
131 ),
132 )
133
134 create_datetime = Column(type_=DateTime, nullable=False, server_default=func.now())
135 update_datetime = Column(
136 type_=DateTime,
137 nullable=False,
138 server_default=func.now(),
139 onupdate=naive_utcnow,
140 )