File size: 1,660 Bytes
09f6c98
93266ae
b362e29
6f3b0f5
 
 
 
09f6c98
6f3b0f5
 
 
09f6c98
6f3b0f5
 
 
 
09f6c98
 
6f3b0f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, HTTPException, Request, Depends
from config_provider import get_config, service_config
from service_config import ServiceConfig

router = APIRouter()

@router.post("/login")
async def login(request: Request, config: ServiceConfig = Depends(get_config)):
    data = await request.json()
    username = data.get("username")
    password = data.get("password")
    user = next((u for u in config.users if u["username"] == username), None)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid username or password")

    hashed = user["password_hash"].encode()
    if not bcrypt.checkpw(password.encode(), hashed):
        raise HTTPException(status_code=401, detail="Invalid username or password")

    return {"message": "Login successful"}

@router.post("/change_password")
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"}