File size: 8,413 Bytes
b0dbc6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468dd82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0dbc6a
 
468dd82
b0dbc6a
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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()