14 Commits
Author SHA1 Message Date
Rudi c4cef10909 Base Website
Basic Website, mit Login, Homepage, Usericon, Profilsettings, adminsettings.
(KI)
2026-09-23 23:07:35 +02:00
Rudi 99cea87151 Some small changes
Z.B. Dateipfad oben hinschreiben
2026-09-23 18:13:48 +02:00
Rudi ea86fd75ec Final merging to main
Docker Build & Push / build-and-push (push) Successful in 35s
2026-09-03 17:49:29 +02:00
Rudi 650a11231a Somw changes 2026-09-03 17:49:18 +02:00
Rudi e543c60ed5 last visual fixes 2026-09-03 17:38:58 +02:00
Rudi 799cc9597c Zeilen Falsch
Docker Build & Push / build-and-push (push) Successful in 35s
2026-09-03 17:36:40 +02:00
Rudi a6f1c0e967 fix: repo to Lower 2026-09-03 17:35:28 +02:00
Rudi 26bb103535 some description
Docker Build & Push / build-and-push (push) Failing after 26s
2026-09-03 17:22:18 +02:00
Rudi 756799feb6 fix 'toLower' not implemented 2026-09-03 17:21:25 +02:00
Rudi 2db0cc3ecb fix with uppercase repo name
Docker Build & Push / build-and-push (push) Failing after 29s
2026-09-03 17:17:29 +02:00
Rudi 0a950cefe2 Workflow update
Docker Build & Push / build-and-push (push) Successful in 2m30s
2026-09-03 17:03:27 +02:00
Rudi 51c024edde pürerelease fix N°2
Docker Build & Push / build (push) Successful in 28s
Docker Build & Push / release (push) Successful in 9s
2026-08-28 21:10:35 +02:00
Rudi af3b084ee9 prerelease fix
Docker Build & Push / build (push) Successful in 30s
Docker Build & Push / release (push) Successful in 10s
2026-08-28 21:05:58 +02:00
Rudi bef5493dc1 YAML fix
Docker Build & Push / build (push) Successful in 29s
Docker Build & Push / release (push) Successful in 11s
2026-08-28 21:02:22 +02:00
21 changed files with 518 additions and 92 deletions

No files matched your search

+44 -49
View File
@@ -1,63 +1,58 @@
name: Docker Build & Push name: Docker Build & Push
run-name: Release ${{ gitea.ref_name }}
on: on:
push: push:
tags: tags:
- 'v*' - 'v*'
jobs: jobs:
build: build-and-push:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
releases: write
packages: write
steps: steps:
- name: Code auschecken - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Bei Gitea Container Registry anmelden
uses: docker/login-action@v2
with:
registry: 127.0.0.1:3000
username: ${{ gitea.actor }}
password: ${{ secrets.token }}
- name: Docker Image bauen (nur lokal im Runner)
uses: docker/build-push-action@v4
with:
context: .
push: false
tags: |
127.0.0.1:3000/rudi/tandur:${{ gitea.ref_name }}
127.0.0.1:3000/rudi/tandur:latest
- name: Images zu Gitea pushen
run: |
docker push 127.0.0.1:3000/rudi/tandur:${{ gitea.ref_name }}
docker push 127.0.0.1:3000/rudi/tandur:latest
release:
if: startsWith(gitea.ref, 'refs/tags/v')
needs: build
runs-on: ubuntu-latest
steps:
- name: Code auschecken
uses: actions/checkout@v3
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Gitea Release erstellen - name: Log in to Gitea Container Registry
uses: docker/login-action@v3
with:
registry: git.schamagusa.de
username: ${{ gitea.actor }}
password: ${{ secrets.RELEASE_TOKEN }}
# 'toLower()' is not implemented
- name: Repository kleinschreiben
id: lowercase
env:
REPO: ${{ gitea.repository }}
run: |
echo "repo=$(printf '%s' "$REPO" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
- name: Build and push Docker image
uses: docker/build-push-action@v5
env:
REPO: ${{ gitea.repository }}
with:
context: .
push: true
tags: |
git.schamagusa.de/${{ steps.lowercase.outputs.repo }}:${{ gitea.ref_name }}
git.schamagusa.de/${{ steps.lowercase.outputs.repo }}:latest
- name: Prepare release notes
run: |
sed "s|{{VERSION}}|${{ gitea.ref_name }}|g" CHANGELOG.md > release_notes.md
cat release_notes.md
- name: Create Release
uses: https://gitea.com/actions/gitea-release-action@main uses: https://gitea.com/actions/gitea-release-action@main
with: with:
api_key: '${{ secrets.TOKEN }}' body_path: release_notes.md
files: |- prerelease: ${{ contains(gitea.ref_name, '-rc') || contains(gitea.ref_name, '-beta') || contains(gitea.ref_name, '-alpha') }}
docker-compose.yaml files: |
body: | example.docker-compose.yaml
## Docker Image: example.env
```
docker pull git.schamagusa.de/rudi/tandur:latest
```
## Docker Compose
Download the `docker-compose.yaml`
and then
```
docker compose pull
docker compose up -d
```
+22
View File
@@ -0,0 +1,22 @@
This version includes a new workflow file, so the Releases come faster and better to you
## New Features
- Workflow with better description and performance
## Bug fixes
- added 'toLower' function to workflow
---
### Installation
> **Note:** This guide assumes that Docker and Docker Compose are already installed.
Download the `example.env` and the `example.docker-compose.yaml`, edit those and rename to `.env` and `docker-compose.yaml`.
Then run
```bash
docker compose pull
docker compose up -d
```
+10 -1
View File
@@ -2,7 +2,7 @@ from fastapi import Depends, status, Request
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
import jwt import jwt
# auth/dependencies.py # auth/dependencies.py
# @/auth/dependencies.py
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from database import get_db from database import get_db
from models.user import User from models.user import User
@@ -31,3 +31,12 @@ def get_me(request: Request, db: Session = Depends(get_db)) -> User:
raise UnauthorizedError("Token invalid or expired") raise UnauthorizedError("Token invalid or expired")
return user return user
def get_current_user_optional(request: Request, db: Session = Depends(get_db)) -> User | None:
"""
Same as get_me, but without error
"""
try:
return get_me(request, db)
except UnauthorizedError:
return None
+1
View File
@@ -1,3 +1,4 @@
# @/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): class Settings(BaseSettings):
+1 -1
View File
@@ -1,4 +1,4 @@
# crud/user.py # @/crud/user.py
from sqlalchemy import select, exists, func from sqlalchemy import select, exists, func
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
File renamed without changes.
+10
View File
@@ -0,0 +1,10 @@
# Einvironment Variablen
API_KEY=
TANDOOR_URL =
SECRET_KEY =
#ALGORITHM = "HS256"
#ACCESS_TOKEN_EXPIRE_MINUTES = 30
+1
View File
@@ -1,3 +1,4 @@
# @/exeptions.py
from typing import Any from typing import Any
+61 -5
View File
@@ -1,14 +1,31 @@
from fastapi import FastAPI, Request, status # @/main.py
from fastapi.responses import JSONResponse from fastapi import FastAPI, Request, status, Depends
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.templating import Jinja2Templates from fastapi.templating import Jinja2Templates
from exceptions import UserNotFoundError, UserAlreadyExistsError, UnauthorizedError, ForbiddenError, ValidationError
from exceptions import UserNotFoundError, UserAlreadyExistsError, UnauthorizedError, ForbiddenError, ValidationError #Errors
from auth.dependencies import get_current_user_optional
from database import get_db
import models #Database import models #Database
from routers import api_router #API from routers import api_router #API
app = FastAPI(title="Tandur API") app = FastAPI(title="Tandur API")
app.include_router(api_router) app.include_router(api_router)
templates = Jinja2Templates(directory="templates") templates = Jinja2Templates(directory="templates")
def _safe_next(path: str) -> str:
"""
Lässt als Redirect-Ziel nur relative, interne Pfade zu.
Ohne diese Prüfung wäre /login?next=https://evil.example ein offener
Redirect (Phishing: Login bei uns, Weiterleitung auf fremde Seite).
"""
if path.startswith("/") and not path.startswith("//") and "://" not in path:
return path
return "/"
######### ERROR handling ######### ######### ERROR handling #########
# 1. Globale Regel für 404 # 1. Globale Regel für 404
@@ -50,8 +67,47 @@ def permissions_handler(request: Request, exc: ValidationError):
) )
######### PAGES #########
@app.get("/login")
async def login_page(request: Request, next: str = "/", db: Session = Depends(get_db)):
# Schon eingeloggt? Dann /login gar nicht erst anzeigen.
user = get_current_user_optional(request, db)
if user is not None:
return RedirectResponse(url=_safe_next(next), status_code=status.HTTP_302_FOUND)
return templates.TemplateResponse(request=request, name="login.html")
@app.get("/logout")
async def logout():
response = RedirectResponse(url="/login", status_code=status.HTTP_302_FOUND)
response.delete_cookie("access_token")
return response
@app.get("/") @app.get("/")
async def home(request: Request): async def home(request: Request, db: Session = Depends(get_db)):
return templates.TemplateResponse(request=request, name="index.html") user = get_current_user_optional(request, db)
if user is None:
return RedirectResponse(url="/login?next=/", status_code=status.HTTP_302_FOUND)
return templates.TemplateResponse(request=request, name="index.html", context={"user": user})
@app.get("/profile")
async def profile_page(request: Request, db: Session = Depends(get_db)):
user = get_current_user_optional(request, db)
if user is None:
return RedirectResponse(url="/login?next=/profile", status_code=status.HTTP_302_FOUND)
return templates.TemplateResponse(request=request, name="profile.html", context={"user": user})
@app.get("/admin")
async def admin_page(request: Request, db: Session = Depends(get_db)):
user = get_current_user_optional(request, db)
if user is None:
return RedirectResponse(url="/login?next=/admin", status_code=status.HTTP_302_FOUND)
if user.role != "admin":
# Kein 403 auf Seitenebene - einfach zurück zur Startseite.
# Der eigentliche Schutz sitzt ohnehin serverseitig in den /api/users-Endpunkten.
return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
return templates.TemplateResponse(request=request, name="admin.html", context={"user": user})
+1
View File
@@ -1,3 +1,4 @@
# @/routers/__init__.py
from fastapi import APIRouter from fastapi import APIRouter
from .users import router as users_router from .users import router as users_router
+2 -2
View File
@@ -1,4 +1,4 @@
# routers/auth.py # @/routers/auth.py
from fastapi import APIRouter, Depends, status, Response from fastapi import APIRouter, Depends, status, Response
from fastapi.security import OAuth2PasswordRequestForm from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session
from database import get_db from database import get_db
from schemas.auth import LoginRequest from schemas.auth import LoginRequest
from schemas.user import UserResponse from schemas.user import UserResponse
#from exceptions import UserAlreadyExistsError, UserNotFoundError from exceptions import UnauthorizedError
from crud.user import get_user_by_email from crud.user import get_user_by_email
from auth.security import verify_password, create_access_token from auth.security import verify_password, create_access_token
+1 -1
View File
@@ -1,4 +1,4 @@
# routers/users.py # @/routers/users.py
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
+1 -1
View File
@@ -1,4 +1,4 @@
# /schemas/auth.py # @/schemas/auth.py
from pydantic import BaseModel from pydantic import BaseModel
+1
View File
@@ -1,3 +1,4 @@
# @/schemas/user.py
from pydantic import BaseModel from pydantic import BaseModel
class UserCreate(BaseModel): class UserCreate(BaseModel):
+154
View File
@@ -0,0 +1,154 @@
{% extends "base.html" %}
{% block title %}Admin – Tandur{% endblock %}
{% block content %}
{% include "navbar.html" %}
<main class="mx-auto max-w-5xl px-4 py-10" x-data="adminPanel()" x-init="load()">
<div class="mb-8 flex items-center justify-between">
<h1 class="font-display text-2xl font-semibold">Benutzer</h1>
<button @click="openCreate()" class="rounded bg-marker px-4 py-2 text-sm font-medium text-board hover:brightness-95">
Benutzer anlegen
</button>
</div>
<p x-show="error" x-text="error" class="mb-4 text-sm text-brick" style="display:none"></p>
<div class="overflow-hidden rounded border border-panel">
<table class="w-full text-left text-sm">
<thead class="bg-panel text-muted">
<tr>
<th class="px-4 py-2 font-medium">E-Mail</th>
<th class="px-4 py-2 font-medium">Rolle</th>
<th class="px-4 py-2 font-medium"></th>
</tr>
</thead>
<tbody>
<template x-for="u in users" :key="u.id">
<tr class="border-t border-panel">
<td class="px-4 py-2" x-text="u.email"></td>
<td class="px-4 py-2" x-text="u.role"></td>
<td class="space-x-3 px-4 py-2 text-right">
<button @click="openEdit(u)" class="text-marker hover:underline">Bearbeiten</button>
<button @click="remove(u)" class="text-brick hover:underline">Löschen</button>
</td>
</tr>
</template>
<tr x-show="!loading && users.length === 0">
<td colspan="3" class="px-4 py-6 text-center text-muted">Keine Benutzer vorhanden.</td>
</tr>
</tbody>
</table>
</div>
<!-- Modal: Anlegen / Bearbeiten -->
<div x-show="modalOpen" style="display:none" class="fixed inset-0 z-10 flex items-center justify-center bg-black/50 px-4">
<div class="w-full max-w-sm rounded border border-panel bg-panel p-6">
<h2 class="mb-4 font-display text-lg font-semibold" x-text="editing ? 'Benutzer bearbeiten' : 'Benutzer anlegen'"></h2>
<form @submit.prevent="save" class="space-y-4">
<div>
<label class="mb-1 block text-sm text-muted">E-Mail</label>
<input type="username" x-model="form.email" required
class="w-full rounded border border-board bg-board px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
</div>
<div>
<label class="mb-1 block text-sm text-muted" x-text="editing ? 'Neues Passwort (optional)' : 'Passwort'"></label>
<input type="password" x-model="form.password" :required="!editing"
class="w-full rounded border border-board bg-board px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
</div>
<div>
<label class="mb-1 block text-sm text-muted">Rolle</label>
<select x-model="form.role" class="w-full rounded border border-board bg-board px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
<option value="user">user</option>
<option value="admin">admin</option>
</select>
</div>
<p x-show="formError" x-text="formError" class="text-sm text-brick" style="display:none"></p>
<div class="flex justify-end gap-3 pt-2">
<button type="button" @click="modalOpen = false" class="rounded px-4 py-2 text-sm text-muted hover:text-chalk">Abbrechen</button>
<button type="submit" class="rounded bg-marker px-4 py-2 text-sm font-medium text-board hover:brightness-95">Speichern</button>
</div>
</form>
</div>
</div>
</main>
<script>
function adminPanel() {
return {
users: [],
loading: true,
error: '',
modalOpen: false,
editing: null,
form: { email: '', password: '', role: 'user' },
formError: '',
async load() {
this.loading = true;
this.error = '';
const res = await fetch('/api/users/', { credentials: 'same-origin' });
if (res.status === 401) {
window.location.href = '/login?next=/admin';
return;
}
if (res.status === 404) {
// Backend meldet "keine User" als 404 statt leerer Liste
this.users = [];
} else if (!res.ok) {
this.error = 'Benutzer konnten nicht geladen werden.';
} else {
this.users = await res.json();
}
this.loading = false;
},
openCreate() {
this.editing = null;
this.form = { email: '', password: '', role: 'user' };
this.formError = '';
this.modalOpen = true;
},
openEdit(u) {
this.editing = u;
this.form = { email: u.email, password: '', role: u.role };
this.formError = '';
this.modalOpen = true;
},
async save() {
this.formError = '';
const payload = { email: this.form.email, role: this.form.role };
if (this.form.password) payload.password = this.form.password;
const url = this.editing ? `/api/users/${this.editing.id}` : '/api/users/';
const method = this.editing ? 'PATCH' : 'POST';
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(payload)
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
this.formError = data.detail || 'Speichern fehlgeschlagen.';
return;
}
this.modalOpen = false;
await this.load();
},
async remove(u) {
if (!confirm(`Benutzer ${u.email} wirklich löschen?`)) return;
const res = await fetch(`/api/users/${u.id}`, { method: 'DELETE', credentials: 'same-origin' });
if (res.ok) await this.load();
}
}
}
</script>
{% endblock %}
+28 -4
View File
@@ -2,15 +2,39 @@
<html lang="de"> <html lang="de">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Shoppingliste</title> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Tandur{% endblock %}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">
<!-- Tailwind via CDN --> <!-- Tailwind via CDN -->
<script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
board: '#1F2B22', /* Hintergrund: dunkles Tafel-Grün */
panel: '#26332A', /* Flächen/Karten */
chalk: '#F2EFE6', /* Text */
muted: '#A9B3A6', /* Text, gedämpft */
marker: '#E8B93A', /* Akzent / primäre Aktion */
brick: '#C1553D', /* Warnung / destruktive Aktion */
},
fontFamily: {
display: ['"Space Grotesk"', 'sans-serif'],
},
}
}
}
</script>
<!-- Alpine.js via CDN --> <!-- Alpine.js via CDN -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script> <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
{% block head %}{% endblock %}
</head> </head>
<body class="bg-gray-100 p-8"> <body class="min-h-screen bg-board text-chalk antialiased">
<div class="max-w-2xl mx-auto bg-white p-6 rounded-lg shadow-md">
{% block content %}{% endblock %} {% block content %}{% endblock %}
</div>
</body> </body>
</html> </html>
+12 -5
View File
@@ -1,8 +1,15 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Tandur{% endblock %}
{% block content %} {% block content %}
<div x-data="{ title: 'Meine Shoppingliste' }"> {% include "navbar.html" %}
<h1 class="text-2xl font-bold mb-4" x-text="title"></h1>
<p>Das Grundgerüst steht!</p> <main class="mx-auto max-w-5xl px-4 py-10">
</div> <h1 class="font-display text-2xl font-semibold mb-2">Einkaufsliste</h1>
<p class="mb-8 text-muted">Angemeldet als {{ user.email }}</p>
<button type="button" disabled title="Noch nicht implementiert"
class="cursor-not-allowed rounded bg-marker px-4 py-2 font-medium text-board opacity-60">
Daten laden
</button>
</main>
{% endblock %} {% endblock %}
+65
View File
@@ -0,0 +1,65 @@
{% extends "base.html" %}
{% block title %}Anmelden – Tandur{% endblock %}
{% block content %}
<div class="flex min-h-screen items-center justify-center px-4">
<div class="w-full max-w-sm">
<h1 class="font-display text-2xl font-semibold mb-1">Tandur</h1>
<p class="mb-8 text-sm text-muted">Melde dich an, um deine Einkaufsliste zu sehen.</p>
<form x-data="loginForm()" @submit.prevent="submit" class="space-y-4" novalidate>
<div>
<label for="email" class="mb-1 block text-sm text-muted">E-Mail</label>
<input id="email" type="email" x-model="email" required autocomplete="username"
class="w-full rounded border border-panel bg-panel px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
</div>
<div>
<label for="password" class="mb-1 block text-sm text-muted">Passwort</label>
<input id="password" type="password" x-model="password" required autocomplete="current-password"
class="w-full rounded border border-panel bg-panel px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
</div>
<p x-show="error" x-text="error" class="text-sm text-brick" style="display:none"></p>
<button type="submit" :disabled="loading"
class="w-full rounded bg-marker py-2 font-medium text-board hover:brightness-95 disabled:opacity-60">
<span x-text="loading ? 'Anmelden …' : 'Anmelden'"></span>
</button>
</form>
</div>
</div>
<script>
function loginForm() {
return {
email: '',
password: '',
error: '',
loading: false,
async submit() {
this.error = '';
this.loading = true;
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ username: this.email, password: this.password })
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
this.error = data.detail || 'Anmeldung fehlgeschlagen.';
return;
}
// "next" kommt aus der URL, die main.py beim Redirect zu /login gesetzt hat
const params = new URLSearchParams(window.location.search);
window.location.href = params.get('next') || '/';
} catch (e) {
this.error = 'Server nicht erreichbar.';
} finally {
this.loading = false;
}
}
}
}
</script>
{% endblock %}
+26
View File
@@ -0,0 +1,26 @@
<header class="border-b border-panel">
<div class="mx-auto flex max-w-5xl items-center justify-between px-4 py-3">
<a href="/" class="font-display text-lg font-semibold tracking-tight">Tandur</a>
<div x-data="{ open: false }" class="relative">
<button @click="open = !open" @click.outside="open = false"
class="flex h-9 w-9 items-center justify-center rounded border border-panel transition-colors hover:border-marker"
aria-label="Menü öffnen" aria-haspopup="true" :aria-expanded="open">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<circle cx="12" cy="8" r="3.2"/>
<path d="M4.5 20c1.4-3.6 4.2-5.4 7.5-5.4s6.1 1.8 7.5 5.4"/>
</svg>
</button>
<div x-show="open" x-transition.origin.top.right style="display: none;"
class="absolute right-0 mt-2 w-48 rounded border border-panel bg-panel py-1 shadow-lg shadow-black/30 z-10">
<a href="/profile" class="block px-4 py-2 text-sm hover:bg-board">Profil</a>
{% if user.role == "admin" %}
<a href="/admin" class="block px-4 py-2 text-sm hover:bg-board">Admin-Einstellungen</a>
{% endif %}
<div class="my-1 border-t border-board"></div>
<a href="/logout" class="block px-4 py-2 text-sm text-brick hover:bg-board">Abmelden</a>
</div>
</div>
</div>
</header>
+73
View File
@@ -0,0 +1,73 @@
{% extends "base.html" %}
{% block title %}Profil – Tandur{% endblock %}
{% block content %}
{% include "navbar.html" %}
<main class="mx-auto max-w-md px-4 py-10">
<h1 class="font-display text-2xl font-semibold mb-8">Profil</h1>
<form x-data="profileForm()" x-init="init($el.dataset)"
data-user-id="{{ user.id }}" data-email="{{ user.email }}"
@submit.prevent="save" class="space-y-4">
<div>
<label class="mb-1 block text-sm text-muted">E-Mail</label>
<input type="email" x-model="email" required
class="w-full rounded border border-panel bg-panel px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
</div>
<div>
<label class="mb-1 block text-sm text-muted">Neues Passwort (optional)</label>
<input type="password" x-model="password" autocomplete="new-password"
class="w-full rounded border border-panel bg-panel px-3 py-2 text-chalk focus:outline-none focus:ring-2 focus:ring-marker">
</div>
<div class="text-sm text-muted">Rolle: <span class="text-chalk">{{ user.role }}</span></div>
<p x-show="message" x-text="message" :class="success ? 'text-marker' : 'text-brick'" class="text-sm" style="display:none"></p>
<button type="submit" class="rounded bg-marker px-4 py-2 font-medium text-board hover:brightness-95">
Speichern
</button>
</form>
</main>
<script>
function profileForm() {
return {
userId: null,
email: '',
password: '',
message: '',
success: false,
init(dataset) {
this.userId = dataset.userId;
this.email = dataset.email;
},
async save() {
this.message = '';
const payload = { email: this.email };
if (this.password) payload.password = this.password;
const res = await fetch(`/api/users/${this.userId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(payload)
});
if (res.status === 401) {
window.location.href = '/login?next=/profile';
return;
}
if (!res.ok) {
const data = await res.json().catch(() => ({}));
this.message = data.detail || 'Speichern fehlgeschlagen.';
this.success = false;
return;
}
this.password = '';
this.message = 'Gespeichert.';
this.success = true;
}
}
}
</script>
{% endblock %}
+4 -23
View File
@@ -4,33 +4,14 @@ import models
Base.metadata.create_all(bind=engine) # falls Tabelle noch nicht existiert Base.metadata.create_all(bind=engine) # falls Tabelle noch nicht existiert
from crud.user import create_user, get_user_by_email, update_user, delete_user, verify_password from crud.user import get_users, get_user_by_email, update_user, delete_user
db = SessionLocal() db = SessionLocal()
# Erstellen # Erstellen
u = create_user(db, email="2test@example.com", password="test1234", role="admin") u = get_users(db)
print("Erstellt:", u.id, u.email, u.role) for user in u:
print(f"User: {user.email}, role: {user.role}, created_at: {user.created_at}")
# Lesen
found = get_user_by_email(db, "1test@example.com")
print(found)
print("Gefunden:", found.email if found else "nicht gefunden")
# Passwort prüfen
print("Passwort korrekt:", verify_password("test1234", found.password))
print("Falsches Passwort:", verify_password("falsch", found.password))
# Updaten
updated = update_user(db, u.id, email="neu@example.com")
print("Aktualisiert:", updated.email)
# Löschen
success = delete_user(db, u.id)
print("Gelöscht:", success)
# Prüfen, ob wirklich weg
gone = get_user_by_email(db, "neu@example.com")
print("Nach Löschen noch da?:", gone)
db.close() db.close()