initial commit
This commit is contained in:
41
app/services/auth.py
Normal file
41
app/services/auth.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
def get_current_user(request: Request, db: Session = Depends(get_db)) -> User:
|
||||
token = request.cookies.get("access_token")
|
||||
if not token:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Nicht angemeldet.")
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
user_id = int(payload.get("sub"))
|
||||
except (JWTError, TypeError, ValueError) as exc:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Ungültiger Token.") from exc
|
||||
|
||||
user = db.query(User).filter(User.id == user_id, User.is_active.is_(True)).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Benutzer nicht gefunden.")
|
||||
return user
|
||||
|
||||
|
||||
def get_admin_user(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin-Rechte erforderlich.")
|
||||
return current_user
|
||||
|
||||
|
||||
def require_editor_or_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role not in {"admin", "editor"}:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Editor- oder Admin-Rechte erforderlich.")
|
||||
return current_user
|
||||
|
||||
|
||||
def require_reader_or_higher(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role not in {"admin", "editor", "reader"}:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin-Rechte erforderlich.")
|
||||
return current_user
|
||||
17
app/services/config_store.py
Normal file
17
app/services/config_store.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.system import AppConfig
|
||||
|
||||
|
||||
def get_config(db: Session, key: str, default: str = "") -> str:
|
||||
row = db.query(AppConfig).filter(AppConfig.key == key).first()
|
||||
return row.value if row else default
|
||||
|
||||
|
||||
def set_config(db: Session, key: str, value: str) -> None:
|
||||
row = db.query(AppConfig).filter(AppConfig.key == key).first()
|
||||
if row:
|
||||
row.value = value
|
||||
else:
|
||||
db.add(AppConfig(key=key, value=value))
|
||||
db.commit()
|
||||
20
app/services/csrf.py
Normal file
20
app/services/csrf.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import secrets
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
|
||||
CSRF_COOKIE_NAME = "csrf_token"
|
||||
CSRF_FORM_FIELD = "csrf_token"
|
||||
|
||||
|
||||
def ensure_csrf_cookie(request: Request) -> str:
|
||||
token = request.cookies.get(CSRF_COOKIE_NAME)
|
||||
if token:
|
||||
return token
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def validate_csrf(request: Request, form_token: str) -> None:
|
||||
cookie_token = request.cookies.get(CSRF_COOKIE_NAME)
|
||||
if not cookie_token or not form_token or not secrets.compare_digest(cookie_token, form_token):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="CSRF-Validierung fehlgeschlagen.")
|
||||
76
app/services/newsletter.py
Normal file
76
app/services/newsletter.py
Normal file
@@ -0,0 +1,76 @@
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from typing import Any
|
||||
|
||||
|
||||
def filter_articles(
|
||||
articles: list[dict[str, Any]],
|
||||
category_filter: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if not category_filter:
|
||||
return articles
|
||||
wanted = category_filter.strip().lower()
|
||||
return [
|
||||
a
|
||||
for a in articles
|
||||
if any(c.lower() == wanted for c in a.get("categories", []))
|
||||
]
|
||||
|
||||
|
||||
def create_plain_text(articles: list[dict[str, Any]], title: str) -> str:
|
||||
lines = [title, "=" * len(title), ""]
|
||||
if not articles:
|
||||
lines.append("Keine Artikel im gewählten Zeitraum gefunden.")
|
||||
return "\n".join(lines)
|
||||
|
||||
for idx, item in enumerate(articles, start=1):
|
||||
stamp = _format_ts(item.get("timestamp"))
|
||||
cat = ", ".join(item.get("categories", [])) or "Keine Kategorie"
|
||||
comment = item.get("comment") or "-"
|
||||
lines.extend(
|
||||
[
|
||||
f"{idx}. {item.get('title', 'Ohne Titel')}",
|
||||
f" Zeit: {stamp}",
|
||||
f" Benutzer: {item.get('user', '-')}",
|
||||
f" Kategorien: {cat}",
|
||||
f" Kommentar: {comment}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def create_html(articles: list[dict[str, Any]], title: str) -> str:
|
||||
if not articles:
|
||||
return f"<h2>{escape(title)}</h2><p>Keine Artikel im gewählten Zeitraum gefunden.</p>"
|
||||
|
||||
blocks = [f"<h2>{escape(title)}</h2>", "<ul>"]
|
||||
for item in articles:
|
||||
article_title = escape(item.get("title", "Ohne Titel"))
|
||||
stamp = escape(_format_ts(item.get("timestamp")))
|
||||
user = escape(item.get("user", "-"))
|
||||
cat = escape(", ".join(item.get("categories", [])) or "Keine Kategorie")
|
||||
comment = escape(item.get("comment") or "-")
|
||||
blocks.append(
|
||||
(
|
||||
"<li>"
|
||||
f"<strong>{article_title}</strong><br>"
|
||||
f"Zeit: {stamp}<br>"
|
||||
f"Benutzer: {user}<br>"
|
||||
f"Kategorien: {cat}<br>"
|
||||
f"Kommentar: {comment}"
|
||||
"</li>"
|
||||
)
|
||||
)
|
||||
blocks.append("</ul>")
|
||||
return "\n".join(blocks)
|
||||
|
||||
|
||||
def _format_ts(value: str | None) -> str:
|
||||
if not value:
|
||||
return "-"
|
||||
try:
|
||||
dt = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
|
||||
return dt.strftime("%d.%m.%Y %H:%M UTC")
|
||||
except ValueError:
|
||||
return value
|
||||
89
app/services/smtp_sender.py
Normal file
89
app/services/smtp_sender.py
Normal file
@@ -0,0 +1,89 @@
|
||||
import smtplib
|
||||
from datetime import datetime
|
||||
from email.mime.text import MIMEText
|
||||
from typing import Sequence
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.system import SendLog
|
||||
from app.services.config_store import get_config
|
||||
|
||||
|
||||
def get_smtp_settings(db: Session) -> dict[str, str]:
|
||||
return {
|
||||
"enabled": get_config(db, "smtp.enabled", "false"),
|
||||
"host": get_config(db, "smtp.host", ""),
|
||||
"port": get_config(db, "smtp.port", "587"),
|
||||
"username": get_config(db, "smtp.username", ""),
|
||||
"password": get_config(db, "smtp.password", ""),
|
||||
"from_email": get_config(db, "smtp.from_email", ""),
|
||||
"use_tls": get_config(db, "smtp.use_tls", "true"),
|
||||
"recipients": get_config(db, "smtp.recipients", ""),
|
||||
"schedule_time": get_config(db, "smtp.schedule_time", "08:00"),
|
||||
"last_scheduled_date": get_config(db, "smtp.last_scheduled_date", ""),
|
||||
}
|
||||
|
||||
|
||||
def send_newsletter(
|
||||
db: Session,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: str,
|
||||
recipients: Sequence[str],
|
||||
scheduled: bool = False,
|
||||
) -> None:
|
||||
settings = get_smtp_settings(db)
|
||||
if settings["enabled"].lower() != "true":
|
||||
_log(db, subject, recipients, "skipped", "SMTP ist deaktiviert.", scheduled)
|
||||
return
|
||||
if not settings["host"] or not settings["from_email"] or not recipients:
|
||||
_log(db, subject, recipients, "failed", "SMTP unvollständig konfiguriert.", scheduled)
|
||||
return
|
||||
|
||||
msg = MIMEText(html_content, "html", "utf-8")
|
||||
msg["Subject"] = subject
|
||||
msg["From"] = settings["from_email"]
|
||||
msg["To"] = ", ".join(recipients)
|
||||
|
||||
try:
|
||||
port = int(settings["port"])
|
||||
with smtplib.SMTP(settings["host"], port, timeout=20) as server:
|
||||
if settings["use_tls"].lower() == "true":
|
||||
server.starttls()
|
||||
if settings["username"]:
|
||||
server.login(settings["username"], settings["password"])
|
||||
server.sendmail(settings["from_email"], list(recipients), msg.as_string())
|
||||
_log(db, subject, recipients, "sent", "Versand erfolgreich.", scheduled)
|
||||
except Exception as exc:
|
||||
_log(db, subject, recipients, "failed", f"Versandfehler: {exc}", scheduled)
|
||||
|
||||
|
||||
def run_scheduled_send_if_due(db: Session, subject: str, html_content: str, text_content: str) -> None:
|
||||
settings = get_smtp_settings(db)
|
||||
if settings["enabled"].lower() != "true":
|
||||
return
|
||||
now = datetime.now()
|
||||
schedule_time = settings["schedule_time"] or "08:00"
|
||||
if now.strftime("%H:%M") < schedule_time:
|
||||
return
|
||||
today = now.strftime("%Y-%m-%d")
|
||||
if settings["last_scheduled_date"] == today:
|
||||
return
|
||||
recipients = [r.strip() for r in settings["recipients"].split(",") if r.strip()]
|
||||
send_newsletter(db, subject, html_content, text_content, recipients, scheduled=True)
|
||||
from app.services.config_store import set_config
|
||||
|
||||
set_config(db, "smtp.last_scheduled_date", today)
|
||||
|
||||
|
||||
def _log(db: Session, subject: str, recipients: Sequence[str], status: str, detail: str, scheduled: bool) -> None:
|
||||
db.add(
|
||||
SendLog(
|
||||
subject=subject,
|
||||
recipients=", ".join(recipients) if recipients else "-",
|
||||
status=status,
|
||||
detail=detail,
|
||||
scheduled=scheduled,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
78
app/services/wiki.py
Normal file
78
app/services/wiki.py
Normal file
@@ -0,0 +1,78 @@
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
class WikiService:
|
||||
def __init__(self) -> None:
|
||||
self.api_url = settings.wiki_api_url
|
||||
|
||||
async def get_recent_changes(self, days: int = 30, only_edited: bool = False) -> list[dict[str, Any]]:
|
||||
now = datetime.now(timezone.utc)
|
||||
start = now - timedelta(days=days)
|
||||
rcstart = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
rcend = start.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
params = {
|
||||
"action": "query",
|
||||
"format": "json",
|
||||
"list": "recentchanges",
|
||||
"rcprop": "title|timestamp|user|comment|flags|sizes|loginfo",
|
||||
"rclimit": "200",
|
||||
"rcstart": rcstart,
|
||||
"rcend": rcend,
|
||||
"rcnamespace": "0",
|
||||
}
|
||||
if only_edited:
|
||||
params["rctype"] = "edit"
|
||||
else:
|
||||
params["rctype"] = "new|edit"
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
cont: dict[str, Any] = {}
|
||||
async with httpx.AsyncClient(timeout=20.0) as client:
|
||||
while True:
|
||||
response = await client.get(self.api_url, params={**params, **cont})
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
rows.extend(payload.get("query", {}).get("recentchanges", []))
|
||||
if "continue" not in payload:
|
||||
break
|
||||
cont = payload["continue"]
|
||||
|
||||
titles = sorted({item["title"] for item in rows if item.get("title")})
|
||||
categories = await self._get_categories_for_titles(client, titles)
|
||||
|
||||
for row in rows:
|
||||
row["categories"] = categories.get(row.get("title", ""), [])
|
||||
return rows
|
||||
|
||||
async def _get_categories_for_titles(self, client: httpx.AsyncClient, titles: list[str]) -> dict[str, list[str]]:
|
||||
result: dict[str, list[str]] = defaultdict(list)
|
||||
if not titles:
|
||||
return {}
|
||||
|
||||
chunk_size = 25
|
||||
for i in range(0, len(titles), chunk_size):
|
||||
chunk = titles[i : i + chunk_size]
|
||||
params = {
|
||||
"action": "query",
|
||||
"format": "json",
|
||||
"prop": "categories",
|
||||
"cllimit": "max",
|
||||
"titles": "|".join(chunk),
|
||||
}
|
||||
response = await client.get(self.api_url, params=params)
|
||||
response.raise_for_status()
|
||||
pages = response.json().get("query", {}).get("pages", {})
|
||||
for page in pages.values():
|
||||
title = page.get("title")
|
||||
if not title:
|
||||
continue
|
||||
raw_categories = page.get("categories", [])
|
||||
result[title] = [c.get("title", "").replace("Kategorie:", "") for c in raw_categories if c.get("title")]
|
||||
return result
|
||||
Reference in New Issue
Block a user