Spaces:
Sleeping
Sleeping
Create login.py
Browse files
login.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# services/login.py
|
| 3 |
+
from fastapi import APIRouter, HTTPException
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
import sqlite3, os, hmac, hashlib
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
# Resolve absolute path to db/users.db (adjust if your file is elsewhere)
|
| 11 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # .../services
|
| 12 |
+
PROJECT_ROOT = os.path.dirname(BASE_DIR) # project root
|
| 13 |
+
DB_PATH = os.path.join(PROJECT_ROOT, "db", "users.db") # .../db/users.db
|
| 14 |
+
|
| 15 |
+
def get_conn():
|
| 16 |
+
# Helpful debug: see exactly which file is used
|
| 17 |
+
print(f"[login.py] Connecting to DB: {DB_PATH} | exists={os.path.exists(DB_PATH)}")
|
| 18 |
+
return sqlite3.connect(DB_PATH)
|
| 19 |
+
|
| 20 |
+
def pbkdf2_hash(password: str, salt_hex: Optional[str] = None) -> tuple[str, str]:
|
| 21 |
+
if not salt_hex:
|
| 22 |
+
salt_hex = os.urandom(16).hex()
|
| 23 |
+
salt = bytes.fromhex(salt_hex)
|
| 24 |
+
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000)
|
| 25 |
+
return dk.hex(), salt_hex
|
| 26 |
+
|
| 27 |
+
def verify_password(password: str, stored_hash_hex: str, salt_hex: str) -> bool:
|
| 28 |
+
actual_hash_hex, _ = pbkdf2_hash(password, salt_hex)
|
| 29 |
+
return hmac.compare_digest(actual_hash_hex, stored_hash_hex)
|
| 30 |
+
|
| 31 |
+
class LoginRequest(BaseModel):
|
| 32 |
+
username: str
|
| 33 |
+
password: str
|
| 34 |
+
|
| 35 |
+
@router.post("/login")
|
| 36 |
+
def login(req: LoginRequest):
|
| 37 |
+
username = req.username.strip()
|
| 38 |
+
password = req.password
|
| 39 |
+
|
| 40 |
+
if not username or not password:
|
| 41 |
+
raise HTTPException(status_code=400, detail="Username and password required.")
|
| 42 |
+
|
| 43 |
+
conn = get_conn()
|
| 44 |
+
try:
|
| 45 |
+
cur = conn.execute("SELECT password_hash, salt FROM users WHERE username = ?", (username,))
|
| 46 |
+
row = cur.fetchone()
|
| 47 |
+
if not row:
|
| 48 |
+
raise HTTPException(status_code=401, detail="Invalid credentials.")
|
| 49 |
+
stored_hash, salt = row
|
| 50 |
+
|
| 51 |
+
if not verify_password(password, stored_hash, salt):
|
| 52 |
+
raise HTTPException(status_code=401, detail="Invalid credentials.")
|
| 53 |
+
|
| 54 |
+
return {"ok": True, "username": username}
|
| 55 |
+
finally:
|
| 56 |
+
conn.close()
|