-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_repository.py
More file actions
244 lines (165 loc) · 6.85 KB
/
auth_repository.py
File metadata and controls
244 lines (165 loc) · 6.85 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from sqlalchemy import select, update
from sqlalchemy.orm import selectinload
from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession
from models import User, RefreshToken, VerificationCode, ResetToken
class AuthRepository:
def __init__(self, session: AsyncSession):
self.session = session
"""=== User ==="""
async def get_user_by_id(self, user_id: int) -> User | None:
"""Retrieves a user from the database by their unique ID.
Args:
user_id: The unique identifier of the user to retrieve.
Returns:
The User object if found, otherwise None.
"""
query = select(User).where(User.id == user_id).options(selectinload(User.department))
result = await self.session.execute(query)
return result.scalar_one_or_none()
async def get_user_by_email(self, email: str) -> User | None:
"""Retrieves a user from the database by their email address.
Note:
This method does not check the `is_active` status of the user.
The calling service is responsible for handling active and inactive users.
Args:
email: The email address of the user to retrieve.
Returns:
The User object if found, otherwise None.
"""
query = select(User).where(User.email == email).options(selectinload(User.department))
result = await self.session.execute(query)
return result.scalar_one_or_none()
async def save_user(self, user: User) -> User:
"""Saves a user to the database, either creating or updating it.
This method handles both the creation of a new user and the update
of an existing one. It adds the user object to the session, commits the
transaction, and refreshes the object to get the latest state from the
Args:
user: The User object to be saved.
Returns:
The saved User object, refreshed from the database.
"""
self.session.add(user)
await self.session.flush()
await self.session.refresh(user)
return user
"""=== Token ==="""
async def get_reset_token(self, token: str) -> ResetToken | None:
"""Retrieves an active, un-used password reset token.
Args:
token: The reset token string to search for.
Returns:
The ResetToken object if a valid token is found, otherwise None.
"""
query = select(ResetToken).where(
ResetToken.token == token,
ResetToken.expires_at > datetime.now(timezone.utc),
ResetToken.used == False
)
token = await self.session.execute(query)
return token.scalar_one_or_none()
async def get_active_token(self, token: str) -> RefreshToken | None:
"""Retrieves an active, un-used refresh token from the database.
Args:
token: The refresh token string to search for.
Returns:
The RefreshToken object if a valid token is found, otherwise None.
"""
query = select(RefreshToken).where(
RefreshToken.token == token,
RefreshToken.used == False,
RefreshToken.expires_at > datetime.now(timezone.utc)
)
result = await self.session.execute(query)
return result.scalar_one_or_none()
async def save_reset_token(self, token: ResetToken) -> None:
"""Saves a password reset token to the database.
Args:
token: The ResetToken object to save.
"""
self.session.add(token)
await self.session.flush()
async def save_refresh_token(self, refresh_token: RefreshToken) -> RefreshToken:
"""Saves a refresh token to the database.
Args:
refresh_token: The RefreshToken object to save.
Returns:
The saved RefreshToken object, refreshed from the database.
"""
self.session.add(refresh_token)
await self.session.flush()
await self.session.refresh(refresh_token)
return refresh_token
async def invalidate_reset_token(self, token: ResetToken) -> None:
"""Marks a password reset token as used in the database.
Args:
token: The ResetToken object to invalidate.
"""
token.used = True
await self.session.flush()
await self.session.refresh(token)
async def invalidate_refresh_token(self, token: RefreshToken) -> None:
"""Marks a refresh token as used in the database.
Args:
token: The RefreshToken object to invalidate.
"""
token.used = True
await self.session.flush()
await self.session.refresh(token)
async def invalidate_all_user_refresh_tokens(self, user_id: int) -> None:
"""Marks all of a user's refresh tokens as used in the database.
This is used to invalidate all active sessions for a user, for example,
after a password change.
Args:
user_id: The ID of the user whose tokens are to be invalidated.
"""
stmt = (
update(RefreshToken)
.where(RefreshToken.user_id == user_id, RefreshToken.used == False)
.values(used=True)
)
await self.session.execute(stmt)
await self.session.flush()
"""=== Email verification ==="""
async def get_verification_code_by_email(self, email: str) -> VerificationCode | None:
"""
Return verification code by email or None.
Args:
email (str): Email address.
Returns:
VerificationCode | None
"""
query = select(VerificationCode).where(
VerificationCode.email == email,
VerificationCode.used == False,
VerificationCode.expires_at > datetime.now(timezone.utc)
)
result =await self.session.execute(query)
return result.scalar_one_or_none()
async def save_verification_code(self, code: VerificationCode) -> None:
"""
Save verification code in database.
Args:
code (VerificationCode): Verification code object.
Returns:
None
"""
self.session.add(code)
await self.session.flush()
await self.session.refresh(code)
async def invalidate_all_verifications_codes_by_email(self, email: str) -> None:
"""
Invalidate all verification code by email.
Args:
email (str): Email address.
Returns:
None
"""
stmt = (
update(VerificationCode)
.where(VerificationCode.email == email, VerificationCode.used == False)
.values(used=True)
)
await self.session.execute(stmt)
await self.session.flush()