Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c8c4cfb77 | ||
|
|
2275ff1a71 | ||
|
|
726f5491ff |
@@ -15,6 +15,7 @@ function plural(n: number, one: string, many: string) {
|
|||||||
// allen Zielen. Mobil: Kopfleiste (Menü, Titel, Einstellungen), unten die
|
// allen Zielen. Mobil: Kopfleiste (Menü, Titel, Einstellungen), unten die
|
||||||
// TabBar mit den fünf wichtigsten Zielen; das Menü blendet dieselbe
|
// TabBar mit den fünf wichtigsten Zielen; das Menü blendet dieselbe
|
||||||
// Seitenleiste als Schublade ein. Umgeschaltet wird nur per CSS (app.css).
|
// Seitenleiste als Schublade ein. Umgeschaltet wird nur per CSS (app.css).
|
||||||
|
// Außer der Startseite haben alle Seiten den "zurück zum Feed"-Knopf.
|
||||||
export function Layout() {
|
export function Layout() {
|
||||||
const path = useLocation().pathname;
|
const path = useLocation().pathname;
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
@@ -55,10 +56,12 @@ export function Layout() {
|
|||||||
<span className="icon-btn mobile-only" aria-hidden="true"><span className="icon" /></span>
|
<span className="icon-btn mobile-only" aria-hidden="true"><span className="icon" /></span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{path === "/" && (
|
{path === "/" ? (
|
||||||
<p id="stats" className="tagline">
|
<p id="stats" className="tagline">
|
||||||
Ohne Datenverlust seit {plural(days, "Tag", "Tagen")}
|
Ohne Datenverlust seit {plural(days, "Tag", "Tagen")}
|
||||||
</p>
|
</p>
|
||||||
|
) : (
|
||||||
|
<div id="headerbar"><Link className="button" to="/">zurück zum Feed</Link></div>
|
||||||
)}
|
)}
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ type Target = { title: string; icon?: ReactNode; to: string; end?: boolean };
|
|||||||
|
|
||||||
// Bereiche, die es noch nicht gibt: Route und Platzhalter-Seite bestehen,
|
// Bereiche, die es noch nicht gibt: Route und Platzhalter-Seite bestehen,
|
||||||
// in der Navigation sind sie bis dahin ausgeblendet.
|
// in der Navigation sind sie bis dahin ausgeblendet.
|
||||||
const unfinished = new Set(["/search", "/notifications", "/chats", "/settings"]);
|
const unfinished = new Set(["/search", "/notifications", "/chats"]);
|
||||||
|
|
||||||
export const isReady = (to: string) => !unfinished.has(to);
|
export const isReady = (to: string) => !unfinished.has(to);
|
||||||
|
|
||||||
|
|||||||
+65
-6
@@ -52,6 +52,9 @@ header {
|
|||||||
padding: 0.5rem 0;
|
padding: 0.5rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* "zurück zum Feed" unter dem Titel, auf allen Seiten außer dem Feed. */
|
||||||
|
#headerbar a { background-color: white; }
|
||||||
|
|
||||||
/* Klick auf die Überschrift führt zurück zum Feed. */
|
/* Klick auf die Überschrift führt zurück zum Feed. */
|
||||||
#topbar > a {
|
#topbar > a {
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
@@ -207,6 +210,8 @@ h2 {
|
|||||||
border-bottom: 1px solid black;
|
border-bottom: 1px solid black;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#headerbar { padding-bottom: 0.3rem; }
|
||||||
|
|
||||||
#topbar {
|
#topbar {
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
}
|
}
|
||||||
@@ -408,7 +413,6 @@ img.avatar {
|
|||||||
}
|
}
|
||||||
|
|
||||||
img.avatar-sm { width: var(--avatar-sm); height: var(--avatar-sm); }
|
img.avatar-sm { width: var(--avatar-sm); height: var(--avatar-sm); }
|
||||||
img.avatar-lg { width: 72px; height: 72px; }
|
|
||||||
|
|
||||||
/* Byline mit kleinem Avatar neben Name + Zeitstempel. Einheitliche 1rem für die
|
/* Byline mit kleinem Avatar neben Name + Zeitstempel. Einheitliche 1rem für die
|
||||||
ganze Meta-Zeile (Name, Datum, Repost-Cooldown), damit nichts größer rausfällt
|
ganze Meta-Zeile (Name, Datum, Repost-Cooldown), damit nichts größer rausfällt
|
||||||
@@ -430,13 +434,68 @@ img.avatar-lg { width: 72px; height: 72px; }
|
|||||||
/* Melden steht rechts in der Byline. */
|
/* Melden steht rechts in der Byline. */
|
||||||
.byline .report { margin-left: auto; }
|
.byline .report { margin-left: auto; }
|
||||||
|
|
||||||
/* Profilkopf: großer Avatar links neben Name und "Mitglied seit". */
|
/* --- Profil ---
|
||||||
.profile-head {
|
Header-Bild im Format 3:1 über die ganze Spalte; ohne Bild ein schwarzer
|
||||||
display: flex;
|
Balken. Der Avatar ragt zur Hälfte in den Header hinein, ein weißer Rand
|
||||||
align-items: center;
|
mit schwarzer Kante trennt ihn vom Bild. */
|
||||||
gap: 0.75rem;
|
#profile { padding: 0; }
|
||||||
|
|
||||||
|
.profile-header {
|
||||||
|
aspect-ratio: 3 / 1;
|
||||||
|
background-color: black;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.profile-header img {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
margin: 0;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-body { padding: 0 0.5rem 0.5rem; }
|
||||||
|
|
||||||
|
.profile-top {
|
||||||
|
--avatar-xl: 112px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-end;
|
||||||
|
margin-top: calc(var(--avatar-xl) / -2);
|
||||||
|
}
|
||||||
|
|
||||||
|
img.avatar-xl {
|
||||||
|
width: var(--avatar-xl);
|
||||||
|
height: var(--avatar-xl);
|
||||||
|
border: 4px solid white;
|
||||||
|
outline: 1px solid black;
|
||||||
|
}
|
||||||
|
|
||||||
|
#profile-name {
|
||||||
|
display: block;
|
||||||
|
margin: 0.4rem 0 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bio {
|
||||||
|
margin: 0.4rem 0;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
#profile-info { margin: 0.4rem 0 0; }
|
||||||
|
|
||||||
|
/* Bearbeiten-Bereich des Eigentümers unter dem Profilkopf. */
|
||||||
|
.profile-edit {
|
||||||
|
border-top: 1px solid black;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-edit h3, #settings h3 { margin: 0.8rem 0 0; }
|
||||||
|
.profile-edit form { display: inline-block; width: 100%; }
|
||||||
|
.counter { margin-left: auto; font-size: 1rem; }
|
||||||
|
|
||||||
/* --- Thread-Strich ---
|
/* --- Thread-Strich ---
|
||||||
Der Strich ist ein eigenes Flex-Geschwister links neben dem Inhalt, nicht
|
Der Strich ist ein eigenes Flex-Geschwister links neben dem Inhalt, nicht
|
||||||
eine Border am Inhalt selbst. align-self: stretch macht ihn exakt so hoch
|
eine Border am Inhalt selbst. align-self: stretch macht ihn exakt so hoch
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { StatsPage } from "./pages/StatsPage";
|
|||||||
import { ResetPage } from "./pages/ResetPage";
|
import { ResetPage } from "./pages/ResetPage";
|
||||||
import { MePage, Placeholder } from "./pages/Placeholder";
|
import { MePage, Placeholder } from "./pages/Placeholder";
|
||||||
import { DocPage } from "./pages/DocPage";
|
import { DocPage } from "./pages/DocPage";
|
||||||
|
import { SettingsPage } from "./pages/SettingsPage";
|
||||||
import "./app.css";
|
import "./app.css";
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
@@ -39,7 +40,7 @@ const router = createBrowserRouter([
|
|||||||
{ path: "/search", element: <Placeholder title="Suche" /> },
|
{ path: "/search", element: <Placeholder title="Suche" /> },
|
||||||
{ path: "/notifications", element: <Placeholder title="Benachrichtigungen" /> },
|
{ path: "/notifications", element: <Placeholder title="Benachrichtigungen" /> },
|
||||||
{ path: "/chats", element: <Placeholder title="Chats" /> },
|
{ path: "/chats", element: <Placeholder title="Chats" /> },
|
||||||
{ path: "/settings", element: <Placeholder title="Einstellungen" /> },
|
{ path: "/settings", element: <SettingsPage /> },
|
||||||
{ path: "/impressum", element: <DocPage name="impressum" /> },
|
{ path: "/impressum", element: <DocPage name="impressum" /> },
|
||||||
{ path: "/datenschutz", element: <DocPage name="datenschutz" /> },
|
{ path: "/datenschutz", element: <DocPage name="datenschutz" /> },
|
||||||
{ path: "/beitragsordnung", element: <DocPage name="beitragsordnung" /> },
|
{ path: "/beitragsordnung", element: <DocPage name="beitragsordnung" /> },
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useMe } from "../auth";
|
|||||||
import { AuthBox } from "../components/AuthBox";
|
import { AuthBox } from "../components/AuthBox";
|
||||||
|
|
||||||
// Placeholder steht für Bereiche, die noch eigene Projekte sind (Suche,
|
// Placeholder steht für Bereiche, die noch eigene Projekte sind (Suche,
|
||||||
// Benachrichtigungen, Chats, Einstellungen).
|
// Benachrichtigungen, Chats).
|
||||||
export function Placeholder({ title }: { title: string }) {
|
export function Placeholder({ title }: { title: string }) {
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { useNavigate } from "react-router";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useAuthChanged, useMe } from "../auth";
|
||||||
|
import { useFormAction } from "../useFormAction";
|
||||||
|
import { AuthBox } from "../components/AuthBox";
|
||||||
|
|
||||||
|
// SettingsPage: Kontoeinstellungen (Name, Passwort, Löschen). Profilbild, Header und
|
||||||
|
// Beschreibung bearbeitet man auf dem eigenen Profil.
|
||||||
|
export function SettingsPage() {
|
||||||
|
const me = useMe();
|
||||||
|
if (!me.isSuccess) return null;
|
||||||
|
if (!me.data) return <AuthBox />;
|
||||||
|
return <Settings />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Settings() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const authChanged = useAuthChanged();
|
||||||
|
|
||||||
|
// Der neue Name taucht auch in den Beitragskarten auf -> Feeds, Profile und
|
||||||
|
// das eigene Konto neu laden.
|
||||||
|
const refresh = () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ["feed"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["thread"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["profile"] });
|
||||||
|
return authChanged();
|
||||||
|
};
|
||||||
|
|
||||||
|
const rename = useFormAction<{ username: string }>("/user/rename", "Umbenennen fehlgeschlagen.", async (form) => {
|
||||||
|
form.reset();
|
||||||
|
await refresh();
|
||||||
|
});
|
||||||
|
const password = useFormAction("/user/password", "Ändern fehlgeschlagen.", (form) => form.reset());
|
||||||
|
const del = useFormAction("/user/delete", "Löschen fehlgeschlagen.", async () => {
|
||||||
|
await refresh();
|
||||||
|
navigate("/");
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section id="settings">
|
||||||
|
<h2>Einstellungen</h2>
|
||||||
|
|
||||||
|
<h3>Name ändern</h3>
|
||||||
|
<form id="rename-form" onSubmit={rename.onSubmit}>
|
||||||
|
<input name="user" type="text" placeholder="Neuer Nutzername" autoComplete="username" />{" "}
|
||||||
|
<button type="submit" disabled={rename.busy}>Namen ändern</button>
|
||||||
|
</form>
|
||||||
|
<p className="msg" id="rename-msg">{rename.msg}</p>
|
||||||
|
{rename.ok && <p className="muted">Name geändert.</p>}
|
||||||
|
|
||||||
|
<h3>Passwort ändern</h3>
|
||||||
|
<form id="password-form" onSubmit={password.onSubmit}>
|
||||||
|
<input name="pass" type="password" placeholder="Bisheriges Passwort" autoComplete="current-password" />{" "}
|
||||||
|
<input name="pass1" type="password" placeholder="Neues Passwort" autoComplete="new-password" />{" "}
|
||||||
|
<input name="pass2" type="password" placeholder="Neues Passwort wiederholen" autoComplete="new-password" />{" "}
|
||||||
|
<button type="submit" disabled={password.busy}>Passwort ändern</button>
|
||||||
|
</form>
|
||||||
|
<p className="msg" id="password-msg">{password.msg}</p>
|
||||||
|
{password.ok && <p className="muted">Passwort geändert. Andere Geräte sind abgemeldet.</p>}
|
||||||
|
|
||||||
|
<h3>Konto löschen</h3>
|
||||||
|
<form
|
||||||
|
id="delete-form"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
if (confirm("Konto wirklich unwiderruflich löschen?")) del.onSubmit(e);
|
||||||
|
else e.preventDefault();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p className="muted">Löscht dein Konto samt Beiträgen und Votes unwiderruflich.</p>{" "}
|
||||||
|
<input name="pass1" type="password" placeholder="Passwort bestätigen" autoComplete="current-password" />{" "}
|
||||||
|
<button type="submit" disabled={del.busy}>Konto endgültig löschen</button>
|
||||||
|
</form>
|
||||||
|
<p className="msg" id="delete-msg">{del.msg}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,27 +1,33 @@
|
|||||||
import { useState, type FormEvent } from "react";
|
import { useState } from "react";
|
||||||
import { useNavigate, useParams } from "react-router";
|
import { useParams } from "react-router";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { api, errMsg } from "../api";
|
import { api, errMsg } from "../api";
|
||||||
import { useAuthChanged, useMe } from "../auth";
|
import { useAuthChanged, useMe } from "../auth";
|
||||||
import { avatarUrl } from "../format";
|
import { avatarUrl, linkify } from "../format";
|
||||||
|
import { useFormAction } from "../useFormAction";
|
||||||
import { Feed } from "../components/Feed";
|
import { Feed } from "../components/Feed";
|
||||||
import type { Profile } from "../types";
|
import type { Profile } from "../types";
|
||||||
|
|
||||||
|
// Muss zu maxBioRunes im Server passen (internal/httpapi/users.go).
|
||||||
|
const maxBio = 300;
|
||||||
|
|
||||||
// Beim Wechsel zu einem anderen Profil frisch anfangen (Meldungen, Formulare).
|
// Beim Wechsel zu einem anderen Profil frisch anfangen (Meldungen, Formulare).
|
||||||
export function UserPage() {
|
export function UserPage() {
|
||||||
const { username = "" } = useParams();
|
const { username = "" } = useParams();
|
||||||
return <ProfileView key={username} username={username} />;
|
return <ProfileView key={username} username={username} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProfileView: Header-Bild (ohne Bild ein schwarzer Balken), darauf
|
||||||
|
// überlappend der Avatar, darunter Name, Beschreibung, Meta-Zeile und die
|
||||||
|
// Beiträge. Der Eigentümer bearbeitet Bilder und Beschreibung direkt hier;
|
||||||
|
// Name und Konto stehen unter /settings.
|
||||||
function ProfileView({ username }: { username: string }) {
|
function ProfileView({ username }: { username: string }) {
|
||||||
const profile = useQuery({
|
const profile = useQuery({
|
||||||
queryKey: ["profile", username],
|
queryKey: ["profile", username],
|
||||||
queryFn: () => api.get<Profile>(`/u/${encodeURIComponent(username)}/info`),
|
queryFn: () => api.get<Profile>(`/u/${encodeURIComponent(username)}/info`),
|
||||||
});
|
});
|
||||||
const me = useMe().data;
|
const me = useMe().data;
|
||||||
// Nach einem Upload das neue Bild sofort zeigen: Zeitstempel am URL
|
const [editing, setEditing] = useState(false);
|
||||||
// umgeht den Browser-Cache.
|
|
||||||
const [avatarBust, setAvatarBust] = useState("");
|
|
||||||
|
|
||||||
const info = profile.data;
|
const info = profile.data;
|
||||||
let name = "";
|
let name = "";
|
||||||
@@ -32,23 +38,26 @@ function ProfileView({ username }: { username: string }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section id="profile">
|
<section id="profile">
|
||||||
<div className="profile-head">
|
<div className="profile-header">
|
||||||
<img
|
{info?.header && <img src={`/${info.header}`} alt="" />}
|
||||||
id="profile-avatar"
|
</div>
|
||||||
className="avatar avatar-lg"
|
<div className="profile-body">
|
||||||
src={avatarUrl(info?.avatar ?? "") + avatarBust}
|
<div className="profile-top">
|
||||||
alt=""
|
<img id="profile-avatar" className="avatar avatar-xl" src={avatarUrl(info?.avatar ?? "")} alt="" />
|
||||||
/>
|
{isOwner && (
|
||||||
<div>
|
<button onClick={() => setEditing(!editing)} aria-expanded={editing}>
|
||||||
|
{editing ? "Fertig" : "Profil bearbeiten"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<h2 id="profile-name">{name}</h2>
|
<h2 id="profile-name">{name}</h2>
|
||||||
|
{info?.bio && <p className="bio">{linkify(info.bio)}</p>}
|
||||||
<p id="profile-info" className="muted">
|
<p id="profile-info" className="muted">
|
||||||
{info && `Mitglied seit ${new Date(info.created_at * 1000).toLocaleDateString("de-DE")}`}
|
{info &&
|
||||||
|
`Mitglied seit ${new Date(info.created_at * 1000).toLocaleDateString("de-DE")} · ` +
|
||||||
|
`${info.entries} ${info.entries === 1 ? "Beitrag" : "Beiträge"}`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
{isOwner && editing && info && <ProfileEdit info={info} />}
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="settings" hidden={!isOwner}>
|
|
||||||
{isOwner && <Settings onAvatar={() => setAvatarBust(`?t=${Date.now()}`)} />}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{info && (
|
{info && (
|
||||||
@@ -62,81 +71,64 @@ function ProfileView({ username }: { username: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// useFormAction verdrahtet ein Einstellungsformular: POST auf path, bei Erfolg
|
// ProfileEdit: Header-Bild, Profilbild und Beschreibung, nur für den
|
||||||
// onSuccess mit Formular und Antwort, bei Fehler die Meldung unter dem Formular.
|
// Eigentümer.
|
||||||
function useFormAction<T>(path: string, fallback: string, onSuccess: (form: HTMLFormElement, data: T) => void) {
|
function ProfileEdit({ info }: { info: Profile }) {
|
||||||
const m = useMutation({ mutationFn: (fd: FormData) => api.post<T>(path, fd) });
|
|
||||||
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
const form = e.currentTarget;
|
|
||||||
m.mutate(new FormData(form), { onSuccess: (data) => onSuccess(form, data) });
|
|
||||||
};
|
|
||||||
return { onSubmit, busy: m.isPending, msg: m.isError ? errMsg(m.error, fallback) : "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Settings: nur für den Eigentümer.
|
|
||||||
function Settings({ onAvatar }: { onAvatar: () => void }) {
|
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const navigate = useNavigate();
|
|
||||||
const authChanged = useAuthChanged();
|
const authChanged = useAuthChanged();
|
||||||
|
const [bio, setBio] = useState(info.bio);
|
||||||
|
|
||||||
// Neues Bild und neuer Name tauchen auch in den Beitragskarten auf -> die
|
const refreshProfile = () => qc.invalidateQueries({ queryKey: ["profile"] });
|
||||||
// Feeds und das eigene Konto neu laden.
|
// Das Profilbild taucht auch in den Beitragskarten und im eigenen Konto auf.
|
||||||
const refresh = () => {
|
const refreshAvatar = () => {
|
||||||
qc.invalidateQueries({ queryKey: ["feed"] });
|
qc.invalidateQueries({ queryKey: ["feed"] });
|
||||||
qc.invalidateQueries({ queryKey: ["thread"] });
|
qc.invalidateQueries({ queryKey: ["thread"] });
|
||||||
qc.invalidateQueries({ queryKey: ["profile"] });
|
refreshProfile();
|
||||||
return authChanged();
|
return authChanged();
|
||||||
};
|
};
|
||||||
|
|
||||||
const avatar = useFormAction<{ avatar: string }>("/user/avatar", "Hochladen fehlgeschlagen.", (form) => {
|
const header = useFormAction("/user/header", "Hochladen fehlgeschlagen.", (form) => {
|
||||||
form.reset();
|
form.reset();
|
||||||
onAvatar();
|
refreshProfile();
|
||||||
refresh();
|
|
||||||
});
|
});
|
||||||
const rename = useFormAction<{ username: string }>("/user/rename", "Umbenennen fehlgeschlagen.", async (_form, data) => {
|
const removeHeader = useFormAction("/user/header/remove", "Entfernen fehlgeschlagen.", refreshProfile);
|
||||||
await refresh();
|
const avatar = useFormAction("/user/avatar", "Hochladen fehlgeschlagen.", (form) => {
|
||||||
navigate(`/u/${encodeURIComponent(data.username)}`);
|
form.reset();
|
||||||
});
|
refreshAvatar();
|
||||||
const del = useFormAction("/user/delete", "Löschen fehlgeschlagen.", async () => {
|
|
||||||
await refresh();
|
|
||||||
navigate("/");
|
|
||||||
});
|
});
|
||||||
|
const saveBio = useFormAction("/user/bio", "Speichern fehlgeschlagen.", refreshProfile);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<div className="profile-edit">
|
||||||
<h2>Einstellungen</h2>
|
<h3>Header-Bild</h3>
|
||||||
<details>
|
<form id="header-form" onSubmit={header.onSubmit}>
|
||||||
<summary>Profilbild ändern</summary>
|
<input name="header" type="file" accept="image/*" />{" "}
|
||||||
|
<button type="submit" disabled={header.busy}>Bild hochladen</button>
|
||||||
|
</form>
|
||||||
|
{info.header && (
|
||||||
|
<form onSubmit={removeHeader.onSubmit}>
|
||||||
|
<button type="submit" disabled={removeHeader.busy}>Header-Bild entfernen</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<p className="msg">{header.msg || removeHeader.msg}</p>
|
||||||
|
|
||||||
|
<h3>Profilbild</h3>
|
||||||
<form id="avatar-form" onSubmit={avatar.onSubmit}>
|
<form id="avatar-form" onSubmit={avatar.onSubmit}>
|
||||||
<input name="avatar" type="file" accept="image/*" />{" "}
|
<input name="avatar" type="file" accept="image/*" />{" "}
|
||||||
<button type="submit" disabled={avatar.busy}>Bild hochladen</button>
|
<button type="submit" disabled={avatar.busy}>Bild hochladen</button>
|
||||||
</form>
|
</form>
|
||||||
<p className="msg" id="avatar-msg">{avatar.msg}</p>
|
<p className="msg" id="avatar-msg">{avatar.msg}</p>
|
||||||
</details>
|
|
||||||
<details>
|
<h3>Beschreibung</h3>
|
||||||
<summary>Name ändern</summary>
|
<form id="bio-form" onSubmit={saveBio.onSubmit}>
|
||||||
<form id="rename-form" onSubmit={rename.onSubmit}>
|
<textarea name="bio" rows={4} maxLength={maxBio} value={bio} onChange={(e) => setBio(e.target.value)} />
|
||||||
<input name="user" type="text" placeholder="Neuer Nutzername" autoComplete="username" />{" "}
|
<div className="row">
|
||||||
<button type="submit" disabled={rename.busy}>Namen ändern</button>
|
<button type="submit" disabled={saveBio.busy}>Text speichern</button>
|
||||||
|
{saveBio.ok && bio === info.bio && <span className="muted">Gespeichert.</span>}
|
||||||
|
<span className="muted counter">{[...bio].length}/{maxBio}</span>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
<p className="msg" id="rename-msg">{rename.msg}</p>
|
<p className="msg">{saveBio.msg}</p>
|
||||||
</details>
|
</div>
|
||||||
<details>
|
|
||||||
<summary>Konto löschen</summary>
|
|
||||||
<form
|
|
||||||
id="delete-form"
|
|
||||||
onSubmit={(e) => {
|
|
||||||
if (confirm("Konto wirklich unwiderruflich löschen?")) del.onSubmit(e);
|
|
||||||
else e.preventDefault();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<p className="muted">Löscht dein Konto samt Beiträgen und Votes unwiderruflich.</p>{" "}
|
|
||||||
<input name="pass1" type="password" placeholder="Passwort bestätigen" autoComplete="current-password" />{" "}
|
|
||||||
<button type="submit" disabled={del.busy}>Konto endgültig löschen</button>
|
|
||||||
</form>
|
|
||||||
<p className="msg" id="delete-msg">{del.msg}</p>
|
|
||||||
</details>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,11 @@ export interface Profile {
|
|||||||
username: string;
|
username: string;
|
||||||
created_at: number;
|
created_at: number;
|
||||||
avatar: string;
|
avatar: string;
|
||||||
|
// Header-Bild, '' = schwarzer Balken.
|
||||||
|
header: string;
|
||||||
|
bio: string;
|
||||||
|
// Anzahl nicht gelöschter Beiträge.
|
||||||
|
entries: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StatsDetail {
|
export interface StatsDetail {
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import type { FormEvent } from "react";
|
||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { api, errMsg } from "./api";
|
||||||
|
|
||||||
|
// useFormAction verdrahtet ein Einstellungsformular: POST auf path, bei Erfolg
|
||||||
|
// onSuccess mit Formular und Antwort, bei Fehler die Meldung unter dem Formular.
|
||||||
|
// ok meldet, dass der letzte Versand geklappt hat.
|
||||||
|
export function useFormAction<T>(path: string, fallback: string, onSuccess: (form: HTMLFormElement, data: T) => void) {
|
||||||
|
const m = useMutation({ mutationFn: (fd: FormData) => api.post<T>(path, fd) });
|
||||||
|
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const form = e.currentTarget;
|
||||||
|
m.mutate(new FormData(form), { onSuccess: (data) => onSuccess(form, data) });
|
||||||
|
};
|
||||||
|
return { onSubmit, busy: m.isPending, msg: m.isError ? errMsg(m.error, fallback) : "", ok: m.isSuccess };
|
||||||
|
}
|
||||||
@@ -136,3 +136,37 @@ func (s *Store) UID(ctx context.Context, username string) (int64, error) {
|
|||||||
}
|
}
|
||||||
return uid, nil
|
return uid, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ErrWrongPassword: das bisherige Passwort beim Ändern stimmt nicht.
|
||||||
|
var ErrWrongPassword = apperr.Forbidden("auth.bad_password", "Das bisherige Passwort ist falsch.").At("pass")
|
||||||
|
|
||||||
|
// ChangePassword setzt ein neues Passwort, wenn current das bisherige ist.
|
||||||
|
// Alle anderen Sessions des Nutzers enden; keepSession (die eigene) bleibt.
|
||||||
|
func (s *Store) ChangePassword(ctx context.Context, uid int64, current, password, keepSession string) error {
|
||||||
|
var old []byte
|
||||||
|
err := s.db.QueryRowContext(ctx, `SELECT password FROM account WHERE uid = $1`, uid).Scan(&old)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrUserNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("passwort lesen: %w", err)
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword(old, []byte(current)) != nil {
|
||||||
|
return ErrWrongPassword
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("passwort hashen: %w", err)
|
||||||
|
}
|
||||||
|
return database.InTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||||
|
if _, err := tx.ExecContext(ctx, `UPDATE account SET password = $1 WHERE uid = $2`, hash, uid); err != nil {
|
||||||
|
return fmt.Errorf("passwort setzen: %w", err)
|
||||||
|
}
|
||||||
|
// Wer das alte Passwort kannte, soll mit dessen Sessions nicht drin bleiben.
|
||||||
|
if _, err := tx.ExecContext(ctx,
|
||||||
|
`DELETE FROM session WHERE uid = $1 AND value <> $2`, uid, keepSession); err != nil {
|
||||||
|
return fmt.Errorf("sessions beenden: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ CREATE TABLE IF NOT EXISTS account (
|
|||||||
last_login BIGINT,
|
last_login BIGINT,
|
||||||
avatar TEXT NOT NULL DEFAULT ''
|
avatar TEXT NOT NULL DEFAULT ''
|
||||||
);
|
);
|
||||||
|
-- Profil: Beschreibung (Klartext) und Header-Bild, '' = keins.
|
||||||
|
ALTER TABLE account ADD COLUMN IF NOT EXISTS bio TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE account ADD COLUMN IF NOT EXISTS header TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS session (
|
CREATE TABLE IF NOT EXISTS session (
|
||||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"image"
|
||||||
|
"image/png"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type profileJSON struct {
|
||||||
|
Header string `json:"header"`
|
||||||
|
Bio string `json:"bio"`
|
||||||
|
Entries int64 `json:"entries"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProfile(t *testing.T, srv *testServer, username string) profileJSON {
|
||||||
|
t.Helper()
|
||||||
|
resp, err := http.Get(srv.URL + "/api/u/" + username + "/info")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
var p profileJSON
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
|
||||||
|
t.Fatalf("decode profil: %v", err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// uploadImage schickt ein kleines PNG als Feld field an urlStr.
|
||||||
|
func uploadImage(t *testing.T, c *http.Client, urlStr, field string) int {
|
||||||
|
t.Helper()
|
||||||
|
var body bytes.Buffer
|
||||||
|
mw := multipart.NewWriter(&body)
|
||||||
|
fw, err := mw.CreateFormFile(field, "bild.png")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := png.Encode(fw, image.NewRGBA(image.Rect(0, 0, 30, 10))); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mw.Close()
|
||||||
|
req, err := http.NewRequest(http.MethodPost, urlStr, &body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
resp := do(t, c, req)
|
||||||
|
resp.Body.Close()
|
||||||
|
return resp.StatusCode
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileBio(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
srv := newTestServer(t)
|
||||||
|
alice := registerAndLogin(t, srv, "alice")
|
||||||
|
createEntry(t, alice, srv, post("eins"))
|
||||||
|
createEntry(t, alice, srv, post("zwei"))
|
||||||
|
|
||||||
|
if got := postStatus(t, newClient(t), srv.URL+"/api/user/bio", url.Values{"bio": {"x"}}); got != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("bio ohne login: erwartet 401, bekam %d", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Zeilenumbrüche werden normalisiert, Überlänge runenweise gekürzt.
|
||||||
|
long := " Zeile 1\r\nZeile 2 " + strings.Repeat("ö", 400)
|
||||||
|
if got := postStatus(t, alice, srv.URL+"/api/user/bio", url.Values{"bio": {long}}); got != http.StatusOK {
|
||||||
|
t.Fatalf("bio: erwartet 200, bekam %d", got)
|
||||||
|
}
|
||||||
|
p := getProfile(t, srv, "alice")
|
||||||
|
if !strings.HasPrefix(p.Bio, "Zeile 1\nZeile 2 ö") || len([]rune(p.Bio)) != maxBioRunes {
|
||||||
|
t.Fatalf("bio falsch gespeichert: %q (%d Runen)", p.Bio, len([]rune(p.Bio)))
|
||||||
|
}
|
||||||
|
if p.Entries != 2 {
|
||||||
|
t.Fatalf("beitragszahl: erwartet 2, bekam %d", p.Entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leer löscht die Beschreibung.
|
||||||
|
postStatus(t, alice, srv.URL+"/api/user/bio", url.Values{"bio": {" "}})
|
||||||
|
if p := getProfile(t, srv, "alice"); p.Bio != "" {
|
||||||
|
t.Fatalf("bio nicht gelöscht: %q", p.Bio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileHeader(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
srv := newTestServer(t)
|
||||||
|
alice := registerAndLogin(t, srv, "alice")
|
||||||
|
exists := func(path string) bool {
|
||||||
|
_, err := os.Stat(filepath.Join(srv.Media.Root, filepath.FromSlash(path)))
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := postStatus(t, alice, srv.URL+"/api/user/header", url.Values{}); got != http.StatusBadRequest {
|
||||||
|
t.Fatalf("header ohne bild: erwartet 400, bekam %d", got)
|
||||||
|
}
|
||||||
|
if got := uploadImage(t, alice, srv.URL+"/api/user/header", "header"); got != http.StatusOK {
|
||||||
|
t.Fatalf("header: erwartet 200, bekam %d", got)
|
||||||
|
}
|
||||||
|
first := getProfile(t, srv, "alice").Header
|
||||||
|
if first == "" || !exists(first) {
|
||||||
|
t.Fatalf("header nicht gespeichert: %q", first)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ein neues Bild ersetzt das alte, die alte Datei verschwindet.
|
||||||
|
uploadImage(t, alice, srv.URL+"/api/user/header", "header")
|
||||||
|
second := getProfile(t, srv, "alice").Header
|
||||||
|
if second == first || exists(first) || !exists(second) {
|
||||||
|
t.Fatalf("header nicht ersetzt: alt %q, neu %q", first, second)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := postStatus(t, alice, srv.URL+"/api/user/header/remove", url.Values{}); got != http.StatusOK {
|
||||||
|
t.Fatalf("header entfernen: erwartet 200, bekam %d", got)
|
||||||
|
}
|
||||||
|
if p := getProfile(t, srv, "alice"); p.Header != "" || exists(second) {
|
||||||
|
t.Fatalf("header nicht entfernt: %q", p.Header)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kontolöschung räumt das Header-Bild mit ab.
|
||||||
|
uploadImage(t, alice, srv.URL+"/api/user/header", "header")
|
||||||
|
third := getProfile(t, srv, "alice").Header
|
||||||
|
postStatus(t, alice, srv.URL+"/api/user/delete", url.Values{"pass1": {"supersecret1"}})
|
||||||
|
if exists(third) {
|
||||||
|
t.Fatal("header nach kontolöschung noch vorhanden")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChangePassword: falsches bisheriges oder ungültiges neues Passwort wird
|
||||||
|
// abgewiesen; danach gilt nur das neue, die eigene Session bleibt, andere
|
||||||
|
// enden.
|
||||||
|
func TestChangePassword(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
srv := newTestServer(t)
|
||||||
|
alice := registerAndLogin(t, srv, "alice")
|
||||||
|
other := newClient(t)
|
||||||
|
postForm(t, other, srv.URL+"/api/auth/login", url.Values{
|
||||||
|
"user": {"alice"}, "pass": {"supersecret1"}, "timeout": {"86400"},
|
||||||
|
}).Body.Close()
|
||||||
|
|
||||||
|
change := func(cur, pass1, pass2 string) int {
|
||||||
|
return postStatus(t, alice, srv.URL+"/api/user/password",
|
||||||
|
url.Values{"pass": {cur}, "pass1": {pass1}, "pass2": {pass2}})
|
||||||
|
}
|
||||||
|
if got := change("falsch", "neuesgeheim1", "neuesgeheim1"); got != http.StatusForbidden {
|
||||||
|
t.Fatalf("falsches bisheriges: erwartet 403, bekam %d", got)
|
||||||
|
}
|
||||||
|
if got := change("supersecret1", "kurz", "kurz"); got != http.StatusBadRequest {
|
||||||
|
t.Fatalf("zu kurz: erwartet 400, bekam %d", got)
|
||||||
|
}
|
||||||
|
if got := change("supersecret1", "neuesgeheim1", "anders12345"); got != http.StatusBadRequest {
|
||||||
|
t.Fatalf("ungleich: erwartet 400, bekam %d", got)
|
||||||
|
}
|
||||||
|
if got := change("supersecret1", "neuesgeheim1", "neuesgeheim1"); got != http.StatusOK {
|
||||||
|
t.Fatalf("ändern: erwartet 200, bekam %d", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := getStatus(t, alice, srv.URL+"/api/user/info"); got != http.StatusOK {
|
||||||
|
t.Fatalf("eigene session: erwartet 200, bekam %d", got)
|
||||||
|
}
|
||||||
|
if got := getStatus(t, other, srv.URL+"/api/user/info"); got != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("andere session: erwartet 401, bekam %d", got)
|
||||||
|
}
|
||||||
|
login := func(pass string) int {
|
||||||
|
return postStatus(t, newClient(t), srv.URL+"/api/auth/login",
|
||||||
|
url.Values{"user": {"alice"}, "pass": {pass}, "timeout": {"86400"}})
|
||||||
|
}
|
||||||
|
if got := login("supersecret1"); got != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("altes passwort: erwartet 401, bekam %d", got)
|
||||||
|
}
|
||||||
|
if got := login("neuesgeheim1"); got != http.StatusOK {
|
||||||
|
t.Fatalf("neues passwort: erwartet 200, bekam %d", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -112,7 +112,13 @@ func (s *Server) apiRoutes(r chi.Router) {
|
|||||||
r.Post("/entry/{pid}/delete", s.api(s.handleDeleteEntry))
|
r.Post("/entry/{pid}/delete", s.api(s.handleDeleteEntry))
|
||||||
r.Get("/user/info", s.api(s.handleUserInfo))
|
r.Get("/user/info", s.api(s.handleUserInfo))
|
||||||
r.Post("/user/rename", s.api(s.handleUserRename))
|
r.Post("/user/rename", s.api(s.handleUserRename))
|
||||||
|
// Gedrosselt wie der Login: wer eine fremde Session hat, soll das
|
||||||
|
// bisherige Passwort nicht durchprobieren können.
|
||||||
|
r.With(s.limitByIP(20, time.Minute)).Post("/user/password", s.api(s.handleUserPassword))
|
||||||
r.Post("/user/avatar", s.api(s.handleSetAvatar))
|
r.Post("/user/avatar", s.api(s.handleSetAvatar))
|
||||||
|
r.Post("/user/header", s.api(s.handleSetHeader))
|
||||||
|
r.Post("/user/header/remove", s.api(s.handleRemoveHeader))
|
||||||
|
r.Post("/user/bio", s.api(s.handleSetBio))
|
||||||
r.Post("/user/delete", s.api(s.handleUserDelete))
|
r.Post("/user/delete", s.api(s.handleUserDelete))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+94
-18
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
@@ -14,6 +15,7 @@ import (
|
|||||||
"kver/internal/account"
|
"kver/internal/account"
|
||||||
"kver/internal/apperr"
|
"kver/internal/apperr"
|
||||||
"kver/internal/database"
|
"kver/internal/database"
|
||||||
|
"kver/internal/runes"
|
||||||
)
|
)
|
||||||
|
|
||||||
// notFoundOr bildet sql.ErrNoRows auf account.ErrUserNotFound ab, alles
|
// notFoundOr bildet sql.ErrNoRows auf account.ErrUserNotFound ab, alles
|
||||||
@@ -25,13 +27,18 @@ func notFoundOr(err error) error {
|
|||||||
return apperr.Internal(err)
|
return apperr.Internal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// maxBioRunes begrenzt die Profilbeschreibung.
|
||||||
|
const maxBioRunes = 300
|
||||||
|
|
||||||
func (s *Server) handleUserPage(w http.ResponseWriter, r *http.Request) error {
|
func (s *Server) handleUserPage(w http.ResponseWriter, r *http.Request) error {
|
||||||
username := chi.URLParam(r, "username")
|
username := chi.URLParam(r, "username")
|
||||||
var uid, createdAt int64
|
var uid, createdAt, entries int64
|
||||||
var avatar string
|
var avatar, header, bio string
|
||||||
if err := s.DB.QueryRowContext(r.Context(),
|
if err := s.DB.QueryRowContext(r.Context(),
|
||||||
`SELECT uid, created_at, avatar FROM account WHERE username = $1`, username,
|
`SELECT uid, created_at, avatar, header, bio,
|
||||||
).Scan(&uid, &createdAt, &avatar); err != nil {
|
(SELECT COUNT(*) FROM entry e WHERE e.uid = a.uid AND e.deleted = 0)
|
||||||
|
FROM account a WHERE username = $1`, username,
|
||||||
|
).Scan(&uid, &createdAt, &avatar, &header, &bio, &entries); err != nil {
|
||||||
return notFoundOr(err)
|
return notFoundOr(err)
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
@@ -39,6 +46,9 @@ func (s *Server) handleUserPage(w http.ResponseWriter, r *http.Request) error {
|
|||||||
"username": username,
|
"username": username,
|
||||||
"created_at": createdAt,
|
"created_at": createdAt,
|
||||||
"avatar": avatar,
|
"avatar": avatar,
|
||||||
|
"header": header,
|
||||||
|
"bio": bio,
|
||||||
|
"entries": entries,
|
||||||
})
|
})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -96,27 +106,84 @@ func (s *Server) handleUserRename(w http.ResponseWriter, r *http.Request) error
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handleUserPassword ändert das Passwort des eingeloggten Nutzers: pass ist
|
||||||
|
// das bisherige, pass1/pass2 das neue wie bei der Registrierung. Die eigene
|
||||||
|
// Session bleibt, alle anderen enden.
|
||||||
|
func (s *Server) handleUserPassword(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
pass1 := r.FormValue("pass1")
|
||||||
|
fields := map[string]string{}
|
||||||
|
account.CheckNewPassword(pass1, r.FormValue("pass2"), fields)
|
||||||
|
if len(fields) > 0 {
|
||||||
|
return errInvalidForm.WithFields(fields)
|
||||||
|
}
|
||||||
|
sess, _ := s.session(r)
|
||||||
|
if err := s.accounts.ChangePassword(r.Context(), currentUID(r), r.FormValue("pass"), pass1, sess.Value); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, status{"ok"})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleSetBio setzt die Profilbeschreibung des eingeloggten Nutzers; leer
|
||||||
|
// löscht sie. Klartext, Links macht erst das Frontend klickbar.
|
||||||
|
func (s *Server) handleSetBio(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
bio := strings.ReplaceAll(r.FormValue("bio"), "\r\n", "\n")
|
||||||
|
bio = runes.Truncate(strings.TrimSpace(bio), maxBioRunes)
|
||||||
|
if _, err := s.DB.ExecContext(r.Context(),
|
||||||
|
`UPDATE account SET bio = $1 WHERE uid = $2`, bio, currentUID(r)); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"bio": bio})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Profilbilder: Spalte in account, zugleich Name des Formularfelds. Die
|
||||||
|
// Abfragen stehen fest im Code, damit kein Spaltenname in SQL zusammengesetzt
|
||||||
|
// wird. Der Self-Join liefert das bisherige Bild (prev sieht die Zeile vor dem
|
||||||
|
// UPDATE), ohne eigene Abfrage davor.
|
||||||
|
var setImageQuery = map[string]string{
|
||||||
|
"avatar": `UPDATE account a SET avatar = $1 FROM account prev
|
||||||
|
WHERE a.uid = $2 AND prev.uid = a.uid RETURNING prev.avatar`,
|
||||||
|
"header": `UPDATE account a SET header = $1 FROM account prev
|
||||||
|
WHERE a.uid = $2 AND prev.uid = a.uid RETURNING prev.header`,
|
||||||
|
}
|
||||||
|
|
||||||
// handleSetAvatar speichert ein hochgeladenes Profilbild des eingeloggten
|
// handleSetAvatar speichert ein hochgeladenes Profilbild des eingeloggten
|
||||||
// Nutzers und ersetzt ein eventuell vorhandenes.
|
// Nutzers und ersetzt ein eventuell vorhandenes.
|
||||||
func (s *Server) handleSetAvatar(w http.ResponseWriter, r *http.Request) error {
|
func (s *Server) handleSetAvatar(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
return s.setImage(w, r, "avatar")
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleSetHeader speichert das Header-Bild des Profils.
|
||||||
|
func (s *Server) handleSetHeader(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
return s.setImage(w, r, "header")
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleRemoveHeader entfernt das Header-Bild; das Profil zeigt dann den
|
||||||
|
// schwarzen Balken.
|
||||||
|
func (s *Server) handleRemoveHeader(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
old, err := s.replaceImage(r.Context(), "header", "", currentUID(r))
|
||||||
|
if err != nil {
|
||||||
|
return notFoundOr(err)
|
||||||
|
}
|
||||||
|
s.removeMedia(old)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"header": ""})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) setImage(w http.ResponseWriter, r *http.Request, field string) error {
|
||||||
if err := parseUpload(w, r); err != nil {
|
if err := parseUpload(w, r); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fh := formFile(r, "avatar")
|
fh := formFile(r, field)
|
||||||
if fh == nil {
|
if fh == nil {
|
||||||
return apperr.Invalid("avatar.missing", "Kein Bild hochgeladen.").At("avatar")
|
return apperr.Invalid(field+".missing", "Kein Bild hochgeladen.").At(field)
|
||||||
}
|
}
|
||||||
stored, err := s.saveUpload(fh, "avatar")
|
stored, err := s.saveUpload(fh, field)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Der Self-Join liefert das bisherige Bild (prev sieht die Zeile vor dem
|
old, err := s.replaceImage(r.Context(), field, stored, currentUID(r))
|
||||||
// UPDATE), ohne eigene Abfrage davor.
|
|
||||||
var old string
|
|
||||||
err = s.DB.QueryRowContext(r.Context(),
|
|
||||||
`UPDATE account a SET avatar = $1 FROM account prev
|
|
||||||
WHERE a.uid = $2 AND prev.uid = a.uid
|
|
||||||
RETURNING prev.avatar`, stored, currentUID(r)).Scan(&old)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.removeMedia(stored)
|
s.removeMedia(stored)
|
||||||
return notFoundOr(err)
|
return notFoundOr(err)
|
||||||
@@ -124,10 +191,17 @@ func (s *Server) handleSetAvatar(w http.ResponseWriter, r *http.Request) error {
|
|||||||
if old != stored {
|
if old != stored {
|
||||||
s.removeMedia(old)
|
s.removeMedia(old)
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"avatar": stored})
|
writeJSON(w, http.StatusOK, map[string]string{field: stored})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// replaceImage setzt die Bildspalte field und liefert den bisherigen Pfad.
|
||||||
|
func (s *Server) replaceImage(ctx context.Context, field, path string, uid int64) (string, error) {
|
||||||
|
var old string
|
||||||
|
err := s.DB.QueryRowContext(ctx, setImageQuery[field], path, uid).Scan(&old)
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
|
||||||
// handleUserDelete löscht den eingeloggten Account dauerhaft, nach
|
// handleUserDelete löscht den eingeloggten Account dauerhaft, nach
|
||||||
// Bestätigung durch das Passwort (Formularfeld pass1). Sessions, Reset-Links
|
// Bestätigung durch das Passwort (Formularfeld pass1). Sessions, Reset-Links
|
||||||
// und Votes werden in einer Transaktion mitgelöscht; die eigenen Beiträge
|
// und Votes werden in einer Transaktion mitgelöscht; die eigenen Beiträge
|
||||||
@@ -161,13 +235,15 @@ func (s *Server) handleUserDelete(w http.ResponseWriter, r *http.Request) error
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// userMedia liefert die Mediendateien eines Nutzers: Beitragsbilder und das
|
// userMedia liefert die Mediendateien eines Nutzers: Beitragsbilder, Profil-
|
||||||
// Profilbild.
|
// und Header-Bild.
|
||||||
func (s *Server) userMedia(ctx context.Context, uid int64) ([]string, error) {
|
func (s *Server) userMedia(ctx context.Context, uid int64) ([]string, error) {
|
||||||
rows, err := s.DB.QueryContext(ctx,
|
rows, err := s.DB.QueryContext(ctx,
|
||||||
`SELECT filepath FROM entry WHERE uid = $1 AND filepath <> ''
|
`SELECT filepath FROM entry WHERE uid = $1 AND filepath <> ''
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT avatar FROM account WHERE uid = $1 AND avatar <> ''`, uid)
|
SELECT avatar FROM account WHERE uid = $1 AND avatar <> ''
|
||||||
|
UNION ALL
|
||||||
|
SELECT header FROM account WHERE uid = $1 AND header <> ''`, uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("medien lesen: %w", err)
|
return nil, fmt.Errorf("medien lesen: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-2
@@ -128,12 +128,16 @@ TOR-Anfragen auf `create` werden mit `403 tor.blocked` abgewiesen.
|
|||||||
|
|
||||||
| Methode | Pfad | Auth | Request | Erfolg |
|
| Methode | Pfad | Auth | Request | Erfolg |
|
||||||
|---------|------|------|---------|--------|
|
|---------|------|------|---------|--------|
|
||||||
| GET | `/api/u/{username}/info` | – | – | `200 {"uid","username","created_at","avatar"}` |
|
| GET | `/api/u/{username}/info` | – | – | `200 {"uid","username","created_at","avatar","header","bio","entries"}`; `header` leer = kein Header-Bild, `entries` = nicht gelöschte Beiträge |
|
||||||
| GET | `/api/u/{username}/feed/{page}` | – | – | `200 [Entry]`: alle Beiträge inkl. Antworten, chronologisch |
|
| GET | `/api/u/{username}/feed/{page}` | – | – | `200 [Entry]`: alle Beiträge inkl. Antworten, chronologisch |
|
||||||
| GET | `/api/user/info` | ✓ | – | `200 {"uid","username","created_at","last_login","avatar"}` |
|
| GET | `/api/user/info` | ✓ | – | `200 {"uid","username","created_at","last_login","avatar"}` |
|
||||||
| POST | `/api/user/rename` | ✓ | `user` | `200 {"username"}`; vergeben: `409 user.name_taken` |
|
| POST | `/api/user/rename` | ✓ | `user` | `200 {"username"}`; vergeben: `409 user.name_taken` |
|
||||||
|
| POST | `/api/user/password` | ✓ | `pass`, `pass1`, `pass2` | `200 {"status":"ok"}`; beendet alle anderen Sessions; bisheriges Passwort falsch: `403 auth.bad_password`, neues ungültig: `400 user.invalid`; Rate-Limit pro IP |
|
||||||
| POST | `/api/user/avatar` | ✓ | multipart: `avatar` | `200 {"avatar"}` |
|
| POST | `/api/user/avatar` | ✓ | multipart: `avatar` | `200 {"avatar"}` |
|
||||||
| POST | `/api/user/delete` | ✓ | `pass1` | `200 {"status":"deleted"}`, löscht Konto, Beiträge, Votes, Sessions; falsches Passwort: `403 auth.bad_password` |
|
| POST | `/api/user/header` | ✓ | multipart: `header` | `200 {"header"}`, ersetzt ein vorhandenes Header-Bild |
|
||||||
|
| POST | `/api/user/header/remove` | ✓ | – | `200 {"header":""}` |
|
||||||
|
| POST | `/api/user/bio` | ✓ | `bio` | `200 {"bio"}`: Klartext, getrimmt, höchstens 300 Zeichen (länger wird gekürzt); leer löscht |
|
||||||
|
| POST | `/api/user/delete` | ✓ | `pass1` | `200 {"status":"deleted"}`, löscht Konto, Beiträge, Votes, Sessions, Profil- und Header-Bild; falsches Passwort: `403 auth.bad_password` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -48,7 +48,8 @@ githooks` läuft das nach jedem Commit automatisch im Hintergrund (Log:
|
|||||||
| `src/Layout.tsx` | Seitenrahmen: Kopf (mobil mit Menü und Einstellungen), Schublade |
|
| `src/Layout.tsx` | Seitenrahmen: Kopf (mobil mit Menü und Einstellungen), Schublade |
|
||||||
| `src/Nav.tsx` | Seitenleiste (alle Ziele) und mobile TabBar (fünf wichtigste); Icons von lucide-react, die Rechtstexte ohne Icon |
|
| `src/Nav.tsx` | Seitenleiste (alle Ziele) und mobile TabBar (fünf wichtigste); Icons von lucide-react, die Rechtstexte ohne Icon |
|
||||||
| `src/docs/*.html` | Rechtstexte (Impressum, Datenschutz, Beitragsordnung) |
|
| `src/docs/*.html` | Rechtstexte (Impressum, Datenschutz, Beitragsordnung) |
|
||||||
| `src/pages/*` | Startseite, Thread, Profil, Statistik, Rechtstexte (`DocPage.tsx`); `Placeholder.tsx` für Suche, Benachrichtigungen, Chats, Einstellungen und die Profil-Weiche `/me` |
|
| `src/pages/*` | Startseite, Thread, Profil (Header, Beschreibung, Bearbeiten für den Eigentümer), Einstellungen (Name, Passwort, Konto löschen), Statistik, Rechtstexte (`DocPage.tsx`); `Placeholder.tsx` für Suche, Benachrichtigungen, Chats und die Profil-Weiche `/me` |
|
||||||
|
| `src/useFormAction.ts` | Formular-POST mit Fehlermeldung (Profil, Einstellungen) |
|
||||||
| `src/components/*` | Feed, Beitragskarte, Votes, Repost, Login, Beitrag verfassen |
|
| `src/components/*` | Feed, Beitragskarte, Votes, Repost, Login, Beitrag verfassen |
|
||||||
|
|
||||||
Seitenrouten des Clients (`/`, `/e/:pid`, `/u/:username`, `/stats`, `/reset`,
|
Seitenrouten des Clients (`/`, `/e/:pid`, `/u/:username`, `/stats`, `/reset`,
|
||||||
@@ -61,8 +62,8 @@ auch in `pageRoutes()` (`internal/httpapi/server.go`) stehen, sonst liefert ein
|
|||||||
Ab 900 px Fensterbreite steht links die Seitenleiste mit allen Zielen (Icon +
|
Ab 900 px Fensterbreite steht links die Seitenleiste mit allen Zielen (Icon +
|
||||||
Titel). Darunter: Kopfleiste mit Menü, Titel und Einstellungsrad, unten die
|
Titel). Darunter: Kopfleiste mit Menü, Titel und Einstellungsrad, unten die
|
||||||
TabBar mit Feed, Suche, Benachrichtigungen, Chats und Profil; das Menü blendet
|
TabBar mit Feed, Suche, Benachrichtigungen, Chats und Profil; das Menü blendet
|
||||||
die Seitenleiste als Schublade ein. Suche, Benachrichtigungen, Chats und
|
die Seitenleiste als Schublade ein. Suche, Benachrichtigungen und Chats sind
|
||||||
Einstellungen sind noch Platzhalter und deshalb ausgeblendet (`unfinished` in
|
noch Platzhalter und deshalb ausgeblendet (`unfinished` in
|
||||||
`src/Nav.tsx`); ihre Routen bestehen weiter. Umgeschaltet wird nur per CSS
|
`src/Nav.tsx`); ihre Routen bestehen weiter. Umgeschaltet wird nur per CSS
|
||||||
(`app.css`, Abschnitt Navigation).
|
(`app.css`, Abschnitt Navigation).
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user