-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathauth.py
More file actions
462 lines (396 loc) · 15.6 KB
/
auth.py
File metadata and controls
462 lines (396 loc) · 15.6 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""Define the Autorization Manager."""
import datetime
import jwt
from fastapi import BackgroundTasks, Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import NameEmail
from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession
from app.config.settings import get_settings
from app.database.db import get_database
from app.database.helpers import (
get_user_by_email_,
get_user_by_id_,
hash_password,
)
from app.managers.email import EmailManager
from app.managers.helpers import MAX_JWT_TOKEN_LENGTH, is_valid_jwt_format
from app.models.enums import RoleType
from app.models.user import User
from app.schemas.email import EmailTemplateSchema
from app.schemas.request.auth import TokenRefreshRequest
class ResponseMessages:
"""Error strings for different circumstances."""
CANT_GENERATE_JWT = "Unable to generate the JWT"
CANT_GENERATE_REFRESH = "Unable to generate the Refresh Token"
CANT_GENERATE_VERIFY = "Unable to generate the Verification Token"
CANT_GENERATE_RESET = "Unable to generate the Password Reset Token"
INVALID_TOKEN = "That token is Invalid" # noqa: S105
EXPIRED_TOKEN = "That token has Expired" # noqa: S105
VERIFICATION_SUCCESS = "User successfully Verified"
USER_NOT_FOUND = "User not Found"
ALREADY_VALIDATED = "You are already validated"
VALIDATION_RESENT = "Validation email re-sent"
RESET_EMAIL_SENT = "Password reset email sent if user exists"
PASSWORD_RESET_SUCCESS = "Password successfully reset" # noqa: S105
class AuthManager:
"""Handle the JWT Auth."""
@staticmethod
def encode_token(user: User) -> str:
"""Create and return a JTW token."""
try:
payload = {
"sub": user.id,
"exp": datetime.datetime.now(tz=datetime.timezone.utc)
+ datetime.timedelta(
minutes=get_settings().access_token_expire_minutes
),
}
return jwt.encode(
payload, get_settings().secret_key, algorithm="HS256"
)
except (jwt.PyJWTError, AttributeError) as exc:
# log the exception
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.CANT_GENERATE_JWT
) from exc
@staticmethod
def encode_refresh_token(user: User) -> str:
"""Create and return a JTW token."""
try:
payload = {
"sub": user.id,
"exp": datetime.datetime.now(tz=datetime.timezone.utc)
+ datetime.timedelta(minutes=60 * 24 * 30),
"typ": "refresh",
}
return jwt.encode(
payload, get_settings().secret_key, algorithm="HS256"
)
except (jwt.PyJWTError, AttributeError) as exc:
# log the exception
raise HTTPException(
status.HTTP_401_UNAUTHORIZED,
ResponseMessages.CANT_GENERATE_REFRESH,
) from exc
@staticmethod
def encode_verify_token(user: User) -> str:
"""Create and return a JTW token."""
try:
payload = {
"sub": user.id,
"exp": datetime.datetime.now(tz=datetime.timezone.utc)
+ datetime.timedelta(minutes=10),
"typ": "verify",
}
return jwt.encode(
payload, get_settings().secret_key, algorithm="HS256"
)
except (jwt.PyJWTError, AttributeError) as exc:
# log the exception
raise HTTPException(
status.HTTP_401_UNAUTHORIZED,
ResponseMessages.CANT_GENERATE_VERIFY,
) from exc
@staticmethod
def encode_reset_token(user: User) -> str:
"""Create and return a password reset JWT token."""
try:
payload = {
"sub": user.id,
"exp": datetime.datetime.now(tz=datetime.timezone.utc)
+ datetime.timedelta(minutes=30),
"typ": "reset",
}
return jwt.encode(
payload, get_settings().secret_key, algorithm="HS256"
)
except (jwt.PyJWTError, AttributeError) as exc:
# log the exception
raise HTTPException(
status.HTTP_401_UNAUTHORIZED,
ResponseMessages.CANT_GENERATE_RESET,
) from exc
@staticmethod
async def refresh(
refresh_token: TokenRefreshRequest, session: AsyncSession
) -> str:
"""Refresh an expired JWT token, given a valid Refresh token."""
# Validate token format before processing
if (
not refresh_token.refresh
or len(refresh_token.refresh) > MAX_JWT_TOKEN_LENGTH
or not is_valid_jwt_format(refresh_token.refresh)
):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
try:
payload = jwt.decode(
refresh_token.refresh,
get_settings().secret_key,
algorithms=["HS256"],
options={"verify_sub": False},
)
if payload["typ"] != "refresh":
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
user_data = await get_user_by_id_(payload["sub"], session)
if not user_data:
raise HTTPException(
status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
)
# block a banned user
if bool(user_data.banned):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
new_token = AuthManager.encode_token(user_data)
except jwt.ExpiredSignatureError as exc:
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.EXPIRED_TOKEN
) from exc
except jwt.InvalidTokenError as exc:
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
) from exc
else:
return new_token
@staticmethod
async def verify(code: str, session: AsyncSession) -> None:
"""Verify a new User's Email using the token they were sent."""
# Validate token format before processing
if (
not code
or len(code) > MAX_JWT_TOKEN_LENGTH
or not is_valid_jwt_format(code)
):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
try:
payload = jwt.decode(
code,
get_settings().secret_key,
algorithms=["HS256"],
options={"verify_sub": False},
)
user_data = await session.get(User, payload["sub"])
if not user_data:
raise HTTPException(
status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
)
if payload["typ"] != "verify":
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
# block a banned user
if bool(user_data.banned):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
if bool(user_data.verified):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
await session.execute(
update(User)
.where(User.id == payload["sub"])
.values(
verified=True,
)
)
await session.commit()
raise HTTPException(
status.HTTP_200_OK, ResponseMessages.VERIFICATION_SUCCESS
)
except jwt.ExpiredSignatureError as exc:
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.EXPIRED_TOKEN
) from exc
except jwt.InvalidTokenError as exc:
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
) from exc
@staticmethod
async def forgot_password(
email: str, background_tasks: BackgroundTasks, session: AsyncSession
) -> None:
"""Send a password reset email to the user if they exist."""
# Get user by email - but don't reveal if user exists for security
user = await get_user_by_email_(email, session)
# Always return success message to prevent email enumeration
if not user:
return
# Don't send reset email to banned users
if bool(user.banned):
return
# Generate reset token
reset_token = AuthManager.encode_reset_token(user)
# Send password reset email
email_manager = EmailManager()
email_manager.template_send(
background_tasks,
EmailTemplateSchema(
recipients=[NameEmail(name=user.first_name, email=user.email)],
subject=f"{get_settings().api_title} - Password Reset",
body={
"name": user.first_name,
"application": get_settings().api_title,
"base_url": get_settings().base_url,
"reset_token": reset_token,
},
template_name="password_reset.html",
),
)
@staticmethod
async def reset_password(
code: str, new_password: str, session: AsyncSession
) -> None:
"""Reset a user's password using the reset token."""
try:
payload = jwt.decode(
code,
get_settings().secret_key,
algorithms=["HS256"],
options={"verify_sub": False},
)
user_data = await session.get(User, payload["sub"])
if not user_data:
raise HTTPException(
status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
)
if payload["typ"] != "reset":
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
# Block banned users from resetting password
if bool(user_data.banned):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
# Hash the new password
hashed_password = hash_password(new_password)
# Update the user's password
await session.execute(
update(User)
.where(User.id == payload["sub"])
.values(password=hashed_password)
)
await session.commit()
except jwt.ExpiredSignatureError as exc:
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.EXPIRED_TOKEN
) from exc
except jwt.InvalidTokenError as exc:
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
) from exc
@staticmethod
async def resend_verify_code(
user: int, background_tasks: BackgroundTasks, session: AsyncSession
) -> None: # pragma: no cover (code not used at this time)
"""Resend the user a verification email."""
user_data = await get_user_by_id_(user, session)
if not user_data:
raise HTTPException(
status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
)
# block a banned user
if bool(user_data.banned):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
)
if bool(user_data.verified):
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
ResponseMessages.ALREADY_VALIDATED,
)
email = EmailManager()
user_full_name = f"{user_data.first_name} {user_data.last_name}"
email.template_send(
background_tasks,
EmailTemplateSchema(
recipients=[NameEmail(user_full_name, user_data.email)],
subject=f"Welcome to {get_settings().api_title}!",
body={
"application": f"{get_settings().api_title}",
"user": user_data.email,
"base_url": get_settings().base_url,
"verification": AuthManager.encode_verify_token(user_data),
},
template_name="welcome.html",
),
)
# await email.simple_send(
# EmailSchema(
# recipients=[user_data["email"]],
# subject=f"Welcome to {get_settings().api_title}!",
# body="Test Email",
# ),
# )
raise HTTPException(
status.HTTP_200_OK, ResponseMessages.VALIDATION_RESENT
)
bearer = HTTPBearer(auto_error=False)
async def get_jwt_user(
request: Request,
db: AsyncSession = Depends(get_database),
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
) -> User | None:
"""Get user from JWT token."""
if not credentials:
return None
try:
# Decode and validate the token
payload = jwt.decode(
credentials.credentials,
get_settings().secret_key,
algorithms=["HS256"],
options={"verify_sub": False},
)
user_data = await get_user_by_id_(payload["sub"], db)
# Check user validity - user must exist, be verified, and not banned
if not user_data:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ResponseMessages.INVALID_TOKEN,
)
if bool(user_data.banned) or not bool(user_data.verified):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ResponseMessages.INVALID_TOKEN,
)
# Store user in request state
request.state.user = user_data
except jwt.ExpiredSignatureError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ResponseMessages.EXPIRED_TOKEN,
) from exc
except jwt.InvalidTokenError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ResponseMessages.INVALID_TOKEN,
) from exc
else:
return user_data
oauth2_schema = get_jwt_user
def is_admin(request: Request) -> None:
"""Block if user is not an Admin."""
if request.state.user.role != RoleType.admin:
raise HTTPException(status.HTTP_403_FORBIDDEN, "Forbidden")
def can_edit_user(request: Request) -> None:
"""Check if the user can edit this resource.
True if they own the resource or are Admin
"""
if (
request.state.user.role != RoleType.admin
and request.state.user.id != int(request.path_params["user_id"])
):
raise HTTPException(status.HTTP_403_FORBIDDEN, "Forbidden")
def is_banned(request: Request) -> None:
"""Dont let banned users access the route."""
if request.state.user.banned:
raise HTTPException(status.HTTP_403_FORBIDDEN, "Banned!")