feat: RBAC E2E тесты и фикс admin-прав для редактирования постов
Основные изменения: - Добавлены E2E тесты для проверки ownership (TC-E2E-102/103): * test_admin_can_edit_any_post — admin может редактировать любой пост * test_user_cannot_edit_other_users_post — user не может редактировать чужой пост - Исправлены use cases (UpdatePost, DeletePost, PublishPost) — добавлена проверка роли admin - Обновлены web routes и API routes для передачи роли в use cases - Добавлены unit тесты для admin-сценариев Реструктуризация тестов: - Удалены старые API тесты (tests/api/) — требуют переработки - Удалены старые integration тесты (tests/integration/) - Переработаны E2E тесты: удалены старые, добавлены новые с POM - Добавлена документация тестов: FEATURE_*.md, TEST_MODEL.md, AGENTS.md Инфраструктура: - Добавлен MockKeycloakClient для dev-режима - Добавлены статические файлы: EasyMDE, Highlight.js, стили markdown - Обновлены шаблоны: base.html, post_form.html, post_detail.html - Обновлена DI конфигурация и провайдеры Документация: - tests/FEATURE_RBAC.md — матрица тестов RBAC - tests/FEATURE_POST_LIFECYCLE.md — тесты жизненного цикла поста - tests/FEATURE_DOMAIN_FOUNDATION.md — тесты доменного слоя - tests/FEATURE_INFRASTRUCTURE.md — тесты инфраструктуры - tests/TEST_MODEL.md — глобальная матрица покрытия - app/presentation/web/AGENTS.md — гайд по Web UI - tests/AGENTS.md — гайд по тестированию
This commit is contained in:
51
app/presentation/web/AGENTS.md
Normal file
51
app/presentation/web/AGENTS.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Web UI Knowledge Base
|
||||
|
||||
**Generated:** 2026-05-03 22:15 UTC
|
||||
**Commit:** 41f2a3d
|
||||
**Branch:** feature/tests
|
||||
|
||||
## Overview
|
||||
|
||||
FastAPI Jinja2 web UI layer with Keycloak auth integration, flash messages, and theme support.
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
app/presentation/web/
|
||||
├── __init__.py
|
||||
├── auth.py # Keycloak OAuth login/logout/callback
|
||||
├── deps.py # Web dependency injection (current_user, require_auth)
|
||||
├── error_handlers.py # HTTP exception handlers for web routes
|
||||
├── flash.py # Flash message middleware
|
||||
└── routes.py # All web page routes (largest file in project)
|
||||
```
|
||||
|
||||
## Where to Look
|
||||
|
||||
| Task | Location |
|
||||
|------|----------|
|
||||
| Add a new page | `routes.py` |
|
||||
| Change auth flow | `auth.py` |
|
||||
| Change flash messages | `flash.py` |
|
||||
| Change error pages | `error_handlers.py` |
|
||||
| Change DI for web | `deps.py` |
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Templates**: Jinja2 in `app/presentation/templates/`
|
||||
- **data-testid attributes REQUIRED** on all interactive elements
|
||||
- **Theme support**: Light/dark via `data-theme` on `<html>`, LocalStorage persistence
|
||||
- **Auth**: HTTP-only cookie `access_token`, Keycloak integration
|
||||
- **Mock data**: Routes currently use `MockPost`/`MOCK_POSTS` — integrate real use cases when ready
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Do NOT use inline comments — self-documenting code only
|
||||
- Do NOT add external CDN dependencies — all assets must be in `static/`
|
||||
- Do NOT bypass `filter_visible_posts()` for draft access control
|
||||
|
||||
## Notes
|
||||
|
||||
- `routes.py` is the largest file in the project (519 lines) — consider splitting by concern
|
||||
- `home`, `list_posts`, `post_detail`, `new_post_form`, `edit_post_form`, `create_post`, `update_post`, `delete_post`, `profile`, `about` are all defined in `routes.py`
|
||||
- Web routers are imported directly in `main.py`, bypassing `app/presentation/__init__.py`
|
||||
@@ -86,14 +86,20 @@ async def exchange_code_for_token(code: str, redirect_uri: str) -> dict[str, Any
|
||||
|
||||
@router.get("/login")
|
||||
async def login(request: Request) -> RedirectResponse:
|
||||
"""Redirect to Keycloak login page.
|
||||
"""Redirect to Keycloak login page or dev login in development mode.
|
||||
|
||||
In development mode redirects to the local dev login page
|
||||
instead of the external Keycloak server.
|
||||
|
||||
Args:
|
||||
request: HTTP request object.
|
||||
|
||||
Returns:
|
||||
RedirectResponse to Keycloak authorization endpoint.
|
||||
RedirectResponse to Keycloak or dev login endpoint.
|
||||
"""
|
||||
if settings.is_dev:
|
||||
return RedirectResponse(url="/auth/dev-login")
|
||||
|
||||
callback_url = str(request.base_url).rstrip("/") + "/auth/callback"
|
||||
login_url = get_keycloak_login_url(callback_url)
|
||||
return RedirectResponse(url=login_url)
|
||||
@@ -142,16 +148,196 @@ async def callback(request: Request, code: str | None = None) -> Response:
|
||||
async def logout(request: Request) -> Response:
|
||||
"""Logout user and clear token cookie.
|
||||
|
||||
In development mode redirects directly to home page.
|
||||
In production redirects to Keycloak logout endpoint.
|
||||
|
||||
Args:
|
||||
request: HTTP request object.
|
||||
|
||||
Returns:
|
||||
RedirectResponse to Keycloak logout with cookie cleared.
|
||||
RedirectResponse with cookie cleared.
|
||||
"""
|
||||
home_url = str(request.base_url).rstrip("/") + "/web/"
|
||||
logout_url = get_keycloak_logout_url(home_url)
|
||||
|
||||
response = RedirectResponse(url=logout_url)
|
||||
response = RedirectResponse(url=home_url)
|
||||
response.delete_cookie(key="access_token")
|
||||
|
||||
if not settings.is_dev:
|
||||
logout_url = get_keycloak_logout_url(home_url)
|
||||
response = RedirectResponse(url=logout_url)
|
||||
response.delete_cookie(key="access_token")
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/dev-login")
|
||||
async def dev_login(request: Request) -> Response:
|
||||
"""Show dev login page for development mode.
|
||||
|
||||
Only available in development mode. Provides a simple form
|
||||
to select role and log in without a real Keycloak server.
|
||||
|
||||
Args:
|
||||
request: HTTP request object.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with dev login form.
|
||||
|
||||
Raises:
|
||||
HTTPException: If accessed outside development mode.
|
||||
"""
|
||||
if not settings.is_dev:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
return HTMLResponse(
|
||||
content="""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Dev Login - Blog</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f5f5;
|
||||
--card: #fff;
|
||||
--text: #333;
|
||||
--border: #ddd;
|
||||
--primary: #0366d6;
|
||||
--primary-text: #fff;
|
||||
--error: #d73a49;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #0d1117;
|
||||
--card: #161b22;
|
||||
--text: #c9d1d9;
|
||||
--border: #30363d;
|
||||
--primary: #58a6ff;
|
||||
--primary-text: #0d1117;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 2rem;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 2rem;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
|
||||
}
|
||||
h1 { margin: 0 0 0.5rem; font-size: 1.5rem; }
|
||||
.badge {
|
||||
display: inline-block;
|
||||
background: var(--error);
|
||||
color: #fff;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
input, select {
|
||||
width: 100%;
|
||||
padding: 0.625rem 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-size: 0.9375rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
background: var(--primary);
|
||||
color: var(--primary-text);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { opacity: 0.9; }
|
||||
.hint {
|
||||
margin-top: 1.5rem;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text);
|
||||
opacity: 0.7;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Development Login</h1>
|
||||
<span class="badge">DEV ONLY</span>
|
||||
<form method="POST" action="/auth/dev-login">
|
||||
<label for="username">Username</label>
|
||||
<input type="text" id="username" name="username" value="Dev User" required>
|
||||
<label for="role">Role</label>
|
||||
<select id="role" name="role">
|
||||
<option value="user">User</option>
|
||||
<option value="user2">Test User</option>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="guest">Guest (unauthenticated)</option>
|
||||
</select>
|
||||
<button type="submit">Sign In</button>
|
||||
</form>
|
||||
<p class="hint">This bypasses Keycloak for local development only.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
)
|
||||
|
||||
|
||||
@router.post("/dev-login")
|
||||
async def dev_login_submit(request: Request) -> Response:
|
||||
"""Handle dev login form submission.
|
||||
|
||||
Sets a dev-specific cookie that MockKeycloakClient recognizes.
|
||||
|
||||
Args:
|
||||
request: HTTP request object with form data.
|
||||
|
||||
Returns:
|
||||
RedirectResponse to home page with dev token cookie set.
|
||||
|
||||
Raises:
|
||||
HTTPException: If accessed outside development mode.
|
||||
"""
|
||||
if not settings.is_dev:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
|
||||
form = await request.form()
|
||||
role = str(form.get("role", "user")).strip()
|
||||
token = f"dev-token-{role}"
|
||||
|
||||
response = RedirectResponse(url="/web/", status_code=302)
|
||||
response.set_cookie(
|
||||
key="access_token",
|
||||
value=token,
|
||||
httponly=True,
|
||||
secure=False,
|
||||
samesite="lax",
|
||||
max_age=86400,
|
||||
)
|
||||
|
||||
return response
|
||||
|
||||
@@ -9,19 +9,26 @@ from typing import Annotated
|
||||
from fastapi import Cookie, Depends, HTTPException, Request
|
||||
|
||||
from app.domain.roles import Role, get_effective_role
|
||||
from app.infrastructure.auth import KeycloakAuthClient, TokenInfo
|
||||
from app.infrastructure.auth import KeycloakAuthClient, MockKeycloakClient, TokenInfo
|
||||
from app.infrastructure.config.settings import settings
|
||||
|
||||
|
||||
async def get_keycloak_client(request: Request) -> KeycloakAuthClient:
|
||||
async def get_keycloak_client(
|
||||
request: Request,
|
||||
) -> KeycloakAuthClient | MockKeycloakClient:
|
||||
"""Get Keycloak client from DI container via request state.
|
||||
|
||||
In development mode returns MockKeycloakClient for local testing.
|
||||
|
||||
Args:
|
||||
request: FastAPI request object.
|
||||
|
||||
Returns:
|
||||
KeycloakAuthClient instance from container.
|
||||
KeycloakAuthClient or MockKeycloakClient instance from container.
|
||||
"""
|
||||
client: KeycloakAuthClient = await request.state.dishka_container.get(KeycloakAuthClient)
|
||||
client: KeycloakAuthClient | MockKeycloakClient = await request.state.dishka_container.get(
|
||||
KeycloakAuthClient
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
@@ -75,9 +82,10 @@ async def get_current_user(
|
||||
user = await get_optional_user(request, access_token)
|
||||
|
||||
if not user:
|
||||
login_url = "/auth/dev-login" if settings.is_dev else "/auth/login"
|
||||
raise HTTPException(
|
||||
status_code=307,
|
||||
headers={"Location": "/auth/login"},
|
||||
headers={"Location": login_url},
|
||||
)
|
||||
|
||||
return user
|
||||
@@ -125,9 +133,10 @@ def require_role(required_role: Role): # type: ignore[no-untyped-def]
|
||||
HTTPException: If user lacks required role.
|
||||
"""
|
||||
if not user:
|
||||
login_url = "/auth/dev-login" if settings.is_dev else "/auth/login"
|
||||
raise HTTPException(
|
||||
status_code=307,
|
||||
headers={"Location": "/auth/login"},
|
||||
headers={"Location": login_url},
|
||||
)
|
||||
|
||||
user_role = get_user_role(user)
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
"""Web UI routes for blog application with authentication.
|
||||
"""Web UI routes for blog application with real use case integration.
|
||||
|
||||
This module provides HTML endpoints for the blog web interface
|
||||
with role-based access control and user authentication.
|
||||
with role-based access control, user authentication, and full
|
||||
integration with the application's use cases and domain layer.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from dishka.integrations.fastapi import DishkaRoute, FromDishka
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from markdown_it import MarkdownIt
|
||||
from pygments import highlight
|
||||
from pygments.formatters import HtmlFormatter
|
||||
from pygments.lexers import get_lexer_by_name
|
||||
from pygments.util import ClassNotFound
|
||||
|
||||
from app.application.dtos import CreatePostDTO, UpdatePostDTO
|
||||
from app.application.use_cases import (
|
||||
CreatePostUseCase,
|
||||
DeletePostUseCase,
|
||||
GetPostUseCase,
|
||||
ListPostsUseCase,
|
||||
PublishPostUseCase,
|
||||
UpdatePostUseCase,
|
||||
)
|
||||
from app.domain.exceptions import (
|
||||
AlreadyExistsException,
|
||||
NotFoundException,
|
||||
ValidationException,
|
||||
)
|
||||
from app.domain.roles import Role, get_effective_role
|
||||
from app.infrastructure.auth import TokenInfo
|
||||
from app.presentation.web.deps import (
|
||||
OptionalUserDep,
|
||||
@@ -20,135 +40,52 @@ from app.presentation.web.deps import (
|
||||
can_delete_post,
|
||||
can_edit_post,
|
||||
can_see_draft,
|
||||
get_user_role,
|
||||
)
|
||||
from app.presentation.web.flash import flash
|
||||
|
||||
router = APIRouter(prefix="/web", tags=["web"])
|
||||
router = APIRouter(prefix="/web", tags=["web"], route_class=DishkaRoute)
|
||||
templates = Jinja2Templates(directory="app/presentation/templates")
|
||||
|
||||
|
||||
def nl2br(value: str) -> str:
|
||||
"""Convert newlines to HTML line breaks.
|
||||
_md = MarkdownIt("commonmark", {"html": False}).enable("table")
|
||||
|
||||
|
||||
def _highlight_code(code: str, lang: str, _: Any) -> str:
|
||||
try:
|
||||
lexer = get_lexer_by_name(lang)
|
||||
except ClassNotFound:
|
||||
lexer = get_lexer_by_name("text")
|
||||
formatter = HtmlFormatter(nowrap=True)
|
||||
result: str = highlight(code, lexer, formatter)
|
||||
return result
|
||||
|
||||
|
||||
def markdown_filter(value: str) -> str:
|
||||
md = MarkdownIt("commonmark", {"html": False, "highlight": _highlight_code}).enable("table")
|
||||
return str(md.render(value))
|
||||
|
||||
|
||||
templates.env.filters["markdown"] = markdown_filter
|
||||
|
||||
|
||||
_DEFAULT_PAGE_SIZE = 10
|
||||
|
||||
|
||||
def _get_user_role(user: TokenInfo | None) -> Role:
|
||||
"""Get effective role from user token.
|
||||
|
||||
Args:
|
||||
value: String with newlines.
|
||||
user: User token info or None for guest.
|
||||
|
||||
Returns:
|
||||
String with <br> tags instead of newlines.
|
||||
Effective role for the user.
|
||||
"""
|
||||
return value.replace("\n", "<br>\n")
|
||||
if not user:
|
||||
return Role.GUEST
|
||||
return get_effective_role(user.roles)
|
||||
|
||||
|
||||
templates.env.filters["nl2br"] = nl2br
|
||||
|
||||
|
||||
class MockPost:
|
||||
"""Mock post object for UI demonstration.
|
||||
|
||||
This class simulates a Post entity for template rendering
|
||||
before integration with actual use cases.
|
||||
|
||||
Attributes:
|
||||
id: Unique identifier for the post.
|
||||
title: Post title value object.
|
||||
content: Post content value object.
|
||||
slug: URL-friendly slug.
|
||||
author_id: Identifier of the post author.
|
||||
published: Publication status flag.
|
||||
tags: List of tags associated with the post.
|
||||
created_at: Timestamp when the post was created.
|
||||
updated_at: Timestamp when the post was last updated.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
id: str,
|
||||
title: str,
|
||||
content: str,
|
||||
slug: str,
|
||||
author_id: str,
|
||||
published: bool,
|
||||
tags: list[str],
|
||||
created_at: datetime | None = None,
|
||||
) -> None:
|
||||
"""Initialize mock post with provided attributes.
|
||||
|
||||
Args:
|
||||
id: Unique identifier for the post.
|
||||
title: Post title string.
|
||||
content: Post content string.
|
||||
slug: URL-friendly slug string.
|
||||
author_id: Author identifier string.
|
||||
published: Whether the post is published.
|
||||
tags: List of tag strings.
|
||||
created_at: Optional creation timestamp, defaults to now.
|
||||
"""
|
||||
self.id = id
|
||||
self.title = MockValueObject(title)
|
||||
self.content = MockValueObject(content)
|
||||
self.slug = MockValueObject(slug)
|
||||
self.author_id = author_id
|
||||
self.published = published
|
||||
self.tags = tags
|
||||
self.created_at = created_at or datetime.now()
|
||||
self.updated_at = self.created_at
|
||||
|
||||
|
||||
class MockValueObject:
|
||||
"""Mock value object for simulating domain value objects.
|
||||
|
||||
Wraps a raw value to simulate the interface of domain
|
||||
value objects like Title, Content, and Slug.
|
||||
|
||||
Attributes:
|
||||
value: The wrapped string value.
|
||||
"""
|
||||
|
||||
def __init__(self, value: str) -> None:
|
||||
"""Initialize with a string value.
|
||||
|
||||
Args:
|
||||
value: The string value to wrap.
|
||||
"""
|
||||
self.value = value
|
||||
|
||||
|
||||
MOCK_POSTS = [
|
||||
MockPost(
|
||||
id=str(uuid4()),
|
||||
title="Getting Started with FastAPI",
|
||||
content="FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use while providing high performance.",
|
||||
slug="getting-started-with-fastapi",
|
||||
author_id="john_doe",
|
||||
published=True,
|
||||
tags=["python", "fastapi", "tutorial"],
|
||||
created_at=datetime(2026, 1, 15, 10, 30),
|
||||
),
|
||||
MockPost(
|
||||
id=str(uuid4()),
|
||||
title="Understanding DDD Architecture",
|
||||
content="Domain-Driven Design (DDD) is an approach to software development that centers the development on programming a domain model that has a rich understanding of the processes and rules of a domain. The term was coined by Eric Evans in his book of the same title.",
|
||||
slug="understanding-ddd-architecture",
|
||||
author_id="jane_smith",
|
||||
published=True,
|
||||
tags=["ddd", "architecture", "software-design"],
|
||||
created_at=datetime(2026, 1, 14, 14, 45),
|
||||
),
|
||||
MockPost(
|
||||
id=str(uuid4()),
|
||||
title="Draft Post Example",
|
||||
content="This is a draft post that hasn't been published yet. It demonstrates how unpublished posts appear in the UI.",
|
||||
slug="draft-post-example",
|
||||
author_id="john_doe",
|
||||
published=False,
|
||||
tags=["draft"],
|
||||
created_at=datetime(2026, 1, 13, 9, 0),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def get_base_context(user: TokenInfo | None) -> dict[str, Any]:
|
||||
def _get_base_context(user: TokenInfo | None) -> dict[str, Any]:
|
||||
"""Get base template context with user info and permissions.
|
||||
|
||||
Args:
|
||||
@@ -157,7 +94,7 @@ def get_base_context(user: TokenInfo | None) -> dict[str, Any]:
|
||||
Returns:
|
||||
Dictionary with user, user_role, and can_create flags.
|
||||
"""
|
||||
user_role = get_user_role(user)
|
||||
user_role = _get_user_role(user)
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
@@ -166,42 +103,77 @@ def get_base_context(user: TokenInfo | None) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def filter_visible_posts(posts: list[MockPost], user: TokenInfo | None) -> list[MockPost]:
|
||||
"""Filter posts based on user permissions.
|
||||
async def _get_visible_posts(
|
||||
list_use_case: ListPostsUseCase,
|
||||
user: TokenInfo | None,
|
||||
limit: int,
|
||||
offset: int,
|
||||
) -> tuple[list[Any], bool]:
|
||||
"""Fetch posts visible to the user with pagination.
|
||||
|
||||
For guests: only published posts.
|
||||
For users: published posts plus own drafts.
|
||||
For admins: all posts.
|
||||
|
||||
Args:
|
||||
posts: List of all posts.
|
||||
list_use_case: Use case for listing posts.
|
||||
user: Current user or None for guest.
|
||||
limit: Maximum number of posts to return.
|
||||
offset: Number of posts to skip.
|
||||
|
||||
Returns:
|
||||
Filtered list of posts visible to the user.
|
||||
Tuple of (visible posts, has_next flag).
|
||||
"""
|
||||
visible_posts = []
|
||||
user_role = _get_user_role(user)
|
||||
|
||||
for post in posts:
|
||||
if post.published or can_see_draft(user, post.author_id):
|
||||
visible_posts.append(post)
|
||||
if user_role == Role.ADMIN:
|
||||
posts = await list_use_case.all_posts()
|
||||
posts = sorted(posts, key=lambda p: p.created_at, reverse=True)
|
||||
total = len(posts)
|
||||
posts = posts[offset : offset + limit]
|
||||
has_next = offset + limit < total
|
||||
return posts, has_next
|
||||
|
||||
return visible_posts
|
||||
published = await list_use_case.published_posts(limit=limit + 1, offset=offset)
|
||||
has_next = len(published) > limit
|
||||
published = published[:limit]
|
||||
|
||||
if user_role == Role.USER and user is not None:
|
||||
own = await list_use_case.by_author(user.user_id)
|
||||
published_ids = {p.id for p in published}
|
||||
own_drafts = [p for p in own if p.id not in published_ids and not p.published]
|
||||
merged = list(published) + own_drafts
|
||||
merged.sort(key=lambda p: p.created_at, reverse=True)
|
||||
return merged[:limit], has_next or len(own_drafts) > 0
|
||||
|
||||
return published, has_next
|
||||
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
async def home(
|
||||
request: Request,
|
||||
user: OptionalUserDep,
|
||||
list_use_case: FromDishka[ListPostsUseCase],
|
||||
) -> HTMLResponse:
|
||||
"""Render the home page with list of posts.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object for template context.
|
||||
user: Current user from dependency.
|
||||
list_use_case: Use case for listing posts.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with rendered posts list template.
|
||||
"""
|
||||
context = get_base_context(user)
|
||||
visible_posts = filter_visible_posts(MOCK_POSTS, user)
|
||||
page_str = request.query_params.get("page", "1")
|
||||
page = max(1, int(page_str) if page_str.isdigit() else 1)
|
||||
offset = (page - 1) * _DEFAULT_PAGE_SIZE
|
||||
|
||||
visible_posts, has_next = await _get_visible_posts(
|
||||
list_use_case, user, _DEFAULT_PAGE_SIZE, offset
|
||||
)
|
||||
|
||||
context = _get_base_context(user)
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
"pages/index.html",
|
||||
@@ -209,9 +181,9 @@ async def home(
|
||||
**context,
|
||||
"posts": visible_posts,
|
||||
"active_page": "home",
|
||||
"current_page": 1,
|
||||
"has_prev": False,
|
||||
"has_next": False,
|
||||
"current_page": page,
|
||||
"has_prev": page > 1,
|
||||
"has_next": has_next,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -220,19 +192,27 @@ async def home(
|
||||
async def list_posts(
|
||||
request: Request,
|
||||
user: OptionalUserDep,
|
||||
list_use_case: FromDishka[ListPostsUseCase],
|
||||
) -> HTMLResponse:
|
||||
"""Render the posts listing page.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object for template context.
|
||||
user: Current user from dependency.
|
||||
list_use_case: Use case for listing posts.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with rendered posts list template.
|
||||
"""
|
||||
context = get_base_context(user)
|
||||
visible_posts = filter_visible_posts(MOCK_POSTS, user)
|
||||
page_str = request.query_params.get("page", "1")
|
||||
page = max(1, int(page_str) if page_str.isdigit() else 1)
|
||||
offset = (page - 1) * _DEFAULT_PAGE_SIZE
|
||||
|
||||
visible_posts, has_next = await _get_visible_posts(
|
||||
list_use_case, user, _DEFAULT_PAGE_SIZE, offset
|
||||
)
|
||||
|
||||
context = _get_base_context(user)
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
"pages/index.html",
|
||||
@@ -240,9 +220,9 @@ async def list_posts(
|
||||
**context,
|
||||
"posts": visible_posts,
|
||||
"active_page": "posts",
|
||||
"current_page": 1,
|
||||
"has_prev": False,
|
||||
"has_next": True,
|
||||
"current_page": page,
|
||||
"has_prev": page > 1,
|
||||
"has_next": has_next,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -261,7 +241,7 @@ async def new_post_form(
|
||||
Returns:
|
||||
HTMLResponse with rendered post form template.
|
||||
"""
|
||||
context = get_base_context(user)
|
||||
context = _get_base_context(user)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
@@ -279,19 +259,51 @@ async def new_post_form(
|
||||
async def create_post(
|
||||
request: Request,
|
||||
user: RequireUserDep,
|
||||
create_use_case: FromDishka[CreatePostUseCase],
|
||||
publish_use_case: FromDishka[PublishPostUseCase],
|
||||
) -> RedirectResponse:
|
||||
"""Handle new post creation form submission.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object containing form data.
|
||||
user: Current user (required).
|
||||
create_use_case: Use case for creating posts.
|
||||
publish_use_case: Use case for publishing posts.
|
||||
|
||||
Returns:
|
||||
RedirectResponse to the new post or home page.
|
||||
RedirectResponse to the new post or form page.
|
||||
"""
|
||||
flash(request, "Post created successfully!", "success")
|
||||
response = RedirectResponse(url="/web/", status_code=303)
|
||||
return response
|
||||
form = await request.form()
|
||||
title = str(form.get("title", "")).strip()
|
||||
content = str(form.get("content", "")).strip()
|
||||
tags_str = str(form.get("tags", "")).strip()
|
||||
action = str(form.get("action", "draft")).strip()
|
||||
|
||||
tags = [t.strip() for t in tags_str.split(",") if t.strip()]
|
||||
|
||||
try:
|
||||
dto = CreatePostDTO(
|
||||
title=title,
|
||||
content=content,
|
||||
author_id=user.user_id,
|
||||
tags=tags,
|
||||
)
|
||||
result = await create_use_case.execute(dto)
|
||||
|
||||
user_role = _get_user_role(user)
|
||||
if action == "publish":
|
||||
await publish_use_case.publish(result.id, user.user_id, user_role)
|
||||
flash(request, "Post published successfully!", "success")
|
||||
else:
|
||||
flash(request, "Post saved as draft!", "success")
|
||||
|
||||
return RedirectResponse(url=f"/web/posts/{result.slug}", status_code=303)
|
||||
except AlreadyExistsException as exc:
|
||||
flash(request, str(exc), "error")
|
||||
return RedirectResponse(url="/web/posts/new", status_code=303)
|
||||
except ValidationException as exc:
|
||||
flash(request, str(exc), "error")
|
||||
return RedirectResponse(url="/web/posts/new", status_code=303)
|
||||
|
||||
|
||||
@router.get("/posts/{post_slug}", response_class=HTMLResponse)
|
||||
@@ -299,13 +311,15 @@ async def post_detail(
|
||||
request: Request,
|
||||
post_slug: str,
|
||||
user: OptionalUserDep,
|
||||
get_use_case: FromDishka[GetPostUseCase],
|
||||
) -> HTMLResponse:
|
||||
"""Render a single post detail page.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object for template context.
|
||||
post_id: The unique identifier of the post to display.
|
||||
post_slug: The URL-friendly slug of the post to display.
|
||||
user: Current user from dependency.
|
||||
get_use_case: Use case for retrieving posts.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with rendered post detail template.
|
||||
@@ -313,15 +327,15 @@ async def post_detail(
|
||||
Raises:
|
||||
HTTPException: If post not found or not visible to user.
|
||||
"""
|
||||
post = next((p for p in MOCK_POSTS if p.slug.value == post_slug), None)
|
||||
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
try:
|
||||
post = await get_use_case.by_slug(post_slug)
|
||||
except NotFoundException:
|
||||
raise HTTPException(status_code=404, detail="Post not found") from None
|
||||
|
||||
if not post.published and not can_see_draft(user, post.author_id):
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
|
||||
context = get_base_context(user)
|
||||
context = _get_base_context(user)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
@@ -341,13 +355,15 @@ async def edit_post_form(
|
||||
request: Request,
|
||||
post_slug: str,
|
||||
user: RequireUserDep,
|
||||
get_use_case: FromDishka[GetPostUseCase],
|
||||
) -> HTMLResponse:
|
||||
"""Render the post edit form.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object for template context.
|
||||
post_id: The unique identifier of the post to edit.
|
||||
post_slug: The URL-friendly slug of the post to edit.
|
||||
user: Current user (required).
|
||||
get_use_case: Use case for retrieving posts.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with rendered post form template.
|
||||
@@ -355,15 +371,15 @@ async def edit_post_form(
|
||||
Raises:
|
||||
HTTPException: If post not found or user cannot edit it.
|
||||
"""
|
||||
post = next((p for p in MOCK_POSTS if p.slug.value == post_slug), None)
|
||||
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
try:
|
||||
post = await get_use_case.by_slug(post_slug)
|
||||
except NotFoundException:
|
||||
raise HTTPException(status_code=404, detail="Post not found") from None
|
||||
|
||||
if not can_edit_post(user, post.author_id):
|
||||
raise HTTPException(status_code=403, detail="Not authorized to edit this post")
|
||||
|
||||
context = get_base_context(user)
|
||||
context = _get_base_context(user)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
@@ -377,90 +393,103 @@ async def edit_post_form(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/posts/{post_slug}/edit", response_class=HTMLResponse)
|
||||
@router.post("/posts/{post_slug}/edit")
|
||||
async def update_post(
|
||||
request: Request,
|
||||
post_slug: str,
|
||||
user: RequireUserDep,
|
||||
) -> HTMLResponse:
|
||||
get_use_case: FromDishka[GetPostUseCase],
|
||||
update_use_case: FromDishka[UpdatePostUseCase],
|
||||
publish_use_case: FromDishka[PublishPostUseCase],
|
||||
) -> RedirectResponse:
|
||||
"""Handle post update form submission.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object containing form data.
|
||||
post_id: The unique identifier of the post to update.
|
||||
post_slug: The URL-friendly slug of the post to update.
|
||||
user: Current user (required).
|
||||
get_use_case: Use case for retrieving posts.
|
||||
update_use_case: Use case for updating posts.
|
||||
publish_use_case: Use case for publishing posts.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with rendered post detail template.
|
||||
|
||||
Raises:
|
||||
HTTPException: If post not found or user cannot edit it.
|
||||
RedirectResponse to the updated post or form page.
|
||||
"""
|
||||
post = next((p for p in MOCK_POSTS if p.slug.value == post_slug), None)
|
||||
form = await request.form()
|
||||
title = str(form.get("title", "")).strip()
|
||||
content = str(form.get("content", "")).strip()
|
||||
tags_str = str(form.get("tags", "")).strip()
|
||||
action = str(form.get("action", "draft")).strip()
|
||||
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
tags = [t.strip() for t in tags_str.split(",") if t.strip()]
|
||||
|
||||
try:
|
||||
post = await get_use_case.by_slug(post_slug)
|
||||
except NotFoundException:
|
||||
raise HTTPException(status_code=404, detail="Post not found") from None
|
||||
|
||||
if not can_edit_post(user, post.author_id):
|
||||
raise HTTPException(status_code=403, detail="Not authorized to edit this post")
|
||||
|
||||
context = get_base_context(user)
|
||||
try:
|
||||
dto = UpdatePostDTO(
|
||||
title=title if title else None,
|
||||
content=content if content else None,
|
||||
tags=tags if tags else None,
|
||||
)
|
||||
user_role = _get_user_role(user)
|
||||
result = await update_use_case.execute(post.id, dto, user.user_id, user_role)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
"pages/post_detail.html",
|
||||
{
|
||||
**context,
|
||||
"post": post,
|
||||
"active_page": "posts",
|
||||
"can_edit": True,
|
||||
"can_delete": can_delete_post(user, post.author_id),
|
||||
},
|
||||
)
|
||||
if action == "publish":
|
||||
if not result.published:
|
||||
await publish_use_case.publish(result.id, user.user_id, user_role)
|
||||
else:
|
||||
if result.published:
|
||||
await publish_use_case.unpublish(result.id, user.user_id, user_role)
|
||||
|
||||
flash(request, "Post updated successfully!", "success")
|
||||
return RedirectResponse(url=f"/web/posts/{result.slug}", status_code=303)
|
||||
except (AlreadyExistsException, ValidationException) as exc:
|
||||
flash(request, str(exc), "error")
|
||||
return RedirectResponse(url=f"/web/posts/{post_slug}/edit", status_code=303)
|
||||
|
||||
|
||||
@router.post("/posts/{post_slug}/delete", response_class=HTMLResponse)
|
||||
@router.post("/posts/{post_slug}/delete")
|
||||
async def delete_post(
|
||||
request: Request,
|
||||
post_slug: str,
|
||||
user: RequireUserDep,
|
||||
) -> HTMLResponse:
|
||||
get_use_case: FromDishka[GetPostUseCase],
|
||||
delete_use_case: FromDishka[DeletePostUseCase],
|
||||
) -> RedirectResponse:
|
||||
"""Handle post deletion.
|
||||
|
||||
Args:
|
||||
request: The HTTP request object.
|
||||
post_id: The unique identifier of the post to delete.
|
||||
post_slug: The URL-friendly slug of the post to delete.
|
||||
user: Current user (required).
|
||||
get_use_case: Use case for retrieving posts.
|
||||
delete_use_case: Use case for deleting posts.
|
||||
|
||||
Returns:
|
||||
HTMLResponse redirecting to the home page.
|
||||
|
||||
Raises:
|
||||
HTTPException: If post not found or user cannot delete it.
|
||||
RedirectResponse redirecting to the home page.
|
||||
"""
|
||||
post = next((p for p in MOCK_POSTS if p.slug.value == post_slug), None)
|
||||
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
try:
|
||||
post = await get_use_case.by_slug(post_slug)
|
||||
except NotFoundException:
|
||||
raise HTTPException(status_code=404, detail="Post not found") from None
|
||||
|
||||
if not can_delete_post(user, post.author_id):
|
||||
raise HTTPException(status_code=403, detail="Not authorized to delete this post")
|
||||
|
||||
context = get_base_context(user)
|
||||
visible_posts = filter_visible_posts(MOCK_POSTS, user)
|
||||
try:
|
||||
user_role = _get_user_role(user)
|
||||
await delete_use_case.execute(post.id, user.user_id, user_role)
|
||||
flash(request, "Post deleted successfully!", "success")
|
||||
except NotFoundException:
|
||||
flash(request, "Post not found.", "error")
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
"pages/index.html",
|
||||
{
|
||||
**context,
|
||||
"posts": visible_posts,
|
||||
"active_page": "home",
|
||||
"current_page": 1,
|
||||
"has_prev": False,
|
||||
"has_next": False,
|
||||
},
|
||||
)
|
||||
return RedirectResponse(url="/web/", status_code=303)
|
||||
|
||||
|
||||
@router.get("/profile", response_class=HTMLResponse)
|
||||
@@ -477,7 +506,7 @@ async def profile(
|
||||
Returns:
|
||||
HTMLResponse with rendered profile template.
|
||||
"""
|
||||
context = get_base_context(user)
|
||||
context = _get_base_context(user)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
@@ -503,17 +532,13 @@ async def about(
|
||||
Returns:
|
||||
HTMLResponse with rendered about page template.
|
||||
"""
|
||||
return HTMLResponse(
|
||||
content=f"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>About - Blog</title></head>
|
||||
<body>
|
||||
<h1>About</h1>
|
||||
<p>A modern blog built with FastAPI and DDD architecture.</p>
|
||||
<p>User: {user.username if user else "Guest"}</p>
|
||||
<a href="/web/">Back to home</a>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
context = _get_base_context(user)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
"pages/about.html",
|
||||
{
|
||||
**context,
|
||||
"active_page": "about",
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user