Spaces:
Sleeping
Sleeping
Download backend/database.py from bevisssssss/AI: direct link, hf CLI and curl.
- Browser
- Download file 8.41 kB
-
https://huggingface.co/spaces/bevisssssss/AI/resolve/main/backend/database.py
- Command line
-
hf download hf://spaces/bevisssssss/AI/backend/database.py
-
curl -L -o database.py https://huggingface.co/spaces/bevisssssss/AI/resolve/main/backend/database.py
8.41 kB
| import os | |
| import sqlite3 | |
| import hashlib | |
| import secrets | |
| from datetime import datetime | |
| DB_DIR = os.path.join(os.path.dirname(__file__), "data") | |
| DB_PATH = os.path.join(DB_DIR, "admin.db") | |
| def get_conn(): | |
| os.makedirs(DB_DIR, exist_ok=True) | |
| conn = sqlite3.connect(DB_PATH) | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| def init_db(): | |
| conn = get_conn() | |
| conn.executescript(""" | |
| CREATE TABLE IF NOT EXISTS accounts ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| username TEXT UNIQUE NOT NULL, | |
| password_hash TEXT NOT NULL, | |
| role TEXT DEFAULT 'user', | |
| active INTEGER DEFAULT 1, | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| CREATE TABLE IF NOT EXISTS announcements ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| kind TEXT DEFAULT '公告', | |
| title TEXT NOT NULL, | |
| content TEXT NOT NULL, | |
| active INTEGER DEFAULT 1, | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| """) | |
| # Migration: add active column if missing | |
| try: | |
| conn.execute("ALTER TABLE accounts ADD COLUMN active INTEGER DEFAULT 1") | |
| except sqlite3.OperationalError: | |
| pass | |
| conn.commit() | |
| conn.close() | |
| def hash_password(password: str) -> str: | |
| salt = secrets.token_hex(8) | |
| h = hashlib.sha256((salt + password).encode()).hexdigest() | |
| return f"{salt}${h}" | |
| def verify_password(password: str, stored: str) -> bool: | |
| if "$" not in stored: | |
| return False | |
| salt, h = stored.split("$", 1) | |
| return hashlib.sha256((salt + password).encode()).hexdigest() == h | |
| def seed_admin(username="admin", password="admin123"): | |
| conn = get_conn() | |
| row = conn.execute("SELECT id FROM accounts WHERE username=?", (username,)).fetchone() | |
| if not row: | |
| conn.execute( | |
| "INSERT INTO accounts (username, password_hash, role, active) VALUES (?, ?, ?, 1)", | |
| (username, hash_password(password), "superadmin"), | |
| ) | |
| conn.commit() | |
| conn.close() | |
| def seed_user(username="user", password="user123"): | |
| conn = get_conn() | |
| row = conn.execute("SELECT id FROM accounts WHERE username=?", (username,)).fetchone() | |
| if not row: | |
| conn.execute( | |
| "INSERT INTO accounts (username, password_hash, role, active) VALUES (?, ?, ?, 1)", | |
| (username, hash_password(password), "user"), | |
| ) | |
| conn.commit() | |
| conn.close() | |
| # ─── Account CRUD ─── | |
| def list_accounts(): | |
| conn = get_conn() | |
| rows = conn.execute("SELECT id, username, role, active, created_at FROM accounts ORDER BY id").fetchall() | |
| conn.close() | |
| return [dict(r) for r in rows] | |
| def create_account(username: str, password: str, role: str = "user", active: bool = True): | |
| conn = get_conn() | |
| try: | |
| conn.execute( | |
| "INSERT INTO accounts (username, password_hash, role, active) VALUES (?, ?, ?, ?)", | |
| (username, hash_password(password), role, 1 if active else 0), | |
| ) | |
| conn.commit() | |
| return True, None | |
| except sqlite3.IntegrityError: | |
| return False, "用户名已存在" | |
| finally: | |
| conn.close() | |
| def update_account(account_id: int, username: str = None, password: str = None, role: str = None, active: bool = None): | |
| conn = get_conn() | |
| fields = [] | |
| values = [] | |
| if username: | |
| fields.append("username=?") | |
| values.append(username) | |
| if password: | |
| fields.append("password_hash=?") | |
| values.append(hash_password(password)) | |
| if role: | |
| fields.append("role=?") | |
| values.append(role) | |
| if active is not None: | |
| fields.append("active=?") | |
| values.append(1 if active else 0) | |
| if not fields: | |
| conn.close() | |
| return False | |
| values.append(account_id) | |
| conn.execute(f"UPDATE accounts SET {', '.join(fields)} WHERE id=?", values) | |
| conn.commit() | |
| conn.close() | |
| return True | |
| def delete_account(account_id: int): | |
| conn = get_conn() | |
| conn.execute("DELETE FROM accounts WHERE id=?", (account_id,)) | |
| conn.commit() | |
| conn.close() | |
| def get_account_by_username(username: str): | |
| conn = get_conn() | |
| row = conn.execute("SELECT * FROM accounts WHERE username=?", (username,)).fetchone() | |
| conn.close() | |
| return dict(row) if row else None | |
| def validate_login(username: str, password: str): | |
| account = get_account_by_username(username) | |
| if not account: | |
| return None | |
| if not account.get("active", 1): | |
| return None | |
| if verify_password(password, account["password_hash"]): | |
| return account | |
| return None | |
| # ─── Announcement CRUD ─── | |
| def list_announcements(): | |
| conn = get_conn() | |
| rows = conn.execute("SELECT * FROM announcements ORDER BY created_at DESC").fetchall() | |
| conn.close() | |
| return [dict(r) for r in rows] | |
| def list_active_announcements(): | |
| conn = get_conn() | |
| rows = conn.execute( | |
| "SELECT * FROM announcements WHERE active=1 ORDER BY created_at DESC" | |
| ).fetchall() | |
| conn.close() | |
| return [dict(r) for r in rows] | |
| def save_announcement(id=None, kind="公告", title="", content="", active=True): | |
| conn = get_conn() | |
| now = datetime.now().isoformat() | |
| if id: | |
| conn.execute( | |
| "UPDATE announcements SET kind=?, title=?, content=?, active=?, updated_at=? WHERE id=?", | |
| (kind, title, content, 1 if active else 0, now, id), | |
| ) | |
| else: | |
| conn.execute( | |
| "INSERT INTO announcements (kind, title, content, active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)", | |
| (kind, title, content, 1 if active else 0, now, now), | |
| ) | |
| id = conn.execute("SELECT last_insert_rowid()").fetchone()[0] | |
| conn.commit() | |
| row = conn.execute("SELECT * FROM announcements WHERE id=?", (id,)).fetchone() | |
| conn.close() | |
| return dict(row) | |
| def delete_announcement(id: int): | |
| conn = get_conn() | |
| conn.execute("DELETE FROM announcements WHERE id=?", (id,)) | |
| conn.commit() | |
| conn.close() | |
| def toggle_announcement(id: int): | |
| conn = get_conn() | |
| conn.execute( | |
| "UPDATE announcements SET active = CASE WHEN active=1 THEN 0 ELSE 1 END, updated_at=? WHERE id=?", | |
| (datetime.now().isoformat(), id), | |
| ) | |
| conn.commit() | |
| conn.close() | |
| # ─── Feedback CRUD ─── | |
| def init_feedback_table(): | |
| conn = get_conn() | |
| conn.execute(""" | |
| CREATE TABLE IF NOT EXISTS feedback ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| username TEXT NOT NULL DEFAULT '', | |
| question TEXT DEFAULT '', | |
| answer TEXT DEFAULT '', | |
| issue_type TEXT NOT NULL DEFAULT 'other', | |
| description TEXT NOT NULL, | |
| contact TEXT DEFAULT '', | |
| status TEXT NOT NULL DEFAULT 'pending', | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| # Migration: add columns if missing | |
| for col in ["question", "answer"]: | |
| try: | |
| conn.execute(f"ALTER TABLE feedback ADD COLUMN {col} TEXT DEFAULT ''") | |
| except sqlite3.OperationalError: | |
| pass | |
| conn.commit() | |
| conn.close() | |
| def submit_feedback(username: str, question: str, answer: str, issue_type: str, description: str, contact: str = ""): | |
| conn = get_conn() | |
| conn.execute( | |
| "INSERT INTO feedback (username, question, answer, issue_type, description, contact) VALUES (?, ?, ?, ?, ?, ?)", | |
| (username, question, answer, issue_type, description, contact), | |
| ) | |
| conn.commit() | |
| conn.close() | |
| def list_feedback(status: str = None): | |
| conn = get_conn() | |
| if status: | |
| rows = conn.execute( | |
| "SELECT * FROM feedback WHERE status=? ORDER BY created_at DESC", (status,) | |
| ).fetchall() | |
| else: | |
| rows = conn.execute("SELECT * FROM feedback ORDER BY created_at DESC").fetchall() | |
| conn.close() | |
| return [dict(r) for r in rows] | |
| def resolve_feedback(feedback_id: int): | |
| conn = get_conn() | |
| conn.execute("UPDATE feedback SET status='resolved' WHERE id=?", (feedback_id,)) | |
| conn.commit() | |
| conn.close() | |
| def delete_feedback(feedback_id: int): | |
| conn = get_conn() | |
| conn.execute("DELETE FROM feedback WHERE id=?", (feedback_id,)) | |
| conn.commit() | |
| conn.close() | |
| # Init on import | |
| init_db() | |
| init_feedback_table() | |
| seed_admin() | |
| seed_user() | |