feat: админка — раздел «Файлы» с просмотром и скачиванием файлов любого пользователя

Бэкенд:
- GET /api/admin/files?username=X — плоский список файлов всех табов
  пользователя (tab_id, filename, size, mtime).
- GET /api/admin/file_download?username=X&tab_id=Y&filename=Z —
  скачивание через FileResponse. Имена с спецсимволами
  («!Реестр СМ..xlsm») передаются query-параметрами вместо path —
  не страдает от URL-escaping. Защита от path traversal через
  Path(x).name + resolve().relative_to(DATA_DIR).

UI:
- Раздел «Файлы» в /admin (новый пункт сайдбара).
- Селект пользователей наполняется из существующего /api/admin/users.
- Кнопка «Скачать» делает fetch с Authorization-заголовком и триггерит
  download через blob — стандартному <a href> JWT не передать.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-05-06 17:34:05 +10:00
co-authored by Claude Opus 4.7
parent b2ff44cbef
commit 228e0dfd6e
2 changed files with 124 additions and 0 deletions
+57
View File
@@ -785,6 +785,63 @@ async def admin_verify_endpoint(request: Request):
return {"ok": True}
@app.get("/api/admin/files")
async def admin_list_files_endpoint(request: Request):
"""All files uploaded by a specific user (across every tab)."""
_require_admin(request)
target_user = request.query_params.get("username", "").strip()
if not target_user:
raise HTTPException(400, "username query param required")
safe_user = Path(target_user).name
if safe_user != target_user or not safe_user:
raise HTTPException(400, "Invalid username")
user_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / safe_user
files = []
if user_dir.exists() and user_dir.is_dir():
for tab_dir in sorted(user_dir.iterdir()):
if not tab_dir.is_dir() or tab_dir.name.startswith("."):
continue
for f in sorted(tab_dir.iterdir()):
if f.is_file() and not f.name.startswith("."):
st = f.stat()
files.append({
"tab_id": tab_dir.name,
"filename": f.name,
"size": st.st_size,
"mtime": st.st_mtime,
})
return {"username": safe_user, "count": len(files), "files": files}
@app.get("/api/admin/file_download")
async def admin_download_file_endpoint(request: Request):
"""Download any user's uploaded file (admin only).
Path components passed as query params to avoid URL-escaping pain
with names like `!Реестр СМ..xlsm` and tab_ids containing slashes.
"""
_require_admin(request)
target_user = request.query_params.get("username", "").strip()
tab_id = request.query_params.get("tab_id", "").strip()
filename = request.query_params.get("filename", "").strip()
if not (target_user and tab_id and filename):
raise HTTPException(400, "username, tab_id, filename required")
safe_user = Path(target_user).name
safe_tab = Path(tab_id).name
safe_name = Path(filename).name
if not (safe_user and safe_tab and safe_name):
raise HTTPException(400, "Invalid path component")
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")).resolve()
fpath = (data_dir / safe_user / safe_tab / safe_name).resolve()
try:
fpath.relative_to(data_dir)
except ValueError:
raise HTTPException(400, "Path traversal denied")
if not fpath.exists() or not fpath.is_file():
raise HTTPException(404, "File not found")
return FileResponse(fpath, filename=safe_name)
@app.get("/admin", response_class=HTMLResponse)
async def admin_page():
# Auth check is done client-side (JS) + all /api/admin/* endpoints require admin
+67
View File
@@ -46,6 +46,7 @@ a { color: var(--accent); text-decoration: none; }
<a href="#invites" onclick="showPage('invites')">Приглашения</a>
<a href="#sessions" onclick="showPage('sessions')">Сессии</a>
<a href="#audit" onclick="showPage('audit')">Журнал</a>
<a href="#files" onclick="showPage('files')">Файлы</a>
<a href="/" class="back">← Вернуться в чат</a>
</nav>
@@ -102,6 +103,21 @@ a { color: var(--accent); text-decoration: none; }
<button class="btn" id="audit-more" onclick="loadAuditMore()" style="margin-top:.5rem;display:none">Ещё</button>
</div>
<!-- Files -->
<div class="page" id="page-files">
<h2>Файлы пользователей</h2>
<div style="display:flex;gap:.5rem;margin-bottom:1rem;align-items:center;flex-wrap:wrap">
<select id="files-user" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;font-size:.85rem;min-width:240px">
<option value="">— выберите пользователя —</option>
</select>
<button class="btn" onclick="loadFiles()" style="padding:4px 10px;font-size:.8rem">Показать файлы</button>
<span id="files-count" style="font-size:.8rem;color:var(--text-muted, #666)"></span>
</div>
<table id="files">
<tr><th>Tab&nbsp;ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>
</table>
</div>
</div>
<script>
@@ -168,6 +184,8 @@ function loadUsers() {
fetch('/api/admin/users', {headers: H}).then(r=>r.json()).then(users => {
const t = document.getElementById('users');
t.innerHTML = '<tr><th>Email</th><th>Роль</th><th>Статус</th><th>Создан</th><th>Действия</th></tr>';
const fSel = document.getElementById('files-user');
if (fSel) fSel.innerHTML = '<option value="">— выберите пользователя —</option>';
for (const u of users) {
const d = new Date(u.created_at < 1e12 ? u.created_at*1000 : u.created_at);
const tr = document.createElement('tr');
@@ -182,11 +200,60 @@ function loadUsers() {
actions += btn('Удалить', "userAction('delete','"+u.email+"')");
tr.innerHTML = '<td>'+u.email+'</td><td>'+u.role+'</td><td>'+status+'</td><td class="time">'+ts+'</td><td>'+actions+'</td>';
t.appendChild(tr);
if (fSel) {
const opt = document.createElement('option');
opt.value = u.email; opt.textContent = u.email;
fSel.appendChild(opt);
}
}
}).catch(()=>{});
}
loadUsers();
// === Files (admin) ===
function fmtSize(n){
if (n < 1024) return n+' B';
if (n < 1024*1024) return (n/1024).toFixed(1)+' KB';
return (n/1024/1024).toFixed(1)+' MB';
}
async function loadFiles() {
const u = document.getElementById('files-user').value;
const tbl = document.getElementById('files');
const cnt = document.getElementById('files-count');
tbl.innerHTML = '<tr><th>Tab&nbsp;ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>';
cnt.textContent = '';
if (!u) return;
cnt.textContent = 'Загрузка…';
const r = await fetch('/api/admin/files?username=' + encodeURIComponent(u), {headers: H});
if (!r.ok) { cnt.textContent = 'Ошибка: ' + r.status; return; }
const d = await r.json();
cnt.textContent = 'Файлов: ' + d.count;
for (const f of d.files) {
const ts = new Date(f.mtime * 1000).toLocaleString('ru-RU', {day:'2-digit', month:'2-digit', year:'2-digit', hour:'2-digit', minute:'2-digit'});
const tr = document.createElement('tr');
const dlUrl = '/api/admin/file_download?username=' + encodeURIComponent(u)
+ '&tab_id=' + encodeURIComponent(f.tab_id)
+ '&filename=' + encodeURIComponent(f.filename);
tr.innerHTML = '<td style="font-family:monospace;font-size:.8rem">' + f.tab_id + '</td>'
+ '<td>' + f.filename.replace(/</g,'&lt;') + '</td>'
+ '<td>' + fmtSize(f.size) + '</td>'
+ '<td class="time">' + ts + '</td>'
+ '<td><button class="btn-sm" onclick="adminDownload(\'' + dlUrl.replace(/'/g, "\\'") + '\',\'' + f.filename.replace(/'/g, "\\'") + '\')">Скачать</button></td>';
tbl.appendChild(tr);
}
}
async function adminDownload(url, filename) {
// fetch with auth header, then trigger browser download
const r = await fetch(url, {headers: H});
if (!r.ok) { alert('Ошибка скачивания: ' + r.status); return; }
const blob = await r.blob();
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
// === Invites ===
async function createInvite() {
const r = await fetch('/api/admin/invite', {method:'POST', headers: H});