From 187cbeacfa817b43da568b0349f1c82a74c687aa Mon Sep 17 00:00:00 2001 From: dsyoon Date: Fri, 6 Nov 2026 11:43:28 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=B9=B4=EB=93=9C=20=EC=98=A4=EB=A5=B8?= =?UTF-8?q?=EC=AA=BD=20=EC=9C=84=20X=20=EB=B2=84=ED=8A=BC=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=A7=81=ED=81=AC=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DELETE /links/: .env 의 DELETE_TOKEN 과 X-Delete-Token 헤더가 맞을 때만 삭제 - 처음 삭제할 때 관리 키를 묻고 브라우저에 기억, 틀리면 다시 묻는다 - 정적 파일에 버전 쿼리를 붙여 캐시된 옛 화면이 남지 않게 한다 Co-Authored-By: Claude Opus 5.5 --- app.py | 29 +++++++++++++++++ static/app.js | 74 ++++++++++++++++++++++++++++++++++++++++++-- static/styles.css | 18 +++++++++++ templates/index.html | 4 +-- 4 files changed, 121 insertions(+), 4 deletions(-) diff --git a/app.py b/app.py index 538386b..fba0693 100644 --- a/app.py +++ b/app.py @@ -1,3 +1,4 @@ +import hmac import ipaddress import os import re @@ -39,6 +40,8 @@ PLACEHOLDER_DATA_URI = ( DEFAULT_PAGE_SIZE = int(os.getenv("DEFAULT_PAGE_SIZE", "30")) MAX_PAGE_SIZE = int(os.getenv("MAX_PAGE_SIZE", "60")) DEFAULT_SCHEMA = os.getenv("DB_SCHEMA", "public") +# 카드 삭제용 관리 키(.env). 비어 있으면 삭제 기능을 막는다. +DELETE_TOKEN = os.getenv("DELETE_TOKEN", "") def _safe_identifier(name: str) -> str: @@ -515,5 +518,31 @@ def add_link(): ) +@app.delete("/links/") +def delete_link(link_id: int): + # 로그인이 없는 공개 페이지라 관리 키(X-Delete-Token)가 맞을 때만 지운다 + if not DELETE_TOKEN: + return jsonify({"error": "삭제 기능이 설정되지 않았습니다."}), 403 + token = (request.headers.get("X-Delete-Token") or "").strip() + if not hmac.compare_digest(token.encode(), DELETE_TOKEN.encode()): + return jsonify({"error": "관리 키가 맞지 않습니다."}), 401 + + table_ref = _table_ref(os.getenv("DB_SCHEMA", DEFAULT_SCHEMA), os.getenv("TABLE", "news_link")) + try: + with get_db_connection() as conn: + with conn.cursor() as cur: + cur.execute(f"DELETE FROM {table_ref} WHERE id = %s RETURNING url", (link_id,)) + row = cur.fetchone() + conn.commit() + except Exception as exc: + return jsonify({"error": "삭제 실패", "detail": str(exc)}), 500 + if not row: + return jsonify({"error": "이미 삭제되었거나 없는 링크입니다."}), 404 + + _, ip = get_request_identity(request) + app.logger.warning("링크 삭제 id=%s url=%s ip=%s", link_id, row[0], ip) + return jsonify({"deleted": link_id}) + + if __name__ == "__main__": app.run(host="127.0.0.1", port=8021, debug=False) diff --git a/static/app.js b/static/app.js index 3d3ba8c..1e0938b 100644 --- a/static/app.js +++ b/static/app.js @@ -52,7 +52,16 @@ function appendLinks(links) { col.className = "col-12 col-md-6 col-lg-4"; const card = document.createElement("div"); - card.className = "card h-100 shadow-sm"; + card.className = "card h-100 shadow-sm position-relative"; + + const deleteBtn = document.createElement("button"); + deleteBtn.type = "button"; + deleteBtn.className = "btn-close card-delete-btn"; + deleteBtn.setAttribute("aria-label", "삭제"); + deleteBtn.title = "삭제"; + deleteBtn.addEventListener("click", () => + deleteLink(link, col, deleteBtn) + ); const image = document.createElement("img"); image.className = "card-img-top"; @@ -90,12 +99,73 @@ function appendLinks(links) { linkBtn.textContent = "원문 보기"; body.append(title, description, linkBtn); - card.append(image, body); + card.append(deleteBtn, image, body); col.appendChild(card); linkList.appendChild(col); }); } +const DELETE_TOKEN_KEY = "newsLinkDeleteToken"; + +function getStoredToken() { + try { + return localStorage.getItem(DELETE_TOKEN_KEY) || ""; + } catch { + return ""; + } +} + +function storeToken(token) { + try { + if (token) localStorage.setItem(DELETE_TOKEN_KEY, token); + else localStorage.removeItem(DELETE_TOKEN_KEY); + } catch { + /* 저장 불가(사생활 보호 모드 등)면 매번 묻는다 */ + } +} + +async function deleteLink(link, col, button) { + const label = link.title || link.url; + if (!window.confirm(`이 링크를 삭제할까요?\n\n${label}`)) return; + + let token = getStoredToken(); + for (let attempt = 0; attempt < 2; attempt += 1) { + if (!token) { + token = (window.prompt("관리 키를 입력하세요.") || "").trim(); + if (!token) return; + } + button.disabled = true; + try { + const res = await fetch(`/links/${encodeURIComponent(link.id)}`, { + method: "DELETE", + headers: { "X-Delete-Token": token }, + }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) { + storeToken(""); + token = ""; + window.alert(data.error || "관리 키가 맞지 않습니다."); + continue; + } + if (!res.ok && res.status !== 404) { + throw new Error(data.error || "삭제하지 못했습니다."); + } + storeToken(token); + col.remove(); + nextOffset = Math.max(0, nextOffset - 1); + if (!linkList.children.length && !hasMore) { + setEmptyStateVisible(true, "아직 저장된 링크가 없습니다."); + } + return; + } catch (err) { + window.alert(err.message); + return; + } finally { + button.disabled = false; + } + } +} + const PAGE_SIZE = 30; let nextOffset = 0; let hasMore = true; diff --git a/static/styles.css b/static/styles.css index f4d928b..a02f454 100644 --- a/static/styles.css +++ b/static/styles.css @@ -15,6 +15,24 @@ body { justify-content: center; } +/* 카드 오른쪽 위 삭제(X) 버튼: 이미지 위에서도 보이도록 흰 원형 배경 */ +.card-delete-btn { + position: absolute; + top: 8px; + right: 8px; + z-index: 2; + padding: 0.5rem; + background-color: rgba(255, 255, 255, 0.9); + background-size: 0.65rem; + border-radius: 50%; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25); + opacity: 0.85; +} + +.card-delete-btn:hover { + opacity: 1; +} + .card-img-top { height: 180px; object-fit: cover; diff --git a/templates/index.html b/templates/index.html index 1592d0e..9f5a271 100644 --- a/templates/index.html +++ b/templates/index.html @@ -13,7 +13,7 @@ href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon" /> - +
@@ -127,6 +127,6 @@
- +