Add admin user management

This commit is contained in:
2026-04-03 12:23:44 +00:00
parent 3d37186fa7
commit 5168e52e4b
18 changed files with 989 additions and 19 deletions
+132 -1
View File
@@ -12,7 +12,17 @@ from typing import Any
import psycopg
from psycopg import sql
from app.domain.models import LedgerEntry, Portfolio, StrategySet
from app.domain.models import LedgerEntry, Portfolio, StrategySet, User
_SELECT_USER = """
SELECT
id,
username,
email,
created_at,
updated_at
FROM users
"""
_SELECT_PORTFOLIO = """
SELECT
@@ -78,6 +88,17 @@ class PostgresPortfolioRepository:
def ensure_schema(self) -> None:
conn = self._connect()
with conn.cursor() as cur:
cur.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS strategy_sets (
@@ -148,6 +169,19 @@ class PostgresPortfolioRepository:
"""
)
@staticmethod
def _row_to_user(row: Any) -> User:
if row is None:
raise ValueError("사용자를 찾을 수 없습니다")
return User(
id=row[0],
username=row[1],
email=row[2],
created_at=row[3] if len(row) > 3 else None,
updated_at=row[4] if len(row) > 4 else None,
)
@staticmethod
def _row_to_portfolio(row: Any) -> Portfolio:
if row is None:
@@ -195,6 +229,103 @@ class PostgresPortfolioRepository:
note=row[12] or "",
)
def _ensure_user_uniqueness(
self,
cur: psycopg.Cursor,
*,
username: str | None = None,
email: str | None = None,
exclude_user_id: str | None = None,
) -> None:
if username is not None:
if exclude_user_id is None:
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
else:
cur.execute("SELECT 1 FROM users WHERE username = %s AND id <> %s", (username, exclude_user_id))
if cur.fetchone() is not None:
raise ValueError(f"이미 존재하는 username입니다: {username}")
if email is not None:
if exclude_user_id is None:
cur.execute("SELECT 1 FROM users WHERE email = %s", (email,))
else:
cur.execute("SELECT 1 FROM users WHERE email = %s AND id <> %s", (email, exclude_user_id))
if cur.fetchone() is not None:
raise ValueError(f"이미 존재하는 email입니다: {email}")
def get_user(self, user_id: str) -> User:
self.ensure_schema()
with self._connect().cursor() as cur:
cur.execute(_SELECT_USER + "WHERE id = %s", (user_id,))
row = cur.fetchone()
return self._row_to_user(row)
def list_users(self) -> list[User]:
self.ensure_schema()
with self._connect().cursor() as cur:
cur.execute(_SELECT_USER + "ORDER BY created_at DESC, username ASC")
rows = cur.fetchall()
return [self._row_to_user(row) for row in rows]
def create_user(self, username: str, *, email: str | None = None) -> User:
self.ensure_schema()
with self._connect().cursor() as cur:
self._ensure_user_uniqueness(cur, username=username, email=email)
user_id = str(uuid.uuid4())
cur.execute(
"""
INSERT INTO users (id, username, email)
VALUES (%s, %s, %s)
RETURNING id, username, email, created_at, updated_at
""",
(user_id, username, email),
)
row = cur.fetchone()
return self._row_to_user(row)
def update_user(self, user_id: str, *, username: str | None = None, email: str | None = None) -> User:
self.ensure_schema()
assignments: list[str] = []
params: list[object] = []
with self._connect().cursor() as cur:
cur.execute(_SELECT_USER + "WHERE id = %s", (user_id,))
existing_row = cur.fetchone()
if existing_row is None:
raise ValueError("사용자를 찾을 수 없습니다")
self._ensure_user_uniqueness(cur, username=username, email=email, exclude_user_id=user_id)
if username is not None:
assignments.append("username = %s")
params.append(username)
if email is not None:
assignments.append("email = %s")
params.append(email)
if not assignments:
return self._row_to_user(existing_row)
assignments.append("updated_at = NOW()")
cur.execute(
f"""
UPDATE users
SET {', '.join(assignments)}
WHERE id = %s
RETURNING id, username, email, created_at, updated_at
""",
(*params, user_id),
)
row = cur.fetchone()
return self._row_to_user(row)
def delete_user(self, user_id: str) -> None:
self.ensure_schema()
with self._connect().cursor() as cur:
cur.execute("SELECT 1 FROM users WHERE id = %s", (user_id,))
if cur.fetchone() is None:
raise ValueError("사용자를 찾을 수 없습니다")
cur.execute("DELETE FROM users WHERE id = %s", (user_id,))
def get(self, portfolio_id: str) -> Portfolio:
self.ensure_schema()
with self._connect().cursor() as cur: