-
Notifications
You must be signed in to change notification settings - Fork 0
/
security.py
372 lines (330 loc) · 12.8 KB
/
security.py
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
"""
Security utilities for the API.
This module contains the utilities for the authentication and authorization
of the API. It includes the functions to hash passwords, generate and verify
the JSON Web Tokens (JWT) and the One-Time-Password (OTP) QR code.
"""
from datetime import datetime, timedelta, timezone
import json
import re
from typing import Literal, Self
from authlib.jose import jwt
from authlib.jose.errors import DecodeError
import bcrypt
from fastapi import Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import HTTPException
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, ValidationError, model_validator
import pyotp
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings, logger
from app.core.email import send_otp_email
from app.core.utils import generate_random_letters, validate_email
ALGORITHM = settings.JWT_ALGORITHM
SECRET_KEY = settings.JWT_SECRET_KEY
ACCESS_TOKEN_EXPIRE_MINUTES = settings.JWT_EXP
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_STR}/auth/login",
auto_error=True
)
class Token(BaseModel):
"""
A token returned from the authentication endpoint.
Attributes
----------
access_token : str
The actual token to use in the Authorization header.
token_type : str
The type of the token, either Bearer or JWT.
"""
access_token: str
token_type: str
def __str__(self) -> str:
return f"{self.token_type} {self.access_token}"
class TokenData(BaseModel):
"""
The data encoded in a JSON Web Token (JWT).
Attributes
----------
purpose : Literal["login", "reset-password", "email-verification", "OTP"]
The purpose of the token.
uuid : str
The UUID of the user.
roles : list[str] | None
The roles of the user, if purpose is "login".
email : str | None
The email of the user, if purpose is "email-verification".
username : str | None
The username of the user, if purpose is "reset-password".
"""
purpose: Literal["login", "reset-password", "email-verification", "OTP"]
uuid: str
roles: list[str] | None = None
email: str | None = None
username: str | None = None
@model_validator(mode="after")
def _enforce_data(self) -> Self:
match self.purpose:
case "login":
if not self.roles:
raise ValueError("Missing roles")
case "reset-password":
if not self.username:
raise ValueError("Missing username")
case "email-verification":
if not self.email:
raise ValueError("Missing email")
case "OTP":
pass
case _: # pragma: no cover # pylint: disable=unreachable
raise ValueError(f"Invalid purpose: {self.purpose}")
return self
def hash_password(password: str) -> str:
"""
Hashes a password using bcrypt.
:param str password: The password to hash.
:return str: The hashed password.
:raises HTTPException: If the password is not a string.
"""
try:
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
except UnicodeEncodeError as e:
raise HTTPException(
status_code=400,
detail=f"Password must be a string. {e.reason}",
) from e
return hashed.decode("utf-8")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verifies a password against a hashed password using bcrypt.
:param str plain_password: The password to verify.
:param str hashed_password: The hashed password to compare with.
:return bool: True if the password matches the hash, False otherwise.
:raises HTTPException: If the password is not a string.
"""
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
def create_access_token(
sub: TokenData,
exp: int = ACCESS_TOKEN_EXPIRE_MINUTES,
key: str = SECRET_KEY
) -> Token:
"""
Creates an access token for a given subject.
:param TokenData sub: The subject to encode in the token.
:param timedelta, optional exp: The time to live of the token in minutes.
:param str, optional key: The secret key to use for encoding.
:return Token: The encoded token.
"""
headers = {"alg": ALGORITHM, "token_type": "bearer"}
payload = {
"iss": settings.PROJECT_NAME,
"sub": jsonable_encoder(sub),
"exp": str(int(timedelta(minutes=exp).total_seconds())),
"iat": str(int(datetime.now(timezone.utc).timestamp())),
}
encoded_jwt = jwt.encode(headers, payload, key)
return Token(access_token=encoded_jwt, token_type="bearer")
def decode_access_token(token: str, strict: bool = True, key: str = SECRET_KEY) -> TokenData:
"""
Decodes a JSON Web Token (JWT) based on the given token, strictness, and secret key.
:param str token: The JWT to decode.
:param bool strict: If True, the token must start with "Bearer " or an HTTPException will be raised.
:param str key: The secret key used to decode the JWT. Defaults to SECRET_KEY.
:return TokenData: The decoded JWT data, which is a TokenData object containing the user's UUID and roles.
:raises HTTPException: If the token is invalid, expired, or has an invalid issuer.
"""
if strict:
# token.startswith("bearer "):
if not bool(re.match('bearer', token, re.I)):
raise HTTPException(
status_code=401, detail="Invalid authorization")
insensitive_token = re.compile(re.escape("bearer "), re.IGNORECASE)
token = insensitive_token.sub("", token) # token.replace("bearer ", "")
try:
claims = jwt.decode(token, key)
except DecodeError as e:
raise HTTPException(
status_code=401,
detail=f"Invalid token. {e}",
) from e
if not claims:
raise HTTPException(
status_code=401,
detail="Could not validate credentials",
)
if claims["iss"] != settings.PROJECT_NAME:
raise HTTPException(
status_code=401,
detail="Could not validate credentials | Invalid issuer",
)
iat = datetime.fromtimestamp(int(claims["iat"]), tz=timezone.utc)
if iat > datetime.now(timezone.utc):
raise HTTPException(
status_code=401,
detail="Token not yet valid",
)
exp = timedelta(seconds=int(claims["exp"]))
if iat + exp < datetime.now(timezone.utc):
raise HTTPException(
status_code=401,
detail="Token expired",
)
try:
return TokenData(**claims["sub"])
except ValidationError as e:
raise HTTPException(
status_code=401,
detail=f"Invalid token. {e}",
) from e
async def generate_otp(
db: AsyncSession,
user_uuid: str,
user_username: str,
user_otp_secret: str | None = None
) -> list[str, str]:
"""
Generate a new OTP URI and secret for a user.
If the user does not have an OTP secret, one is generated and stored in the user object.
:param str user_uuid: The UUID of the user.
:param str user_username: The username of the user.
:param str user_otp_secret: The OTP secret of the user if it exists.
:return tuple[str, str]: A tuple of the OTP URI and secret.
"""
if not user_otp_secret or user_otp_secret == "changeme":
from app.db_objects.db_models import User as User_DB # pylint: disable=import-outside-toplevel
user_otp_secret = generate_random_letters(
length=32, seed=user_uuid)
result = await db.execute(select(User_DB).filter(
User_DB.uuid == user_uuid
))
user_db = result.unique().scalars().first()
user_db.otp_secret = user_otp_secret
db.add(user_db)
await db.commit()
await db.refresh(user_db)
totp = pyotp.TOTP(
s=user_otp_secret,
name=user_username,
issuer=settings.PROJECT_NAME
)
uri = totp.provisioning_uri()
secret = totp.secret
return uri, secret
def validate_otp(user_username: str, user_otp_secret: str, otp: str, method: str) -> bool:
"""
Validate a one-time password (OTP) against a user's secret and chosen method.
:param str user_username: The username of the user.
:param str user_otp_secret: The OTP secret of the user.
:param str otp: The one-time password provided by the user.
:param str method: The method the user chose to use for OTP verification.
:return bool: True if the OTP is valid, False if it is not.
"""
if not user_otp_secret:
return False
match method:
case "none":
return True
case "authenticator":
totp = pyotp.TOTP(
s=user_otp_secret,
name=user_username,
interval=settings.OTP_AUTHENTICATOR_INTERVAL,
issuer=settings.PROJECT_NAME,
digits=settings.OTP_LENGTH
)
return totp.verify(otp)
case "email":
totp = pyotp.TOTP(
s=user_otp_secret,
name=user_username,
interval=settings.OTP_EMAIL_INTERVAL,
issuer=settings.PROJECT_NAME,
digits=settings.OTP_LENGTH
)
return totp.verify(otp)
case _:
raise HTTPException(
status_code=401,
detail="Invalid OTP method"
)
async def authenticate_user(db: AsyncSession, username: str, password: str, request: Request = None):
"""
Authenticate a user using their username/email and password.
:param Session db: The database session.
:param str username: The username or email of the user.
:param str password: The password of the user.
:param Request request: The Request object, defaults to None.
:raises HTTPException: 401 Unauthorized if the user is not found or the password is incorrect.
:raises HTTPException: 400 Bad Request if the user is inactive.
:return User: The user object if the user is found and the password is correct.
"""
from app.db_objects.user import get_user_by_email, get_user_by_username # pylint: disable=import-outside-toplevel
error_msg = HTTPException(
status_code=401,
detail="Incorrect username/email or password or email not verified",
headers={"WWW-Authenticate": "Bearer"},
)
# FIXME: remove comments to force first login with email
# if username in ["user", "manager", "admin"]:
# raise error_msg
if username == "[email protected]":
username = "admin"
email = validate_email(
username,
check_deliverability=settings.EMAIL_METHOD != "none",
raise_error=False
)
db_user = await get_user_by_email(db=db, email=email, raise_error=False)
if not db_user:
db_user = await get_user_by_username(
db=db, username=username, raise_error=False)
if not db_user:
raise error_msg
if not db_user.is_active:
if db_user.user_history:
raise HTTPException(
status_code=400,
detail=(f"Inactive user, please contact support at {settings.CONTACT_EMAIL}.\n",
f"Reason: {json.dumps(db_user.user_history[-1], indent=4)}")
)
raise HTTPException(
status_code=400,
detail=f"Inactive user, please contact support at {
settings.CONTACT_EMAIL}."
)
if verify_password(password, db_user.hashed_password):
if db_user.otp_method == "none":
return db_user
if not db_user.otp_secret:
logger.debug(f"Generating OTP for user {db_user.username}")
otp_secret = (await generate_otp(db, user_uuid=db_user.uuid,
user_username=db_user.username))[1]
else:
otp_secret = db_user.otp_secret
if db_user.otp_method == "email":
totp = pyotp.TOTP(
s=otp_secret,
name=db_user.username,
interval=settings.OTP_EMAIL_INTERVAL,
issuer=settings.PROJECT_NAME,
digits=settings.OTP_LENGTH
)
await send_otp_email(
recipient=db_user.email,
otp_code=totp.now(),
request=request
)
otp_request_token = create_access_token(
sub=TokenData(
purpose="OTP",
uuid=db_user.uuid
))
request.session.update(
{"otp_token": jsonable_encoder(otp_request_token)})
raise HTTPException(
status_code=401,
detail=jsonable_encoder({"error": "OTP-REQUIRED"}),
)
raise error_msg