-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathaccounts.py
More file actions
227 lines (174 loc) · 7.42 KB
/
accounts.py
File metadata and controls
227 lines (174 loc) · 7.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import enum
from datetime import datetime, date, timedelta, timezone
from typing import List, Optional
from sqlalchemy import (
ForeignKey,
String,
Boolean,
DateTime,
Enum,
Integer,
func,
Text,
Date,
UniqueConstraint
)
from sqlalchemy.orm import (
Mapped,
mapped_column,
relationship,
validates
)
from database import Base
from database.validators import accounts as validators
from security.passwords import hash_password, verify_password
from security.utils import generate_secure_token
class UserGroupEnum(str, enum.Enum):
USER = "user"
MODERATOR = "moderator"
ADMIN = "admin"
class GenderEnum(str, enum.Enum):
MAN = "man"
WOMAN = "woman"
class UserGroupModel(Base):
__tablename__ = "user_groups"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[UserGroupEnum] = mapped_column(Enum(UserGroupEnum), nullable=False, unique=True)
users: Mapped[List["UserModel"]] = relationship("UserModel", back_populates="group")
def __repr__(self):
return f"<UserGroupModel(id={self.id}, name={self.name})>"
class UserModel(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True)
_hashed_password: Mapped[str] = mapped_column("hashed_password", String(255), nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False
)
group_id: Mapped[int] = mapped_column(ForeignKey("user_groups.id", ondelete="CASCADE"), nullable=False)
group: Mapped["UserGroupModel"] = relationship("UserGroupModel", back_populates="users")
activation_token: Mapped[Optional["ActivationTokenModel"]] = relationship(
"ActivationTokenModel",
back_populates="user",
cascade="all, delete-orphan"
)
password_reset_token: Mapped[Optional["PasswordResetTokenModel"]] = relationship(
"PasswordResetTokenModel",
back_populates="user",
cascade="all, delete-orphan"
)
refresh_tokens: Mapped[List["RefreshTokenModel"]] = relationship(
"RefreshTokenModel",
back_populates="user",
cascade="all, delete-orphan"
)
profile: Mapped[Optional["UserProfileModel"]] = relationship(
"UserProfileModel",
back_populates="user",
cascade="all, delete-orphan",
lazy="selectin"
)
def __repr__(self):
return f"<UserModel(id={self.id}, email={self.email}, is_active={self.is_active})>"
def has_group(self, group_name: UserGroupEnum) -> bool:
return self.group.name == group_name
@classmethod
def create(cls, email: str, raw_password: str, group_id: int | Mapped[int]) -> "UserModel":
"""
Factory method to create a new UserModel instance.
This method simplifies the creation of a new user by handling
password hashing and setting required attributes.
"""
user = cls(email=email, group_id=group_id)
user.password = raw_password
return user
@property
def password(self) -> None:
raise AttributeError("Password is write-only. Use the setter to set the password.")
@password.setter
def password(self, raw_password: str) -> None:
"""
Set the user's password after validating its strength and hashing it.
"""
validators.validate_password_strength(raw_password)
self._hashed_password = hash_password(raw_password)
def verify_password(self, raw_password: str) -> bool:
"""
Verify the provided password against the stored hashed password.
"""
return verify_password(raw_password, self._hashed_password)
@validates("email")
def validate_email(self, key, value):
return validators.validate_email(value.lower())
class UserProfileModel(Base):
__tablename__ = "user_profiles"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
first_name: Mapped[Optional[str]] = mapped_column(String(100))
last_name: Mapped[Optional[str]] = mapped_column(String(100))
avatar: Mapped[Optional[str]] = mapped_column(String(255))
gender: Mapped[Optional[GenderEnum]] = mapped_column(Enum(GenderEnum))
date_of_birth: Mapped[Optional[date]] = mapped_column(Date)
info: Mapped[Optional[str]] = mapped_column(Text)
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
unique=True)
user: Mapped[UserModel] = relationship("UserModel", back_populates="profile")
__table_args__ = (UniqueConstraint("user_id"),)
def __repr__(self):
return (
f"<UserProfileModel(id={self.id}, first_name={self.first_name}, last_name={self.last_name}, "
f"gender={self.gender}, date_of_birth={self.date_of_birth})>"
)
class TokenBaseModel(Base):
__abstract__ = True
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
token: Mapped[str] = mapped_column(
String(64),
unique=True,
nullable=False,
default=generate_secure_token
)
expires_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
default=lambda: datetime.now(timezone.utc) + timedelta(days=1)
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
class ActivationTokenModel(TokenBaseModel):
__tablename__ = "activation_tokens"
user: Mapped[UserModel] = relationship("UserModel", back_populates="activation_token")
__table_args__ = (UniqueConstraint("user_id"),)
def __repr__(self):
return f"<ActivationTokenModel(id={self.id}, token={self.token}, expires_at={self.expires_at})>"
class PasswordResetTokenModel(TokenBaseModel):
__tablename__ = "password_reset_tokens"
user: Mapped[UserModel] = relationship("UserModel", back_populates="password_reset_token")
__table_args__ = (UniqueConstraint("user_id"),)
def __repr__(self):
return f"<PasswordResetTokenModel(id={self.id}, token={self.token}, expires_at={self.expires_at})>"
class RefreshTokenModel(TokenBaseModel):
__tablename__ = "refresh_tokens"
user: Mapped[UserModel] = relationship("UserModel", back_populates="refresh_tokens")
token: Mapped[str] = mapped_column(
String(512),
unique=True,
nullable=False,
default=generate_secure_token
)
@classmethod
def create(cls, user_id: int | Mapped[int], days_valid: int, token: str) -> "RefreshTokenModel":
"""
Factory method to create a new RefreshTokenModel instance.
This method simplifies the creation of a new refresh token by calculating
the expiration date based on the provided number of valid days and setting
the required attributes.
"""
expires_at = datetime.now(timezone.utc) + timedelta(days=days_valid)
return cls(user_id=user_id, expires_at=expires_at, token=token)
def __repr__(self):
return f"<RefreshTokenModel(id={self.id}, token={self.token}, expires_at={self.expires_at})>"