feat: add activation-code auth
Deploy Speaking Practice / deploy (push) Successful in 24s

This commit is contained in:
TTlaji committed 2026-06-05 16:56:30 +08:00
1 parent 8f3fd04618
commit 2d3ff21222
17 files changed
+1566 -136

No files matched your search

+232
View File
@@ -83,6 +83,31 @@ def initialize_database() -> None:
}
if "cover_url" not in video_columns:
connection.execute("ALTER TABLE videos ADD COLUMN cover_url TEXT")
user_columns = {
row["name"]
for row in connection.execute("PRAGMA table_info(users)").fetchall()
}
if "is_active" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1")
if "last_login_at" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT")
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS activation_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL UNIQUE,
created_by TEXT NOT NULL,
used_by_user_id INTEGER,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
used_at TEXT,
status TEXT NOT NULL DEFAULT 'unused',
FOREIGN KEY (used_by_user_id) REFERENCES users (id) ON DELETE SET NULL
);
CREATE INDEX IF NOT EXISTS idx_activation_codes_status
ON activation_codes (status);
"""
)
connection.execute(
"""
DELETE FROM subtitles
@@ -101,6 +126,213 @@ def initialize_database() -> None:
)
def row_to_user(row: sqlite3.Row) -> dict[str, object]:
return {
"id": row["id"],
"username": repair_mojibake_text(row["email"]),
"displayName": repair_mojibake_text(row["display_name"] or row["email"]),
"role": row["role"],
"isActive": bool(row["is_active"]),
"createdAt": row["created_at"],
"updatedAt": row["updated_at"],
"lastLoginAt": row["last_login_at"] or "",
}
def row_to_activation_code(row: sqlite3.Row) -> dict[str, object]:
return {
"id": row["id"],
"code": row["code"],
"createdBy": row["created_by"],
"status": row["status"],
"createdAt": row["created_at"],
"usedAt": row["used_at"] or "",
"usedByUserId": row["used_by_user_id"],
"usedByUsername": repair_mojibake_text(row["used_by_username"] or ""),
}
def get_user_by_username(username: str) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM users
WHERE email = ?
""",
(repair_mojibake_text(username),),
).fetchone()
return row_to_user(row) if row else None
def get_user_auth_record(username: str) -> sqlite3.Row | None:
with get_connection() as connection:
return connection.execute(
"""
SELECT *
FROM users
WHERE email = ?
""",
(repair_mojibake_text(username),),
).fetchone()
def get_user_by_id(user_id: int) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM users
WHERE id = ?
""",
(user_id,),
).fetchone()
return row_to_user(row) if row else None
def list_users() -> list[dict[str, object]]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT *
FROM users
ORDER BY created_at DESC, id DESC
"""
).fetchall()
return [row_to_user(row) for row in rows]
def update_user_active(user_id: int, is_active: bool) -> dict[str, object] | None:
with get_connection() as connection:
cursor = connection.execute(
"""
UPDATE users
SET is_active = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
AND role != 'admin'
""",
(1 if is_active else 0, user_id),
)
if cursor.rowcount == 0:
return None
return get_user_by_id(user_id)
def mark_user_login(user_id: int) -> None:
with get_connection() as connection:
connection.execute(
"""
UPDATE users
SET last_login_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(user_id,),
)
def register_user_with_activation(*, username: str, password_hash: str, activation_code: str) -> dict[str, object]:
clean_username = repair_mojibake_text(username)
clean_code = activation_code.strip().upper()
with get_connection() as connection:
code_row = connection.execute(
"""
SELECT *
FROM activation_codes
WHERE code = ?
AND status = 'unused'
""",
(clean_code,),
).fetchone()
if code_row is None:
raise ValueError("activation_code_unavailable")
try:
cursor = connection.execute(
"""
INSERT INTO users (
email, password_hash, display_name, role, is_active
)
VALUES (?, ?, ?, 'user', 1)
""",
(clean_username, password_hash, clean_username),
)
except sqlite3.IntegrityError as exc:
raise ValueError("username_exists") from exc
user_id = int(cursor.lastrowid)
connection.execute(
"""
UPDATE activation_codes
SET status = 'used',
used_by_user_id = ?,
used_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(user_id, code_row["id"]),
)
user = get_user_by_id(user_id)
if user is None:
raise RuntimeError("Registered user could not be loaded")
return user
def create_activation_codes(codes: list[str], created_by: str) -> list[dict[str, object]]:
created_ids: list[int] = []
with get_connection() as connection:
for code in codes:
cursor = connection.execute(
"""
INSERT INTO activation_codes (code, created_by)
VALUES (?, ?)
""",
(code, created_by),
)
created_ids.append(int(cursor.lastrowid))
with get_connection() as connection:
placeholders = ",".join("?" for _ in created_ids)
rows = connection.execute(
f"""
SELECT activation_codes.*, users.email AS used_by_username
FROM activation_codes
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
WHERE activation_codes.id IN ({placeholders})
ORDER BY activation_codes.id DESC
""",
created_ids,
).fetchall()
return [row_to_activation_code(row) for row in rows]
def list_activation_codes() -> list[dict[str, object]]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT activation_codes.*, users.email AS used_by_username
FROM activation_codes
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
ORDER BY activation_codes.created_at DESC, activation_codes.id DESC
"""
).fetchall()
return [row_to_activation_code(row) for row in rows]
def delete_unused_activation_code(code_id: int) -> bool:
with get_connection() as connection:
cursor = connection.execute(
"""
DELETE FROM activation_codes
WHERE id = ?
AND status = 'unused'
""",
(code_id,),
)
return cursor.rowcount > 0
def repair_mojibake_text(value: str | None) -> str:
if not value:
return ""