Spaces:
Configuration error
Configuration error
Add security
Browse files- app/security.py +40 -0
app/security.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Password hashing and JWT token handling (stdlib-only PBKDF2, no bcrypt deps)."""
|
| 2 |
+
import datetime
|
| 3 |
+
import hashlib
|
| 4 |
+
import hmac
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import jwt
|
| 8 |
+
|
| 9 |
+
from .config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
| 10 |
+
|
| 11 |
+
_ITERATIONS = 200_000
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def hash_password(password: str) -> str:
|
| 15 |
+
salt = os.urandom(16)
|
| 16 |
+
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, _ITERATIONS)
|
| 17 |
+
return f"{salt.hex()}${digest.hex()}"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def verify_password(password: str, stored: str) -> bool:
|
| 21 |
+
try:
|
| 22 |
+
salt_hex, digest_hex = stored.split("$")
|
| 23 |
+
except ValueError:
|
| 24 |
+
return False
|
| 25 |
+
digest = hashlib.pbkdf2_hmac("sha256", password.encode(),
|
| 26 |
+
bytes.fromhex(salt_hex), _ITERATIONS)
|
| 27 |
+
return hmac.compare_digest(digest.hex(), digest_hex)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def create_access_token(user_id: str) -> str:
|
| 31 |
+
payload = {
|
| 32 |
+
"sub": user_id,
|
| 33 |
+
"exp": datetime.datetime.utcnow()
|
| 34 |
+
+ datetime.timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES),
|
| 35 |
+
}
|
| 36 |
+
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def decode_access_token(token: str) -> dict:
|
| 40 |
+
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|