ciyidogan commited on
Commit
6f3b0f5
·
verified ·
1 Parent(s): 12832d8

Create auth_controller.py

Browse files
Files changed (1) hide show
  1. auth_controller.py +45 -0
auth_controller.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Request
2
+ import bcrypt
3
+ from service_config import ServiceConfig
4
+
5
+ router = APIRouter()
6
+ service_config = ServiceConfig()
7
+ service_config.load()
8
+
9
+ @router.post("/login")
10
+ async def login(request: Request):
11
+ data = await request.json()
12
+ username = data.get("username")
13
+ password = data.get("password")
14
+ user = next((u for u in service_config.users if u["username"] == username), None)
15
+ if not user:
16
+ raise HTTPException(status_code=401, detail="Invalid username or password")
17
+
18
+ hashed = user["password_hash"].encode()
19
+ if not bcrypt.checkpw(password.encode(), hashed):
20
+ raise HTTPException(status_code=401, detail="Invalid username or password")
21
+
22
+ return {"message": "Login successful"}
23
+
24
+ @router.post("/change_password")
25
+ async def change_password(request: Request):
26
+ data = await request.json()
27
+ username = data.get("username")
28
+ old_password = data.get("old_password")
29
+ new_password = data.get("new_password")
30
+ user = next((u for u in service_config.users if u["username"] == username), None)
31
+ if not user:
32
+ raise HTTPException(status_code=404, detail="User not found")
33
+
34
+ if not bcrypt.checkpw(old_password.encode(), user["password_hash"].encode()):
35
+ raise HTTPException(status_code=401, detail="Old password is incorrect")
36
+
37
+ new_hash = bcrypt.hashpw(new_password.encode(), bcrypt.gensalt()).decode()
38
+ user["password_hash"] = new_hash
39
+
40
+ # Config'i kaydet (burada basitçe dosyaya yazılması gerekir)
41
+ with open(service_config.config_path, "w", encoding="utf-8") as f:
42
+ import json
43
+ json.dump(service_config, f, indent=2)
44
+
45
+ return {"message": "Password updated successfully"}