Spaces:
Paused
Paused
Create backend/routes_auth.py
Browse files- backend/routes_auth.py +56 -0
backend/routes_auth.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
import bcrypt
|
| 3 |
+
import secrets
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from fastapi import APIRouter
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from backend.database import DB_FILE, USERS_DIR
|
| 9 |
+
|
| 10 |
+
router = APIRouter()
|
| 11 |
+
|
| 12 |
+
class UserAuth(BaseModel):
|
| 13 |
+
username: str
|
| 14 |
+
password: str
|
| 15 |
+
|
| 16 |
+
@router.post("/api/register")
|
| 17 |
+
async def register(user: UserAuth):
|
| 18 |
+
conn = sqlite3.connect(DB_FILE)
|
| 19 |
+
c = conn.cursor()
|
| 20 |
+
c.execute("SELECT username FROM users WHERE username=?", (user.username,))
|
| 21 |
+
if c.fetchone(): return {"error": "Username already exists"}
|
| 22 |
+
|
| 23 |
+
hashed_pw = bcrypt.hashpw(user.password.encode('utf-8'), bcrypt.gensalt())
|
| 24 |
+
token = secrets.token_hex(16)
|
| 25 |
+
# DEVPORTAL Default Settings
|
| 26 |
+
default_settings = json.dumps({"theme": "#eacc00", "bg": "#0a0a0a", "font": "'Fira Code', monospace"})
|
| 27 |
+
|
| 28 |
+
c.execute("INSERT INTO users VALUES (?, ?, ?, ?)", (user.username, hashed_pw, token, default_settings))
|
| 29 |
+
conn.commit()
|
| 30 |
+
conn.close()
|
| 31 |
+
|
| 32 |
+
user_path = os.path.join(USERS_DIR, user.username)
|
| 33 |
+
os.makedirs(user_path, exist_ok=True)
|
| 34 |
+
return {"success": True, "token": token, "username": user.username, "settings": default_settings}
|
| 35 |
+
|
| 36 |
+
@router.post("/api/login")
|
| 37 |
+
async def login(user: UserAuth):
|
| 38 |
+
conn = sqlite3.connect(DB_FILE)
|
| 39 |
+
c = conn.cursor()
|
| 40 |
+
c.execute("SELECT password, token, settings FROM users WHERE username=?", (user.username,))
|
| 41 |
+
row = c.fetchone()
|
| 42 |
+
conn.close()
|
| 43 |
+
|
| 44 |
+
if row and bcrypt.checkpw(user.password.encode('utf-8'), row[0]):
|
| 45 |
+
return {"success": True, "token": row[1], "username": user.username, "settings": row[2]}
|
| 46 |
+
return {"error": "Invalid credentials"}
|
| 47 |
+
|
| 48 |
+
@router.post("/api/settings")
|
| 49 |
+
async def update_settings(data: dict):
|
| 50 |
+
conn = sqlite3.connect(DB_FILE)
|
| 51 |
+
c = conn.cursor()
|
| 52 |
+
c.execute("UPDATE users SET settings=? WHERE token=?", (json.dumps(data.get("settings", {})), data.get("token")))
|
| 53 |
+
conn.commit()
|
| 54 |
+
conn.close()
|
| 55 |
+
return {"success": True}
|
| 56 |
+
|