Konten: Handle und Anzeigename getrennt
Für @-Erwähnungen in Beiträgen braucht es eindeutige, gut tippbare Namen. Der Handle (a-z, 0-9, _, 3-20 Zeichen, klein) ist jetzt der Bezeichner für Login, Profil- und Chat-URLs und Suche; der Anzeigename ist freier Unicode-Text ohne Eindeutigkeit. Beides ist in den Einstellungen änderbar. Bestehende Konten migriert der Server beim Start selbst: der alte Name wird Anzeigename, der Handle wird daraus abgeleitet (deutsche Umlaute, andere Schriften per go-unidecode, Chinesisch als Pinyin). Namen, die sich direkt übernehmen lassen, werden zuerst vergeben, damit Kollisionen mit Zahl-Zusatz niemandem seinen echten Namen wegnehmen. Der alte Name bleibt als legacy_name; `kver handles` listet, wer sich nun anders anmelden muss. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -61,7 +61,7 @@ func registerAndLogin(t *testing.T, srv *testServer, username string) *http.Clie
|
||||
c := newClient(t)
|
||||
|
||||
resp := postForm(t, c, srv.URL+"/api/auth/newuser", url.Values{
|
||||
"user": {username}, "pass1": {"supersecret1"}, "pass2": {"supersecret1"},
|
||||
"handle": {username}, "pass1": {"supersecret1"}, "pass2": {"supersecret1"},
|
||||
})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
@@ -151,12 +151,12 @@ func TestFeedEmptyThenPopulated(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var posts []struct {
|
||||
Content string `json:"content"`
|
||||
Username string `json:"username"`
|
||||
Content string `json:"content"`
|
||||
Handle string `json:"handle"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&posts)
|
||||
resp.Body.Close()
|
||||
if len(posts) != 1 || posts[0].Content != "hallo welt" || posts[0].Username != "alice" {
|
||||
if len(posts) != 1 || posts[0].Content != "hallo welt" || posts[0].Handle != "alice" {
|
||||
t.Fatalf("unerwarteter Feed: %+v", posts)
|
||||
}
|
||||
}
|
||||
@@ -280,7 +280,7 @@ type threadEntry struct {
|
||||
ReplyCount int64 `json:"reply_count"`
|
||||
Deleted int64 `json:"deleted"`
|
||||
Content string `json:"content"`
|
||||
Username string `json:"username"`
|
||||
Handle string `json:"handle"`
|
||||
Latest *struct {
|
||||
Entry threadEntry `json:"entry"`
|
||||
Skipped int64 `json:"skipped"`
|
||||
@@ -593,7 +593,7 @@ func TestSoftDelete(t *testing.T) {
|
||||
|
||||
// Root bleibt als [deleted]-Platzhalter; die Antwort verwaist nicht.
|
||||
tv := getThread(t, srv, root)
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Username != "" {
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Handle != "" {
|
||||
t.Fatalf("deleted entry nicht anonymisiert: %+v", tv.Entry)
|
||||
}
|
||||
if len(tv.Replies) != 1 || tv.Replies[0].PID != answer {
|
||||
@@ -666,41 +666,43 @@ func TestReport(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameUser(t *testing.T) {
|
||||
func TestSetHandle(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
registerAndLogin(t, srv, "bob")
|
||||
|
||||
// Zu kurz -> 400.
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/rename", url.Values{"user": {"ab"}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("zu kurz: erwartet 400, bekam %d", resp.StatusCode)
|
||||
for _, tt := range []struct {
|
||||
handle string
|
||||
want int
|
||||
}{
|
||||
{"ab", http.StatusBadRequest},
|
||||
{"jörg", http.StatusBadRequest},
|
||||
{"alice", http.StatusBadRequest}, // unverändert
|
||||
{"@BOB", http.StatusConflict},
|
||||
} {
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/handle", url.Values{"handle": {tt.handle}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Errorf("%q: erwartet %d, bekam %d", tt.handle, tt.want, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Bereits vergeben -> 409.
|
||||
resp = postForm(t, alice, srv.URL+"/api/user/rename", url.Values{"user": {"bob"}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("vergeben: erwartet 409, bekam %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Gültig -> 200 + neuer Name.
|
||||
resp = postForm(t, alice, srv.URL+"/api/user/rename", url.Values{"user": {"alice2"}})
|
||||
// Gültig -> 200 + neuer Handle, klein geschrieben.
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/handle", url.Values{"handle": {"Alice2"}})
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("rename: erwartet 200, bekam %d", resp.StatusCode)
|
||||
t.Fatalf("handle: erwartet 200, bekam %d", resp.StatusCode)
|
||||
}
|
||||
var out struct {
|
||||
Username string `json:"username"`
|
||||
Handle string `json:"handle"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&out)
|
||||
if out.Username != "alice2" {
|
||||
t.Fatalf("erwarteter Name alice2, bekam %q", out.Username)
|
||||
if out.Handle != "alice2" {
|
||||
t.Fatalf("erwarteter Handle alice2, bekam %q", out.Handle)
|
||||
}
|
||||
|
||||
// Profil unter dem neuen Namen erreichbar, alter Name weg.
|
||||
// Profil unter dem neuen Handle erreichbar, alter weg.
|
||||
r2, _ := http.Get(srv.URL + "/api/u/alice2/info")
|
||||
r2.Body.Close()
|
||||
if r2.StatusCode != http.StatusOK {
|
||||
@@ -749,7 +751,7 @@ func TestDeleteUser(t *testing.T) {
|
||||
|
||||
// alices Beitrag bleibt als [deleted]-Platzhalter; bobs Antwort verwaist nicht.
|
||||
tv := getThread(t, srv, root)
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Username != "" {
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Handle != "" {
|
||||
t.Fatalf("beitrag nach konto-löschung nicht soft-deleted: %+v", tv.Entry)
|
||||
}
|
||||
if len(tv.Replies) != 1 || tv.Replies[0].PID != answer {
|
||||
@@ -1026,3 +1028,43 @@ func TestBlockTOREntry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisplayName(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
c := newClient(t)
|
||||
resp := postForm(t, c, srv.URL+"/api/auth/newuser", url.Values{
|
||||
"handle": {"@Joerg"}, "display_name": {" Jörg 🌻 "},
|
||||
"pass1": {"supersecret1"}, "pass2": {"supersecret1"},
|
||||
})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("register: status %d", resp.StatusCode)
|
||||
}
|
||||
// Login ignoriert Groß-/Kleinschreibung und "@" im Handle.
|
||||
resp = postForm(t, c, srv.URL+"/api/auth/login", url.Values{
|
||||
"user": {"@JOERG"}, "pass": {"supersecret1"}, "timeout": {"86400"},
|
||||
})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("login: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
var u user
|
||||
if getAs(t, c, srv.URL+"/api/user/info", &u); u != (user{"joerg", "Jörg 🌻"}) {
|
||||
t.Errorf("/user/info: %+v", u)
|
||||
}
|
||||
|
||||
resp = postForm(t, c, srv.URL+"/api/user/display_name", url.Values{"display_name": {""}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("display_name: status %d", resp.StatusCode)
|
||||
}
|
||||
if getAs(t, c, srv.URL+"/api/u/JOERG/info", &u); u != (user{"joerg", ""}) {
|
||||
t.Errorf("/u/JOERG/info: %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,10 +28,11 @@ var (
|
||||
|
||||
// chatJSON ist ein Gespräch in der Übersicht.
|
||||
type chatJSON struct {
|
||||
Username string `json:"username"`
|
||||
Avatar string `json:"avatar"`
|
||||
LastAt int64 `json:"last_at"`
|
||||
Unread int `json:"unread"`
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Avatar string `json:"avatar"`
|
||||
LastAt int64 `json:"last_at"`
|
||||
Unread int `json:"unread"`
|
||||
}
|
||||
|
||||
// handleChats liefert die Gespräche des eingeloggten Nutzers, das mit der
|
||||
@@ -39,14 +40,14 @@ type chatJSON struct {
|
||||
func (s *Server) handleChats(w http.ResponseWriter, r *http.Request) error {
|
||||
uid := currentUID(r)
|
||||
rows, err := s.DB.QueryContext(r.Context(),
|
||||
`SELECT a.username, a.avatar, m.last_at, m.unread
|
||||
`SELECT a.handle, a.display_name, a.avatar, m.last_at, m.unread
|
||||
FROM (SELECT CASE WHEN sender = $1 THEN recipient ELSE sender END AS other,
|
||||
MAX(created_at) AS last_at,
|
||||
COUNT(*) FILTER (WHERE recipient = $1 AND read_at = 0) AS unread
|
||||
FROM message WHERE (sender = $1 OR recipient = $1) AND created_at >= $2
|
||||
GROUP BY 1) m
|
||||
JOIN account a ON a.uid = m.other
|
||||
ORDER BY m.last_at DESC, a.username`, uid, s.expiredBefore())
|
||||
ORDER BY m.last_at DESC, a.handle`, uid, s.expiredBefore())
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
@@ -54,7 +55,7 @@ func (s *Server) handleChats(w http.ResponseWriter, r *http.Request) error {
|
||||
chats := []chatJSON{}
|
||||
for rows.Next() {
|
||||
var c chatJSON
|
||||
if err := rows.Scan(&c.Username, &c.Avatar, &c.LastAt, &c.Unread); err != nil {
|
||||
if err := rows.Scan(&c.Handle, &c.DisplayName, &c.Avatar, &c.LastAt, &c.Unread); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
chats = append(chats, c)
|
||||
@@ -77,7 +78,7 @@ type messageJSON struct {
|
||||
|
||||
// partner liefert die uid des Gesprächspartners aus der URL.
|
||||
func (s *Server) partner(r *http.Request) (int64, error) {
|
||||
other, err := s.uidOf(r.Context(), chi.URLParam(r, "username"))
|
||||
other, err := s.accounts.UID(r.Context(), chi.URLParam(r, "handle"))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func TestChats(t *testing.T) {
|
||||
t.Fatalf("senden: %d %s", st, code)
|
||||
}
|
||||
var list chatsJSON
|
||||
if getAs(t, bob, srv.URL+"/api/chats", &list); len(list.Chats) != 1 || list.Chats[0].Username != "alice" || list.Chats[0].Unread != 1 {
|
||||
if getAs(t, bob, srv.URL+"/api/chats", &list); len(list.Chats) != 1 || list.Chats[0].Handle != "alice" || list.Chats[0].Unread != 1 {
|
||||
t.Fatalf("bobs chats: %+v", list)
|
||||
}
|
||||
var got messagesJSON
|
||||
|
||||
@@ -26,7 +26,8 @@ type Entry struct {
|
||||
Deleted int64 `json:"deleted"`
|
||||
BumpCount int64 `json:"bump_count"`
|
||||
LastBump int64 `json:"last_bump"`
|
||||
Username string `json:"username"`
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Avatar string `json:"avatar"`
|
||||
// Preview ist die fertige Vorschau des ersten Links.
|
||||
Preview *linkpreview.Preview `json:"preview,omitempty"`
|
||||
@@ -68,7 +69,7 @@ const entrySelect = `
|
||||
SELECT e.pid, e.uid, e.created_at, e.content, e.filepath,
|
||||
e.reply_to, e.reply_count, e.last_activity, e.deleted,
|
||||
e.bump_count, e.last_bump,
|
||||
COALESCE(u.username, ''), COALESCE(u.avatar, ''),
|
||||
COALESCE(u.handle, ''), COALESCE(u.display_name, ''), COALESCE(u.avatar, ''),
|
||||
COALESCE(lp.url, ''), COALESCE(lp.kind, ''), COALESCE(lp.title, ''),
|
||||
COALESCE(lp.site, ''), COALESCE(lp.thumb, ''), COALESCE(lp.status, '')
|
||||
FROM entry e LEFT JOIN account u ON u.uid = e.uid
|
||||
@@ -84,7 +85,7 @@ func scanEntry(row interface{ Scan(...any) error }) (Entry, error) {
|
||||
var status string
|
||||
err := row.Scan(&e.PID, &e.UID, &e.CreatedAt, &e.Content, &e.Filepath,
|
||||
&e.ReplyTo, &e.ReplyCount, &e.LastActivity, &e.Deleted,
|
||||
&e.BumpCount, &e.LastBump, &e.Username, &e.Avatar,
|
||||
&e.BumpCount, &e.LastBump, &e.Handle, &e.DisplayName, &e.Avatar,
|
||||
&p.URL, &p.Kind, &p.Title, &p.Site, &p.Thumb, &status)
|
||||
switch {
|
||||
case p.Title != "" && status != linkpreview.StatusNone:
|
||||
@@ -162,7 +163,7 @@ func (s *Server) handleFeed(w http.ResponseWriter, r *http.Request) error {
|
||||
// handleUserFeed liefert alle Beiträge eines Nutzers chronologisch, Antworten
|
||||
// eingeschlossen.
|
||||
func (s *Server) handleUserFeed(w http.ResponseWriter, r *http.Request) error {
|
||||
uid, err := s.accounts.UID(r.Context(), chi.URLParam(r, "username"))
|
||||
uid, err := s.accounts.UID(r.Context(), chi.URLParam(r, "handle"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
@@ -60,20 +59,10 @@ func scanKey(sc interface{ Scan(...any) error }) (keyJSON, error) {
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// uidOf liefert die uid zu username.
|
||||
func (s *Server) uidOf(ctx context.Context, username string) (int64, error) {
|
||||
var uid int64
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT uid FROM account WHERE username = $1`, username).Scan(&uid)
|
||||
if err != nil {
|
||||
return 0, notFoundOr(err)
|
||||
}
|
||||
return uid, nil
|
||||
}
|
||||
|
||||
// handleUserKey liefert den aktuellen Schlüssel eines Nutzers. Ein
|
||||
// verlorener Schlüssel wird nicht mehr ausgeliefert.
|
||||
func (s *Server) handleUserKey(w http.ResponseWriter, r *http.Request) error {
|
||||
uid, err := s.uidOf(r.Context(), chi.URLParam(r, "username"))
|
||||
uid, err := s.accounts.UID(r.Context(), chi.URLParam(r, "handle"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
// tippt. POST statt GET, damit das Token nicht in der URL und damit im Log
|
||||
// steht.
|
||||
func (s *Server) handleResetCheck(w http.ResponseWriter, r *http.Request) error {
|
||||
username, err := s.accounts.ResetUsername(r.Context(), r.FormValue("token"))
|
||||
handle, err := s.accounts.ResetHandle(r.Context(), r.FormValue("token"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"username": username})
|
||||
writeJSON(w, http.StatusOK, map[string]string{"handle": handle})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) error {
|
||||
if len(fields) > 0 {
|
||||
return errInvalidForm.WithFields(fields)
|
||||
}
|
||||
uid, username, err := s.accounts.ResetPassword(r.Context(), r.FormValue("token"), pass1)
|
||||
uid, handle, err := s.accounts.ResetPassword(r.Context(), r.FormValue("token"), pass1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -42,6 +42,6 @@ func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) error {
|
||||
if err := s.startSession(w, r, uid); err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"username": username})
|
||||
writeJSON(w, http.StatusOK, map[string]string{"handle": handle})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func (s *Server) filterPage(r *http.Request, f filter) ([]Entry, error) {
|
||||
}
|
||||
|
||||
// parseFilter liest einen Filter aus den Query-Parametern: q (Freitext,
|
||||
// Wörter durch Leerzeichen getrennt), user (Nutzername), tag (ein oder
|
||||
// Wörter durch Leerzeichen getrennt), user (Handle, @ optional), tag (ein oder
|
||||
// mehrere Hashtags, # optional), roots=1 (keine Antworten).
|
||||
func (s *Server) parseFilter(r *http.Request) (filter, error) {
|
||||
q := r.URL.Query()
|
||||
@@ -98,7 +98,7 @@ func (s *Server) parseFilter(r *http.Request) (filter, error) {
|
||||
if len(f.Words)+len(f.Tags) > maxTerms {
|
||||
return f, errQueryTooLong
|
||||
}
|
||||
if name := strings.TrimPrefix(strings.TrimSpace(q.Get("user")), "@"); name != "" {
|
||||
if name := strings.TrimSpace(q.Get("user")); name != "" {
|
||||
uid, err := s.accounts.UID(r.Context(), name)
|
||||
if err != nil {
|
||||
return f, err
|
||||
|
||||
@@ -103,9 +103,9 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
// offene Endpunkt kein Spam-Kanal wird.
|
||||
r.With(s.limitByIP(10, time.Minute)).Post("/entry/{pid}/report", s.api(s.handleReport))
|
||||
|
||||
r.Get("/u/{username}/info", s.api(s.handleUserPage))
|
||||
r.Get("/u/{username}/feed/{page}", s.api(s.handleUserFeed))
|
||||
r.Get("/u/{username}/key", s.api(s.handleUserKey))
|
||||
r.Get("/u/{handle}/info", s.api(s.handleUserPage))
|
||||
r.Get("/u/{handle}/feed/{page}", s.api(s.handleUserFeed))
|
||||
r.Get("/u/{handle}/key", s.api(s.handleUserKey))
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(s.requireAuth)
|
||||
@@ -115,7 +115,8 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
r.Post("/entry/{pid}/edit", s.api(s.handleEditEntry))
|
||||
r.Post("/entry/{pid}/delete", s.api(s.handleDeleteEntry))
|
||||
r.Get("/user/info", s.api(s.handleUserInfo))
|
||||
r.Post("/user/rename", s.api(s.handleUserRename))
|
||||
r.Post("/user/handle", s.api(s.handleSetHandle))
|
||||
r.Post("/user/display_name", s.api(s.handleSetDisplayName))
|
||||
// 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))
|
||||
@@ -128,8 +129,8 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
r.Get("/user/keys/secret", s.api(s.handleKeySecrets))
|
||||
// Direktnachrichten (notes/chats.md); Senden gedrosselt gegen Spam.
|
||||
r.Get("/chats", s.api(s.handleChats))
|
||||
r.Get("/chats/{username}", s.api(s.handleChat))
|
||||
r.With(s.limitByIP(60, time.Minute)).Post("/chats/{username}", s.api(s.handleSendMessage))
|
||||
r.Get("/chats/{handle}", s.api(s.handleChat))
|
||||
r.With(s.limitByIP(60, time.Minute)).Post("/chats/{handle}", s.api(s.handleSendMessage))
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(s.limitByIP(20, time.Minute))
|
||||
r.Post("/user/key", s.api(s.handleSetKey))
|
||||
@@ -146,8 +147,8 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
func (s *Server) pageRoutes(r chi.Router) {
|
||||
r.With(s.trackImpression).Get("/", serveApp)
|
||||
r.With(s.trackImpression).Get("/e/{pid}", serveApp)
|
||||
r.With(s.trackImpression).Get("/u/{username}", serveApp)
|
||||
r.Get("/chats/{username}", serveApp)
|
||||
r.With(s.trackImpression).Get("/u/{handle}", serveApp)
|
||||
r.Get("/chats/{handle}", serveApp)
|
||||
r.Get("/stats", serveApp)
|
||||
// Das Reset-Token steht im Fragment (#...) und erreicht den Server über
|
||||
// diese Route nie, siehe account/reset.go.
|
||||
|
||||
+15
-14
@@ -34,8 +34,7 @@ var (
|
||||
// errBadCredentials ist für "Nutzer existiert nicht" und "Passwort falsch"
|
||||
// absichtlich derselbe Fehler -- sonst wird der Endpunkt zum
|
||||
// Nutzernamen-Orakel.
|
||||
errBadCredentials = apperr.Unauth("auth.bad_credentials", "Nutzername oder Passwort ist falsch.")
|
||||
errNameShort = apperr.Invalid("user.name_short", "Der Nutzername ist zu kurz.").At("user")
|
||||
errBadCredentials = apperr.Unauth("auth.bad_credentials", "Handle oder Passwort ist falsch.")
|
||||
errInvalidForm = apperr.Invalid("user.invalid", "Die Angaben sind unvollständig oder ungültig.")
|
||||
)
|
||||
|
||||
@@ -75,14 +74,15 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) error {
|
||||
writeJSON(w, http.StatusOK, status{"already_logged_in"})
|
||||
return nil
|
||||
}
|
||||
username := account.SanitizeUsername(r.FormValue("user"))
|
||||
if len(username) < account.MinNameLen {
|
||||
return errNameShort
|
||||
// Angemeldet wird mit dem Handle, Groß-/Kleinschreibung und "@" egal.
|
||||
handle := account.NormalizeHandle(r.FormValue("user"))
|
||||
if !account.ValidHandle(handle) {
|
||||
return errBadCredentials
|
||||
}
|
||||
var uid int64
|
||||
var hash []byte
|
||||
err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT uid, password FROM account WHERE username = $1`, username).Scan(&uid, &hash)
|
||||
`SELECT uid, password FROM account WHERE handle = $1`, handle).Scan(&uid, &hash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errBadCredentials
|
||||
}
|
||||
@@ -189,25 +189,26 @@ func (s *Server) handleSessionInfo(w http.ResponseWriter, r *http.Request) error
|
||||
// handleNewUser sammelt alle Validierungsfehler ein, statt beim ersten
|
||||
// abzubrechen -- der Nutzer soll nicht Feld für Feld durchprobieren müssen.
|
||||
func (s *Server) handleNewUser(w http.ResponseWriter, r *http.Request) error {
|
||||
username := account.SanitizeUsername(r.FormValue("user"))
|
||||
handle := account.NormalizeHandle(r.FormValue("handle"))
|
||||
displayName := account.CleanDisplayName(r.FormValue("display_name"))
|
||||
pass1 := r.FormValue("pass1")
|
||||
fields := map[string]string{}
|
||||
if len(username) < account.MinNameLen {
|
||||
fields["user"] = errNameShort.Msg
|
||||
} else if taken, err := s.accounts.NameTaken(r.Context(), username); err != nil {
|
||||
if !account.ValidHandle(handle) {
|
||||
fields["handle"] = account.ErrHandleInvalid.Msg
|
||||
} else if taken, err := s.accounts.HandleTaken(r.Context(), handle); err != nil {
|
||||
return apperr.Internal(err)
|
||||
} else if taken {
|
||||
fields["user"] = account.ErrUsernameTaken.Msg
|
||||
fields["handle"] = account.ErrHandleTaken.Msg
|
||||
}
|
||||
account.CheckNewPassword(pass1, r.FormValue("pass2"), fields)
|
||||
if len(fields) > 0 {
|
||||
return errInvalidForm.WithFields(fields)
|
||||
}
|
||||
// Rennen zwischen Vorab-Prüfung und INSERT: der UNIQUE-Constraint greift,
|
||||
// Create meldet dann ErrUsernameTaken.
|
||||
if _, err := s.accounts.Create(r.Context(), username, pass1); err != nil {
|
||||
// Create meldet dann ErrHandleTaken.
|
||||
if _, err := s.accounts.Create(r.Context(), handle, displayName, pass1); err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"username": username})
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"handle": handle, "display_name": displayName})
|
||||
return nil
|
||||
}
|
||||
|
||||
+49
-47
@@ -31,24 +31,24 @@ func notFoundOr(err error) error {
|
||||
const maxBioRunes = 300
|
||||
|
||||
func (s *Server) handleUserPage(w http.ResponseWriter, r *http.Request) error {
|
||||
username := chi.URLParam(r, "username")
|
||||
var uid, createdAt, entries int64
|
||||
var avatar, header, bio string
|
||||
var handle, displayName, avatar, header, bio string
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT uid, created_at, avatar, header, bio,
|
||||
`SELECT uid, handle, display_name, created_at, avatar, header, bio,
|
||||
(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 {
|
||||
FROM account a WHERE handle = $1`, account.NormalizeHandle(chi.URLParam(r, "handle")),
|
||||
).Scan(&uid, &handle, &displayName, &createdAt, &avatar, &header, &bio, &entries); err != nil {
|
||||
return notFoundOr(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"uid": uid,
|
||||
"username": username,
|
||||
"created_at": createdAt,
|
||||
"avatar": avatar,
|
||||
"header": header,
|
||||
"bio": bio,
|
||||
"entries": entries,
|
||||
"uid": uid,
|
||||
"handle": handle,
|
||||
"display_name": displayName,
|
||||
"created_at": createdAt,
|
||||
"avatar": avatar,
|
||||
"header": header,
|
||||
"bio": bio,
|
||||
"entries": entries,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -56,53 +56,55 @@ func (s *Server) handleUserPage(w http.ResponseWriter, r *http.Request) error {
|
||||
func (s *Server) handleUserInfo(w http.ResponseWriter, r *http.Request) error {
|
||||
uid := currentUID(r)
|
||||
var createdAt, lastLogin sql.NullInt64
|
||||
var username, avatar string
|
||||
var handle, displayName, avatar string
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT created_at, last_login, username, avatar FROM account WHERE uid = $1`, uid,
|
||||
).Scan(&createdAt, &lastLogin, &username, &avatar); err != nil {
|
||||
`SELECT created_at, last_login, handle, display_name, avatar FROM account WHERE uid = $1`, uid,
|
||||
).Scan(&createdAt, &lastLogin, &handle, &displayName, &avatar); err != nil {
|
||||
return notFoundOr(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"uid": uid,
|
||||
"username": username,
|
||||
"created_at": createdAt.Int64,
|
||||
"last_login": lastLogin.Int64,
|
||||
"avatar": avatar,
|
||||
"uid": uid,
|
||||
"handle": handle,
|
||||
"display_name": displayName,
|
||||
"created_at": createdAt.Int64,
|
||||
"last_login": lastLogin.Int64,
|
||||
"avatar": avatar,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleUserRename benennt den eingeloggten Account um. Nichts außer der
|
||||
// account-Zeile referenziert den username (alles hängt an der uid), daher
|
||||
// genügt ein UPDATE.
|
||||
func (s *Server) handleUserRename(w http.ResponseWriter, r *http.Request) error {
|
||||
uid := currentUID(r)
|
||||
name := account.SanitizeUsername(r.FormValue("user"))
|
||||
if len(name) < account.MinNameLen {
|
||||
return errNameShort
|
||||
// handleSetHandle ändert den Handle des eingeloggten Accounts. Alles hängt an
|
||||
// der uid, daher genügt ein UPDATE; Links auf das alte /u/<handle> laufen
|
||||
// danach ins Leere.
|
||||
func (s *Server) handleSetHandle(w http.ResponseWriter, r *http.Request) error {
|
||||
handle := account.NormalizeHandle(r.FormValue("handle"))
|
||||
if !account.ValidHandle(handle) {
|
||||
return account.ErrHandleInvalid
|
||||
}
|
||||
var current string
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT username FROM account WHERE uid = $1`, uid).Scan(¤t); err != nil {
|
||||
return notFoundOr(err)
|
||||
}
|
||||
if name == current {
|
||||
return apperr.Invalid("user.name_unchanged", "Das ist bereits dein Name.").At("user")
|
||||
}
|
||||
if taken, err := s.accounts.NameTaken(r.Context(), name); err != nil {
|
||||
return apperr.Internal(err)
|
||||
} else if taken {
|
||||
return account.ErrUsernameTaken
|
||||
}
|
||||
if _, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE account SET username = $1 WHERE uid = $2`, name, uid); err != nil {
|
||||
// Rennen zwischen Vorab-Prüfung und UPDATE: UNIQUE-Constraint -> 409.
|
||||
if database.IsUniqueViolation(err, "account_username_key") {
|
||||
return account.ErrUsernameTaken
|
||||
res, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE account SET handle = $1 WHERE uid = $2 AND handle <> $1`, handle, currentUID(r))
|
||||
if err != nil {
|
||||
// Vergeben, auch im Rennen zweier gleichzeitiger Änderungen: 409.
|
||||
if database.IsUniqueViolation(err, "account_handle_key") {
|
||||
return account.ErrHandleTaken
|
||||
}
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"username": name})
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return apperr.Invalid("user.handle_unchanged", "Das ist bereits dein Handle.").At("handle")
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"handle": handle})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleSetDisplayName setzt den Anzeigenamen; leer heißt: Handle anzeigen.
|
||||
func (s *Server) handleSetDisplayName(w http.ResponseWriter, r *http.Request) error {
|
||||
name := account.CleanDisplayName(r.FormValue("display_name"))
|
||||
if _, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE account SET display_name = $1 WHERE uid = $2`, name, currentUID(r)); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"display_name": name})
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user