"""홈페이지 게시판. 게시판 종류(이름·설명·순서·읽기/쓰기/댓글 권한·사용 여부)는 boards 표에 두고 관리자 페이지에서 만들고 고친다. 글과 댓글은 지우지 않고 상태(open 보임 · hidden 운영진이 숨김 · deleted 지움)만 바꿔 되돌릴 수 있게 한다. 글자 수와 하루 쓰기 한도 및 쪽당 글 수는 홈페이지 설정(site_admin.SITE_FIELDS의 게시판 묶음)에서 정한다. 본문은 글자로만 보여 주므로 HTML은 해석되지 않는다. 회원 이름은 쓸 때가 아니라 보여 줄 때 찾아서 이름을 바꾸면 따라간다. """ import re import time from pathlib import Path from fastapi import HTTPException, Request from fastapi.responses import FileResponse import site_admin from korean import josa READ_LEVELS = {"all": "누구나", "member": "회원만"} WRITE_LEVELS = {"member": "회원", "admin": "관리자만"} COMMENT_LEVELS = {"member": "회원", "admin": "관리자만", "off": "댓글 없음"} POST_STATES = {"open": "보임", "hidden": "숨김", "deleted": "지움"} DEFAULT_BOARDS = [ ("notice", "공지사항", "운영 소식과 업데이트 안내", 10, "all", "admin", "member"), ("free", "자유게시판", "근무 이야기와 사용 후기를 나눠요", 20, "all", "member", "member"), ("qna", "질문·건의", "사용하다 막힌 점이나 바라는 기능을 남겨 주세요", 30, "all", "member", "member"), ] TITLE_MAX = 80 def init_schema(conn): conn.executescript(""" CREATE TABLE IF NOT EXISTS boards(id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', sort INTEGER NOT NULL DEFAULT 0, read_level TEXT NOT NULL DEFAULT 'all', write_level TEXT NOT NULL DEFAULT 'member', comment_level TEXT NOT NULL DEFAULT 'member', active INTEGER NOT NULL DEFAULT 1, created INTEGER NOT NULL, updated INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS board_posts(id INTEGER PRIMARY KEY, board TEXT NOT NULL, author TEXT, title TEXT NOT NULL, body TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL, pinned INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL DEFAULT 'open', comments INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS board_posts_list ON board_posts(board, state, pinned, created); CREATE INDEX IF NOT EXISTS board_posts_author ON board_posts(author, created); CREATE TABLE IF NOT EXISTS board_comments(id INTEGER PRIMARY KEY, post INTEGER NOT NULL, author TEXT, body TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'open'); CREATE INDEX IF NOT EXISTS board_comments_post ON board_comments(post, created); CREATE INDEX IF NOT EXISTS board_comments_author ON board_comments(author, created); """) if conn.execute("SELECT COUNT(*) FROM boards").fetchone()[0] == 0: now = int(time.time()) conn.executemany("INSERT INTO boards(id,name,description,sort,read_level,write_level,comment_level,active,created,updated) VALUES(?,?,?,?,?,?,?,1,?,?)", [row + (now, now) for row in DEFAULT_BOARDS]) def clean_text(value, label, limit, multiline): """줄바꿈은 본문에서만 받는다. 탭은 빈칸으로 바꾸고 다른 제어 문자는 받지 않는다.""" if not isinstance(value, str): raise HTTPException(400, josa(label, "을", "를") + " 확인해 주세요.") value = value.replace("\r\n", "\n").replace("\r", "\n").replace("\t", " ") value = value.strip() if multiline else " ".join(value.split()) if multiline: value = re.sub(r"\n{4,}", "\n\n\n", value) if not value: raise HTTPException(400, josa(label, "을", "를") + " 입력해 주세요.") if len(value) > limit: raise HTTPException(400, josa(label, "은", "는") + " " + format(limit, ",") + "자까지 쓸 수 있습니다.") if any((ord(ch) < 32 and ch != "\n") or 0x7f <= ord(ch) < 0xa0 or 0xd800 <= ord(ch) < 0xe000 for ch in value): raise HTTPException(400, label + "에 쓸 수 없는 글자가 있습니다.") return value def setup(app, prefix, root, db, identity, payload, throttle, administrator): web = Path(root) / "web" with db() as conn: init_schema(conn) site_admin.LOG_AREAS["board"] = "게시판" site_admin.ACTION_NAMES.update({ "board-save": "게시판 설정 저장", "board-create": "게시판 만들기", "post-pin": "글 고정", "post-unpin": "글 고정 해제", "post-hide": "글 숨김", "post-show": "글 다시 보이기", "post-delete": "글 지움", "post-restore": "글 되살림", "comment-hide": "댓글 숨김", "comment-show": "댓글 다시 보이기", "comment-delete": "댓글 지움", "comment-restore": "댓글 되살림", }) def settings(conn): values, _ = site_admin.read_settings(conn) return values def viewer(request): """로그인하지 않아도 읽을 수 있는 화면에서 쓴다. 로그인 정보가 없거나 만료됐으면 손님으로 본다.""" try: return identity(request, allow_password_change=True) except HTTPException as error: if error.status_code in (401, 403): return None raise def writer(request): client = identity(request) if client.get("member") is None: raise HTTPException(403, "회원 로그인 후 쓸 수 있습니다.") return client def is_admin(client): return bool(client) and client.get("role") == "admin" def board_row(conn, board_id, client, need_active=True): row = conn.execute("SELECT * FROM boards WHERE id=?", (board_id,)).fetchone() if row is None or (need_active and not row["active"] and not is_admin(client)): raise HTTPException(404, "게시판을 찾을 수 없습니다.") if row["read_level"] == "member" and not client: raise HTTPException(401, "회원만 볼 수 있는 게시판입니다. 로그인해 주세요.") return row def gate(conn, client): if not settings(conn)["boardOn"] and not is_admin(client): raise HTTPException(403, "게시판을 잠시 닫았습니다.") def names(conn, ids): ids = [value for value in set(ids) if value] if not ids: return {} marks = ",".join("?" * len(ids)) return {row[0]: {"name": row[1], "admin": row[2] == "admin"} for row in conn.execute("SELECT id,display_name,role FROM members WHERE id IN (" + marks + ")", ids)} def author_info(people, author): person = people.get(author) return {"authorName": person["name"] if person else "(탈퇴한 회원)", "authorAdmin": bool(person and person["admin"])} def board_info(row): return {"id": row["id"], "name": row["name"], "description": row["description"], "readLevel": row["read_level"], "writeLevel": row["write_level"], "commentLevel": row["comment_level"], "active": bool(row["active"]), "sort": row["sort"]} def can_write(board, client): return bool(client) and (board["write_level"] == "member" or is_admin(client)) def can_comment(board, client): return bool(client) and board["comment_level"] != "off" and (board["comment_level"] == "member" or is_admin(client)) def log(conn, actor, target, action, detail=""): conn.execute("INSERT INTO admin_log(actor,area,target,action,detail,created) VALUES(?,?,?,?,?,?)", (actor, "board", str(target), action, detail[:500], int(time.time()))) def daily_limit(conn, table, author, limit, label): used = conn.execute("SELECT COUNT(*) FROM " + table + " WHERE author=? AND created>?", (author, int(time.time()) - 86400)).fetchone()[0] if used >= limit: raise HTTPException(429, "하루에 쓸 수 있는 " + label + " 수(" + str(limit) + "개)를 넘었습니다. 내일 다시 써 주세요.") # ---------------------------------------------------------------- 화면 @app.get(prefix + "/board") async def board_page(): return FileResponse(web / "board.html", media_type="text/html") @app.get(prefix + "/guide") async def guide_page(): return FileResponse(web / "guide.html", media_type="text/html") # ---------------------------------------------------------------- 읽기 @app.get(prefix + "/api/boards") async def board_list(request: Request): client = viewer(request) with db() as conn: gate(conn, client) rows = conn.execute("""SELECT b.*,(SELECT COUNT(*) FROM board_posts p WHERE p.board=b.id AND p.state='open') AS posts, (SELECT MAX(created) FROM board_posts p WHERE p.board=b.id AND p.state='open') AS latest FROM boards b WHERE b.active=1 ORDER BY b.sort,b.created,b.id""").fetchall() values = settings(conn) boards = [] for row in rows: info = board_info(row) info.update(posts=row["posts"], latest=row["latest"], canWrite=can_write(row, client), locked=row["read_level"] == "member" and not client) boards.append(info) me = {"id": client["member"], "name": client["display_name"], "admin": is_admin(client)} if client else None return {"boards": boards, "me": me, "limits": {"title": TITLE_MAX, "post": values["boardPostMax"], "comment": values["boardCommentMax"]}} @app.get(prefix + "/api/boards/{board_id}/posts") async def post_list(request: Request, board_id: str, q: str = "", page: int = 1): client = viewer(request) if len(q) > 40 or page < 1 or page > 500: raise HTTPException(400, "검색 조건을 확인해 주세요.") with db() as conn: gate(conn, client) board = board_row(conn, board_id, client) size = settings(conn)["boardPageSize"] where = "board=? AND state='open' AND (instr(title,?)>0 OR instr(body,?)>0)" args = [board_id, q, q] total = conn.execute("SELECT COUNT(*) FROM board_posts WHERE " + where, args).fetchone()[0] rows = [dict(row) for row in conn.execute("SELECT id,author,title,created,updated,pinned,comments FROM board_posts WHERE " + where + " ORDER BY pinned DESC,created DESC,id DESC LIMIT ? OFFSET ?", args + [size, (page - 1) * size])] people = names(conn, [row["author"] for row in rows]) for row in rows: row.update(author_info(people, row.pop("author"))) row["pinned"] = bool(row["pinned"]) return {"board": {**board_info(board), "canWrite": can_write(board, client)}, "posts": rows, "total": total, "page": page, "pageSize": size} @app.get(prefix + "/api/posts/{post_id}") async def post_detail(request: Request, post_id: int): client = viewer(request) with db() as conn: gate(conn, client) post = conn.execute("SELECT * FROM board_posts WHERE id=?", (post_id,)).fetchone() if post is None or (post["state"] != "open" and not is_admin(client)): raise HTTPException(404, "글을 찾을 수 없습니다. 지워졌거나 운영진이 숨긴 글입니다.") board = board_row(conn, post["board"], client) comments = [dict(row) for row in conn.execute( "SELECT id,author,body,created,updated,state FROM board_comments WHERE post=? AND (state='open' OR ?) ORDER BY created,id", (post_id, 1 if is_admin(client) else 0))] people = names(conn, [post["author"]] + [row["author"] for row in comments]) mine = bool(client) and client["member"] == post["author"] result = {key: post[key] for key in ("id", "title", "body", "created", "updated", "state")} result.update(author_info(people, post["author"]), pinned=bool(post["pinned"]), mine=mine, canEdit=mine or is_admin(client)) for row in comments: own = bool(client) and client["member"] == row["author"] row.update(author_info(people, row.pop("author")), mine=own, canEdit=own or is_admin(client)) return {"board": {**board_info(board), "canWrite": can_write(board, client), "canComment": can_comment(board, client)}, "post": result, "comments": comments} # ---------------------------------------------------------------- 쓰기 @app.post(prefix + "/api/boards/{board_id}/posts") async def post_create(request: Request, board_id: str): client = writer(request) throttle(request, "board-write", 20, 60) data = await payload(request) with db() as conn: conn.execute("BEGIN IMMEDIATE") gate(conn, client) board = board_row(conn, board_id, client) if not board["active"] or not can_write(board, client): raise HTTPException(403, "이 게시판에는 관리자만 글을 쓸 수 있습니다." if board["write_level"] == "admin" else "이 게시판은 지금 글을 받지 않습니다.") values = settings(conn) title = clean_text(data.get("title"), "제목", TITLE_MAX, False) body = clean_text(data.get("body"), "본문", values["boardPostMax"], True) if not is_admin(client): daily_limit(conn, "board_posts", client["member"], values["boardDailyPosts"], "글") now = int(time.time()) post_id = conn.execute("INSERT INTO board_posts(board,author,title,body,created,updated) VALUES(?,?,?,?,?,?)", (board_id, client["member"], title, body, now, now)).lastrowid return {"id": post_id} @app.post(prefix + "/api/posts/{post_id}") async def post_change(request: Request, post_id: int): client = writer(request) throttle(request, "board-write", 20, 60) data = await payload(request) action = data.get("action") if action not in ("edit", "delete"): raise HTTPException(400, "작업을 확인해 주세요.") with db() as conn: conn.execute("BEGIN IMMEDIATE") gate(conn, client) post = conn.execute("SELECT * FROM board_posts WHERE id=?", (post_id,)).fetchone() if post is None or post["state"] == "deleted": raise HTTPException(404, "글을 찾을 수 없습니다.") if post["author"] != client["member"] and not is_admin(client): raise HTTPException(403, "내가 쓴 글만 고치거나 지울 수 있습니다.") if post["state"] == "hidden" and not is_admin(client): raise HTTPException(403, "운영진이 숨긴 글은 고칠 수 없습니다.") if action == "edit": values = settings(conn) title = clean_text(data.get("title"), "제목", TITLE_MAX, False) body = clean_text(data.get("body"), "본문", values["boardPostMax"], True) conn.execute("UPDATE board_posts SET title=?,body=?,updated=? WHERE id=?", (title, body, int(time.time()), post_id)) else: conn.execute("UPDATE board_posts SET state='deleted',updated=? WHERE id=?", (int(time.time()), post_id)) if post["author"] != client["member"]: log(conn, client["member"], post_id, "post-delete", post["title"]) return {"done": True} @app.post(prefix + "/api/posts/{post_id}/comments") async def comment_create(request: Request, post_id: int): client = writer(request) throttle(request, "board-write", 20, 60) data = await payload(request) with db() as conn: conn.execute("BEGIN IMMEDIATE") gate(conn, client) post = conn.execute("SELECT * FROM board_posts WHERE id=? AND state='open'", (post_id,)).fetchone() if post is None: raise HTTPException(404, "글을 찾을 수 없습니다.") board = board_row(conn, post["board"], client) if not board["active"] or not can_comment(board, client): raise HTTPException(403, "이 게시판은 관리자만 댓글을 쓸 수 있습니다." if board["comment_level"] == "admin" else "이 게시판은 댓글을 받지 않습니다.") values = settings(conn) body = clean_text(data.get("body"), "댓글", values["boardCommentMax"], True) if not is_admin(client): daily_limit(conn, "board_comments", client["member"], values["boardDailyComments"], "댓글") now = int(time.time()) comment_id = conn.execute("INSERT INTO board_comments(post,author,body,created,updated) VALUES(?,?,?,?,?)", (post_id, client["member"], body, now, now)).lastrowid conn.execute("UPDATE board_posts SET comments=(SELECT COUNT(*) FROM board_comments WHERE post=? AND state='open') WHERE id=?", (post_id, post_id)) return {"id": comment_id} @app.post(prefix + "/api/comments/{comment_id}") async def comment_change(request: Request, comment_id: int): client = writer(request) throttle(request, "board-write", 20, 60) data = await payload(request) action = data.get("action") if action not in ("edit", "delete"): raise HTTPException(400, "작업을 확인해 주세요.") with db() as conn: conn.execute("BEGIN IMMEDIATE") gate(conn, client) row = conn.execute("SELECT * FROM board_comments WHERE id=?", (comment_id,)).fetchone() if row is None or row["state"] == "deleted": raise HTTPException(404, "댓글을 찾을 수 없습니다.") if row["author"] != client["member"] and not is_admin(client): raise HTTPException(403, "내가 쓴 댓글만 고치거나 지울 수 있습니다.") if row["state"] == "hidden" and not is_admin(client): raise HTTPException(403, "운영진이 숨긴 댓글은 고칠 수 없습니다.") if action == "edit": body = clean_text(data.get("body"), "댓글", settings(conn)["boardCommentMax"], True) conn.execute("UPDATE board_comments SET body=?,updated=? WHERE id=?", (body, int(time.time()), comment_id)) else: conn.execute("UPDATE board_comments SET state='deleted',updated=? WHERE id=?", (int(time.time()), comment_id)) conn.execute("UPDATE board_posts SET comments=(SELECT COUNT(*) FROM board_comments WHERE post=? AND state='open') WHERE id=?", (row["post"], row["post"])) if row["author"] != client["member"]: log(conn, client["member"], row["post"], "comment-delete", row["body"][:80]) return {"done": True} # ---------------------------------------------------------------- 관리자 @app.get(prefix + "/api/admin/boards") async def admin_boards(request: Request): administrator(request) with db() as conn: rows = conn.execute("""SELECT b.*, (SELECT COUNT(*) FROM board_posts p WHERE p.board=b.id AND p.state='open') AS open_posts, (SELECT COUNT(*) FROM board_posts p WHERE p.board=b.id AND p.state='hidden') AS hidden_posts, (SELECT COUNT(*) FROM board_posts p WHERE p.board=b.id AND p.state='deleted') AS deleted_posts FROM boards b ORDER BY b.sort,b.created,b.id""").fetchall() boards = [] for row in rows: info = board_info(row) info.update(openPosts=row["open_posts"], hiddenPosts=row["hidden_posts"], deletedPosts=row["deleted_posts"]) boards.append(info) return {"boards": boards, "levels": {"read": READ_LEVELS, "write": WRITE_LEVELS, "comment": COMMENT_LEVELS}} @app.post(prefix + "/api/admin/boards") async def admin_board_save(request: Request): actor = administrator(request) throttle(request, "board-admin", 60, 60) data = await payload(request) board_id = data.get("id") if not isinstance(board_id, str) or not re.fullmatch(r"[a-z][a-z0-9-]{1,19}", board_id): raise HTTPException(400, "게시판 주소 이름은 영어 소문자로 시작하는 2~20자(소문자·숫자·-)로 정해 주세요.") name = clean_text(data.get("name"), "게시판 이름", 20, False) description = data.get("description", "") description = "" if isinstance(description, str) and not description.strip() else clean_text(description, "게시판 설명", 100, False) sort = data.get("sort", 100) if type(sort) is not int or not 0 <= sort <= 9999: raise HTTPException(400, "순서는 0~9999 숫자로 정해 주세요.") if data.get("readLevel") not in READ_LEVELS or data.get("writeLevel") not in WRITE_LEVELS or data.get("commentLevel") not in COMMENT_LEVELS: raise HTTPException(400, "읽기·쓰기·댓글 권한을 확인해 주세요.") if type(data.get("active")) is not bool: raise HTTPException(400, "사용 여부를 확인해 주세요.") now = int(time.time()) with db() as conn: conn.execute("BEGIN IMMEDIATE") administrator(request) exists = conn.execute("SELECT 1 FROM boards WHERE id=?", (board_id,)).fetchone() if data.get("create") is True: if exists: raise HTTPException(409, "같은 주소 이름의 게시판이 이미 있습니다.") if conn.execute("SELECT COUNT(*) FROM boards").fetchone()[0] >= 30: raise HTTPException(400, "게시판은 30개까지 만들 수 있습니다.") conn.execute("INSERT INTO boards(id,name,description,sort,read_level,write_level,comment_level,active,created,updated) VALUES(?,?,?,?,?,?,?,?,?,?)", (board_id, name, description, sort, data["readLevel"], data["writeLevel"], data["commentLevel"], int(data["active"]), now, now)) log(conn, actor["member"], board_id, "board-create", name) else: if not exists: raise HTTPException(404, "게시판을 찾을 수 없습니다.") conn.execute("UPDATE boards SET name=?,description=?,sort=?,read_level=?,write_level=?,comment_level=?,active=?,updated=? WHERE id=?", (name, description, sort, data["readLevel"], data["writeLevel"], data["commentLevel"], int(data["active"]), now, board_id)) log(conn, actor["member"], board_id, "board-save", name + (" · 사용" if data["active"] else " · 쉬는 중")) return {"done": True} @app.get(prefix + "/api/admin/board-posts") async def admin_posts(request: Request, board: str = "", state: str = "all", q: str = "", page: int = 1): administrator(request) if state not in ("all", *POST_STATES) or len(q) > 40 or len(board) > 20 or page < 1 or page > 500: raise HTTPException(400, "조회 조건을 확인해 주세요.") where = ["(instr(p.title,?)>0 OR instr(p.body,?)>0)"] args = [q, q] if board: where.append("p.board=?"); args.append(board) if state != "all": where.append("p.state=?"); args.append(state) sql = " FROM board_posts p LEFT JOIN boards b ON b.id=p.board WHERE " + " AND ".join(where) with db() as conn: total = conn.execute("SELECT COUNT(*)" + sql, args).fetchone()[0] rows = [dict(row) for row in conn.execute("SELECT p.id,p.board,b.name AS board_name,p.author,p.title,p.created,p.updated,p.pinned,p.state,p.comments" + sql + " ORDER BY p.created DESC,p.id DESC LIMIT 30 OFFSET ?", args + [(page - 1) * 30])] people = names(conn, [row["author"] for row in rows]) for row in rows: row.update(author_info(people, row.pop("author"))) row["pinned"] = bool(row["pinned"]) return {"posts": rows, "total": total, "page": page, "pageSize": 30, "states": POST_STATES} @app.get(prefix + "/api/admin/board-comments") async def admin_comments(request: Request, state: str = "all", page: int = 1): administrator(request) if state not in ("all", *POST_STATES) or page < 1 or page > 500: raise HTTPException(400, "조회 조건을 확인해 주세요.") where, args = ("", []) if state == "all" else (" WHERE c.state=?", [state]) with db() as conn: total = conn.execute("SELECT COUNT(*) FROM board_comments c" + where, args).fetchone()[0] rows = [dict(row) for row in conn.execute("""SELECT c.id,c.post,p.title AS post_title,c.author,c.body,c.created,c.state FROM board_comments c LEFT JOIN board_posts p ON p.id=c.post""" + where + " ORDER BY c.created DESC,c.id DESC LIMIT 30 OFFSET ?", args + [(page - 1) * 30])] people = names(conn, [row["author"] for row in rows]) for row in rows: row.update(author_info(people, row.pop("author"))) return {"comments": rows, "total": total, "page": page, "pageSize": 30} @app.post(prefix + "/api/admin/board-post/{post_id}") async def admin_post_action(request: Request, post_id: int): actor = administrator(request) throttle(request, "board-admin", 60, 60) data = await payload(request) action = data.get("action") changes = {"pin": ("pinned", 1), "unpin": ("pinned", 0), "hide": ("state", "hidden"), "show": ("state", "open"), "delete": ("state", "deleted"), "restore": ("state", "open")} if action not in changes: raise HTTPException(400, "작업을 확인해 주세요.") column, value = changes[action] with db() as conn: conn.execute("BEGIN IMMEDIATE") administrator(request) post = conn.execute("SELECT id,title FROM board_posts WHERE id=?", (post_id,)).fetchone() if post is None: raise HTTPException(404, "글을 찾을 수 없습니다.") conn.execute("UPDATE board_posts SET " + column + "=? WHERE id=?", (value, post_id)) log(conn, actor["member"], post_id, "post-" + action, post["title"]) return {"done": True} @app.post(prefix + "/api/admin/board-comment/{comment_id}") async def admin_comment_action(request: Request, comment_id: int): actor = administrator(request) throttle(request, "board-admin", 60, 60) data = await payload(request) action = data.get("action") states = {"hide": "hidden", "show": "open", "delete": "deleted", "restore": "open"} if action not in states: raise HTTPException(400, "작업을 확인해 주세요.") with db() as conn: conn.execute("BEGIN IMMEDIATE") administrator(request) row = conn.execute("SELECT id,post,body FROM board_comments WHERE id=?", (comment_id,)).fetchone() if row is None: raise HTTPException(404, "댓글을 찾을 수 없습니다.") conn.execute("UPDATE board_comments SET state=? WHERE id=?", (states[action], comment_id)) conn.execute("UPDATE board_posts SET comments=(SELECT COUNT(*) FROM board_comments WHERE post=? AND state='open') WHERE id=?", (row["post"], row["post"])) log(conn, actor["member"], row["post"], "comment-" + action, row["body"][:80]) return {"done": True}