Spaces:
Running
Running
from fastapi import APIRouter, HTTPException, Request | |
import bcrypt | |
from service_config import ServiceConfig | |
import json | |
from log import log # β eksik olan satΔ±r | |
router = APIRouter() | |
service_config = ServiceConfig() | |
service_config.load() | |
async def login(request: Request): | |
data = await request.json() | |
username = data.get("username") | |
password = data.get("password") | |
user = next((u for u in service_config.users if u["username"] == username), None) | |
if not user: | |
log(f"β User '{username}' not found.") | |
raise HTTPException(status_code=401, detail="Invalid username or password") | |
hashed = user["password_hash"].encode() | |
log(f"π Checking password for user '{username}' with hash '{hashed}'.") | |
try: | |
if not bcrypt.checkpw(password.encode(), hashed): | |
log("β Password check failed.") | |
raise HTTPException(status_code=401, detail="Invalid username or password") | |
except Exception as e: | |
log(f"β Bcrypt check failed with error: {e}") | |
raise HTTPException(status_code=500, detail=f"Internal error during bcrypt check: {e}") | |
log(f"β Login successful for user '{username}'.") | |
return {"message": "Login successful"} | |
async def change_password(request: Request): | |
data = await request.json() | |
username = data.get("username") | |
old_password = data.get("old_password") | |
new_password = data.get("new_password") | |
user = next((u for u in service_config.users if u["username"] == username), None) | |
if not user: | |
raise HTTPException(status_code=404, detail="User not found") | |
if not bcrypt.checkpw(old_password.encode(), user["password_hash"].encode()): | |
raise HTTPException(status_code=401, detail="Old password is incorrect") | |
new_hash = bcrypt.hashpw(new_password.encode(), bcrypt.gensalt()).decode() | |
user["password_hash"] = new_hash | |
with open(service_config.config_path, "w", encoding="utf-8") as f: | |
json.dump(service_config, f, indent=2) | |
return {"message": "Password updated successfully"} | |