Add nested posts UI (#5)

## Summary
- Cut hunt, question, submission, voting, hiding, and profile flows over to unified posts
- Render nested replies with permission-aware inline Reply/Edit controls and edited markers
- Add post profile queries and the author index migration they depend on

Co-authored-by: codegirl-007 <s.raide@gmail.com>
This commit was merged in pull request #5.
This commit is contained in:
2026-08-27 15:53:01 +00:00
committed by codegirl007
parent 4d994d5300
commit 7412069ca6
22 changed files with 1033 additions and 351 deletions
+40 -1
View File
@@ -59,7 +59,7 @@ func (s *Server) handleCreatePost(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
return
}
if !user.Admin() && user.ID != threadRoot.AuthorID {
if !canReplyToThread(user, threadRoot) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
@@ -175,3 +175,42 @@ func canEditPost(user *store.User, post *store.Post) bool {
}
return user.ID == post.AuthorID
}
func canReplyToThread(user *store.User, root *store.Post) bool {
return user != nil &&
root != nil &&
root.PostState != store.PostStateHidden &&
(user.Admin() || user.ID == root.AuthorID)
}
func postLabel(post *store.Post) string {
if post == nil {
return ""
}
if post.ParentID == nil {
return "Question"
}
if post.AuthorRole == store.RoleAdmin {
return "Shop response"
}
return "Homeowner"
}
func postDepthClass(depth int) string {
switch depth {
case 0:
return "root"
case 1:
return "branch"
default:
return "deep"
}
}
func postPointers(posts []store.Post) []*store.Post {
out := make([]*store.Post, len(posts))
for i := range posts {
out[i] = &posts[i]
}
return out
}
+87
View File
@@ -258,6 +258,93 @@ func TestEditPostRoutePermissions(t *testing.T) {
}
}
func TestQuestionPageRendersNestedPostControls(t *testing.T) {
t.Parallel()
srv, mem := newTestServer(t, Config{})
handler := srv.Handler()
homeowner := seedUser(t, mem, uniq("homeowner"), "hunter22", store.RoleUser)
admin := seedUser(t, mem, uniq("admin"), "hunter22", store.RoleAdmin)
homeownerCookies := loginUser(t, handler, homeowner.Username, "hunter22")
adminCookies := loginUser(t, handler, admin.Username, "hunter22")
root := &store.Post{
AuthorID: homeowner.ID,
Title: "Leaky sink",
Body: "Water under the cabinet.",
City: "Oakland",
PostDate: pacific.Today(),
}
if err := mem.CreatePost(context.Background(), root); err != nil {
t.Fatal(err)
}
homeownerReply := &store.Post{
ParentID: &root.ID,
AuthorID: homeowner.ID,
Body: "The model number is 123.",
}
if err := mem.CreatePost(context.Background(), homeownerReply); err != nil {
t.Fatal(err)
}
adminReply := &store.Post{
ParentID: &homeownerReply.ID,
AuthorID: admin.ID,
Body: "Replace the cartridge.",
}
if err := mem.CreatePost(context.Background(), adminReply); err != nil {
t.Fatal(err)
}
homeownerReply.Body = "The model number is 123A."
if err := mem.UpdatePost(context.Background(), homeownerReply); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/questions/"+root.ID, nil)
for _, cookie := range homeownerCookies {
req.AddCookie(cookie)
}
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("question page status = %d: %s", rec.Code, rec.Body.String())
}
body := rec.Body.String()
for _, want := range []string{
`id="post-` + root.ID + `"`,
`id="post-` + homeownerReply.ID + `"`,
`id="post-` + adminReply.ID + `"`,
`class="thread-post thread-post-branch`,
`class="thread-post thread-post-deep is-shop"`,
"Homeowner",
"Shop response",
"Edited",
`action="/posts"`,
`action="/posts/` + root.ID + `/edit"`,
`action="/posts/` + homeownerReply.ID + `/edit"`,
`>The model number is 123A.</textarea>`,
`removeAttribute('open')`,
} {
if !strings.Contains(body, want) {
t.Fatalf("question page missing %q: %s", want, body)
}
}
if strings.Contains(body, `action="/posts/`+adminReply.ID+`/edit"`) {
t.Fatalf("homeowner can edit admin reply: %s", body)
}
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/questions/"+root.ID, nil)
for _, cookie := range adminCookies {
req.AddCookie(cookie)
}
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK ||
!strings.Contains(rec.Body.String(), `action="/posts/`+adminReply.ID+`/edit"`) ||
strings.Contains(rec.Body.String(), `action="/posts/`+root.ID+`/edit"`) {
t.Fatalf("admin edit controls are incorrect: %d %s", rec.Code, rec.Body.String())
}
}
func csrfForCookies(t *testing.T, handler http.Handler, cookies []*http.Cookie) string {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/submit", nil)
+7 -7
View File
@@ -23,7 +23,7 @@ import (
type profilePage struct {
page
States []struct{ Code, Name string }
Questions []store.RankedQuestion
Posts []store.Post
QuestionsLabel string
UploadsEnabled bool
Error string
@@ -255,16 +255,16 @@ func fitAvatar(img image.Image, maxDim int) image.Image {
func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.User, errMsg, stateVal, emailVal string) {
var (
questions []store.RankedQuestion
label string
err error
posts []store.Post
label string
err error
)
if u.Admin() {
label = "Questions you answered"
questions, err = s.store.ListQuestionsAnsweredBy(r.Context(), u.ID)
posts, err = s.store.ListRootPostsAnsweredBy(r.Context(), u.ID)
} else {
label = "Your questions"
questions, err = s.store.ListQuestionsByAuthor(r.Context(), u.ID)
posts, err = s.store.ListRootPostsByAuthor(r.Context(), u.ID)
}
if err != nil {
http.Error(w, "could not load questions", http.StatusInternalServerError)
@@ -275,7 +275,7 @@ func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.
s.exec(w, "profile", profilePage{
page: p,
States: geo.States,
Questions: questions,
Posts: posts,
QuestionsLabel: label,
UploadsEnabled: s.cfg.Blob.Enabled(),
Error: errMsg,
+71 -103
View File
@@ -3,7 +3,6 @@ package web
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
@@ -64,13 +63,12 @@ type huntPage struct {
Label string
IsToday bool
IsYesterday bool
Questions []store.RankedQuestion
Posts []*store.Post
}
type questionPage struct {
page
Question *store.RankedQuestion
Answer *store.Answer
Question *store.Post
}
type submitPage struct {
@@ -90,11 +88,19 @@ type authPage struct {
}
type voteCtx struct {
User *store.User
CSRF string
View string
Date string
Question store.RankedQuestion
User *store.User
CSRF string
View string
Date string
Post *store.Post
}
type threadPostCtx struct {
User *store.User
CSRF string
Root *store.Post
Post *store.Post
Depth int
}
func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) {
@@ -105,12 +111,27 @@ func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.F
cfg.Mail = mail.Nop{}
}
funcMap := template.FuncMap{
"voteCtx": func(user *store.User, csrf, view, date string, q store.RankedQuestion) voteCtx {
return voteCtx{User: user, CSRF: csrf, View: view, Date: date, Question: q}
"voteCtx": func(user *store.User, csrf, view, date string, post *store.Post) voteCtx {
return voteCtx{User: user, CSRF: csrf, View: view, Date: date, Post: post}
},
"postCtx": func(user *store.User, csrf string, root, post *store.Post, depth int) threadPostCtx {
return threadPostCtx{User: user, CSRF: csrf, Root: root, Post: post, Depth: depth}
},
"add": func(a, b int) int { return a + b },
"rank": func(i int) int { return i + 1 },
"isAdmin": func(u *store.User) bool { return u.Admin() },
"canReply": canReplyToThread,
"canEditPost": canEditPost,
"postLabel": postLabel,
"postDepth": postDepthClass,
"isEdited": func(post *store.Post) bool { return post != nil && post.UpdatedAt != post.CreatedAt },
"postTime": func(value string) string {
t, err := time.Parse(time.RFC3339Nano, value)
if err != nil {
return value
}
return t.In(pacific.Loc).Format("Jan 2, 2006 · 3:04 PM")
},
"add": func(a, b int) int { return a + b },
"rank": func(i int) int { return i + 1 },
"isAdmin": func(u *store.User) bool { return u.Admin() },
"pacificLabel": pacific.Label,
"locationTag": func(u *store.User) string {
if u != nil {
@@ -281,7 +302,7 @@ func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string)
if u := currentUser(r); u != nil {
viewer = u.ID
}
questions, err := s.store.ListHunt(r.Context(), date, viewer)
posts, err := s.store.ListRootPosts(r.Context(), date, viewer)
if err != nil {
http.Error(w, "could not load questions", http.StatusInternalServerError)
return
@@ -297,7 +318,7 @@ func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string)
Label: label,
IsToday: pacific.IsToday(date),
IsYesterday: pacific.IsYesterday(date),
Questions: questions,
Posts: postPointers(posts),
})
}
@@ -341,17 +362,17 @@ func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) {
if len(city) > 80 {
city = truncateRunes(city, 80)
}
q := &store.RankedQuestion{
post := &store.Post{
AuthorID: u.ID,
Title: title,
Body: body,
City: city,
}
if err := s.store.CreateQuestion(r.Context(), q); err != nil {
if err := s.store.CreatePost(r.Context(), post); err != nil {
http.Error(w, "could not save question", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/questions/"+url.PathEscape(q.ID), http.StatusSeeOther)
http.Redirect(w, r, "/questions/"+url.PathEscape(post.ID), http.StatusSeeOther)
}
func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) {
@@ -360,29 +381,14 @@ func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) {
if u := currentUser(r); u != nil {
viewer = u.ID
}
q, err := s.store.GetQuestion(r.Context(), id, viewer)
if err != nil || (q.Hidden && !currentUser(r).Admin()) {
post, err := s.store.GetPostThreadForViewer(r.Context(), id, viewer)
if err != nil || (post.PostState == store.PostStateHidden && !currentUser(r).Admin()) {
http.NotFound(w, r)
return
}
var ans *store.Answer
if q.Answered {
ans, err = s.store.GetAnswer(r.Context(), q.ID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
log.Printf("question %s marked answered but answer missing", q.ID)
http.Error(w, "answer unavailable", http.StatusInternalServerError)
return
}
log.Printf("get answer %s: %v", q.ID, err)
http.Error(w, "could not load answer", http.StatusInternalServerError)
return
}
}
s.exec(w, "question", questionPage{
page: s.basePage(r, q.Title),
Question: q,
Answer: ans,
page: s.basePage(r, post.Title),
Question: post,
})
}
@@ -412,8 +418,8 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid vote", http.StatusBadRequest)
return
}
if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil {
if errors.Is(err, store.ErrHiddenOrMissing) {
if err := s.store.VotePost(r.Context(), u.ID, id, value); err != nil {
if errors.Is(err, store.ErrPostNotVotable) {
http.Error(w, "not found", http.StatusNotFound)
return
}
@@ -427,17 +433,17 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) {
s.renderLeaderboard(w, r, date)
return
}
q, err := s.store.GetQuestion(r.Context(), id, u.ID)
post, err := s.store.GetPostThreadForViewer(r.Context(), id, u.ID)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
s.exec(w, "vote", voteCtx{
User: u,
CSRF: s.sessions.GetString(r.Context(), "csrf"),
View: "question",
Date: q.HuntDate,
Question: *q,
User: u,
CSRF: s.sessions.GetString(r.Context(), "csrf"),
View: "question",
Date: post.PostDate,
Post: post,
})
return
}
@@ -460,15 +466,15 @@ func (s *Server) renderLeaderboard(w http.ResponseWriter, r *http.Request, date
if u := currentUser(r); u != nil {
viewer = u.ID
}
questions, err := s.store.ListHunt(r.Context(), date, viewer)
posts, err := s.store.ListRootPosts(r.Context(), date, viewer)
if err != nil {
http.Error(w, "could not load questions", http.StatusInternalServerError)
return
}
s.exec(w, "leaderboard", huntPage{
page: s.basePage(r, ""),
Date: date,
Questions: questions,
page: s.basePage(r, ""),
Date: date,
Posts: postPointers(posts),
})
}
@@ -490,65 +496,27 @@ func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) {
if len(body) > 12000 {
body = truncateRunes(body, 12000)
}
q, err := s.store.GetQuestion(r.Context(), id, u.ID)
if err != nil {
root, err := s.store.GetPost(r.Context(), id)
if err != nil || root.ParentID != nil || root.PostState == store.PostStateHidden {
http.NotFound(w, r)
return
}
_, priorErr := s.store.GetAnswer(r.Context(), id)
wasNew := errors.Is(priorErr, sql.ErrNoRows)
if priorErr != nil && !wasNew {
http.Error(w, "could not load answer", http.StatusInternalServerError)
return
reply := &store.Post{
ParentID: &root.ID,
AuthorID: u.ID,
Body: body,
}
ans := &store.Answer{
QuestionID: id,
AuthorID: u.ID,
Body: body,
}
if err := s.store.UpsertAnswer(r.Context(), ans); err != nil {
if err := s.store.CreatePost(r.Context(), reply); err != nil {
http.Error(w, "could not save answer", http.StatusInternalServerError)
return
}
if wasNew {
s.notifyQuestionAnswered(q, body, u.ID)
}
saved, err := s.store.GetAnswer(r.Context(), id)
if err != nil {
http.Error(w, "could not load answer", http.StatusInternalServerError)
return
}
location := "/questions/" + url.PathEscape(id) + "#post-" + url.PathEscape(reply.ID)
if isHTMX(r) {
s.exec(w, "answer", questionPage{page: s.basePage(r, ""), Answer: saved})
w.Header().Set("HX-Redirect", location)
w.WriteHeader(http.StatusSeeOther)
return
}
http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther)
}
func (s *Server) notifyQuestionAnswered(q *store.RankedQuestion, answerBody, adminID string) {
if q == nil || s.cfg.Mail == nil {
return
}
author, err := s.store.UserByID(context.Background(), q.AuthorID)
if err != nil || author == nil || author.Email == "" || author.ID == adminID {
return
}
msg := mail.QuestionAnswered{
ToEmail: author.Email,
ToName: author.Name,
QuestionID: q.ID,
QuestionTitle: q.Title,
AnswerBody: answerBody,
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.cfg.Mail.NotifyQuestionAnswered(ctx, msg); err != nil {
log.Printf("notify answer %s: %v", q.ID, err)
return
}
log.Printf("notify answer %s: accepted", q.ID)
}()
http.Redirect(w, r, location, http.StatusSeeOther)
}
func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) {
@@ -561,17 +529,17 @@ func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) {
return
}
id := chi.URLParam(r, "id")
q, err := s.store.GetQuestion(r.Context(), id, u.ID)
if err != nil {
post, err := s.store.GetPost(r.Context(), id)
if err != nil || post.ParentID != nil {
http.NotFound(w, r)
return
}
if err := s.store.HideQuestion(r.Context(), id); err != nil {
if err := s.store.SetRootPostState(r.Context(), id, store.PostStateHidden); err != nil {
http.Error(w, "could not hide", http.StatusInternalServerError)
return
}
if isHTMX(r) && r.PostFormValue("view") == "list" {
s.renderLeaderboard(w, r, q.HuntDate)
s.renderLeaderboard(w, r, post.PostDate)
return
}
if isHTMX(r) {
+40 -133
View File
@@ -19,7 +19,6 @@ import (
"plumber"
"plumber/internal/blob"
"plumber/internal/mail"
"plumber/internal/pacific"
"plumber/internal/store"
)
@@ -417,21 +416,21 @@ func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) {
alice := seedUser(t, mem, aliceName, "hunter22", store.RoleUser)
adminCookies := loginUser(t, h, hubName, "hunter22")
q := &store.RankedQuestion{
root := &store.Post{
AuthorID: alice.ID,
Title: "Drip",
Body: "Under sink",
City: "Oakland",
}
if err := mem.CreateQuestion(context.Background(), q); err != nil {
if err := mem.CreatePost(context.Background(), root); err != nil {
t.Fatal(err)
}
ans := &store.Answer{
QuestionID: q.ID,
AuthorID: hub.ID,
Body: "Replace the cartridge.",
reply := &store.Post{
ParentID: &root.ID,
AuthorID: hub.ID,
Body: "Replace the cartridge.",
}
if err := mem.UpsertAnswer(context.Background(), ans); err != nil {
if err := mem.CreatePost(context.Background(), reply); err != nil {
t.Fatal(err)
}
@@ -493,14 +492,14 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
adminCookies := loginUser(t, h, adminName, "hunter22")
userCookies := loginUser(t, h, userName, "hunter22")
q := &store.RankedQuestion{
q := &store.Post{
AuthorID: user.ID,
Title: "Pipe noise",
Body: "Clanking",
City: "SF",
HuntDate: pacific.Today(),
PostDate: pacific.Today(),
}
if err := mem.CreateQuestion(context.Background(), q); err != nil {
if err := mem.CreatePost(context.Background(), q); err != nil {
t.Fatal(err)
}
@@ -556,7 +555,7 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
if rec.Code != 200 {
t.Fatalf("vote htmx %d %s", rec.Code, rec.Body.String())
}
got, err := mem.GetQuestion(context.Background(), q.ID, user.ID)
got, err := mem.GetPostThreadForViewer(context.Background(), q.ID, user.ID)
if err != nil || got.UserVote != 1 || got.Score != 1 {
t.Fatalf("vote not applied: %+v %v", got, err)
}
@@ -581,7 +580,7 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
t.Fatalf("non-admin answer want 403, got %d", rec.Code)
}
// Admin answer success (HTMX)
// Admin answer compatibility route creates a reply and redirects the thread.
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
for _, c := range adminCookies {
@@ -598,22 +597,37 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Tighten the nuts") {
if rec.Code != http.StatusSeeOther {
t.Fatalf("admin answer: %d %s", rec.Code, rec.Body.String())
}
if body := rec.Body.String(); !strings.Contains(body, `class="answer-editor"`) ||
!strings.Contains(body, "<summary>Edit answer</summary>") ||
thread, err := mem.GetPostThread(context.Background(), q.ID)
if err != nil || len(thread.Replies) != 1 {
t.Fatalf("admin reply missing: %+v %v", thread, err)
}
adminReply := thread.Replies[0]
if adminReply.AuthorID != admin.ID || adminReply.Body != "Tighten the nuts." {
t.Fatalf("unexpected admin reply: %+v", adminReply)
}
if got := rec.Header().Get("HX-Redirect"); got != "/questions/"+q.ID+"#post-"+adminReply.ID {
t.Fatalf("admin answer redirect = %q", got)
}
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
for _, c := range adminCookies {
req.AddCookie(c)
}
h.ServeHTTP(rec, req)
if body := rec.Body.String(); !strings.Contains(body, "Tighten the nuts.") ||
!strings.Contains(body, "<summary>Edit</summary>") ||
!strings.Contains(body, ">Tighten the nuts.</textarea>") ||
!strings.Contains(body, `type="reset" class="btn btn-ghost"`) ||
!strings.Contains(body, `removeAttribute('open')`) ||
strings.Contains(body, `<details class="answer-editor" open`) {
t.Fatalf("admin answer editor is not collapsed and populated: %s", body)
}
if _, err := mem.GetAnswer(context.Background(), q.ID); err != nil {
t.Fatal(err)
strings.Contains(body, `<details class="post-composer" open`) {
t.Fatalf("admin reply editor is not collapsed and populated: %s", body)
}
// The public answer is visible to its author, but editing remains admin-only.
// The public reply is visible to the root author, but editing remains admin-only.
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
for _, c := range userCookies {
@@ -623,8 +637,8 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Tighten the nuts.") {
t.Fatalf("question author cannot see answer: %d %s", rec.Code, rec.Body.String())
}
if strings.Contains(rec.Body.String(), `class="answer-editor"`) {
t.Fatalf("question author can see admin answer editor: %s", rec.Body.String())
if strings.Contains(rec.Body.String(), `/posts/`+adminReply.ID+`/edit`) {
t.Fatalf("question author can edit admin reply: %s", rec.Body.String())
}
// Hide invalid id
@@ -659,8 +673,8 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
if rec.Code != http.StatusSeeOther {
t.Fatalf("hide %d %s", rec.Code, rec.Body.String())
}
hidden, err := mem.GetQuestion(context.Background(), q.ID, admin.ID)
if err != nil || !hidden.Hidden {
hidden, err := mem.GetPost(context.Background(), q.ID)
if err != nil || hidden.PostState != store.PostStateHidden {
t.Fatalf("question not hidden: %+v %v", hidden, err)
}
}
@@ -713,113 +727,6 @@ func TestRegisterRequiresEmail(t *testing.T) {
}
}
func TestAnswerNotifyFirstOnly(t *testing.T) {
recMail := &mail.Recording{}
srv, mem := newTestServer(t, Config{Mail: recMail})
h := srv.Handler()
adminName := uniq("adm")
askName := uniq("ask")
admin := seedUser(t, mem, adminName, "hunter22", store.RoleAdmin)
asker := seedUser(t, mem, askName, "hunter22", store.RoleUser)
adminCookies := loginUser(t, h, adminName, "hunter22")
q := &store.RankedQuestion{
AuthorID: asker.ID,
Title: "Leaky sink",
Body: "Drip",
City: "Oakland",
HuntDate: pacific.Today(),
}
if err := mem.CreateQuestion(context.Background(), q); err != nil {
t.Fatal(err)
}
postAnswer := func(body string) {
t.Helper()
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
for _, c := range adminCookies {
req.AddCookie(c)
}
h.ServeHTTP(w, req)
csrf := csrfFrom(w.Body.String())
form := strings.NewReader("_csrf=" + csrf + "&body=" + body)
req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/answer", form)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("HX-Request", "true")
for _, c := range adminCookies {
req.AddCookie(c)
}
w = httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("answer %d %s", w.Code, w.Body.String())
}
}
postAnswer("First+reply")
deadline := time.Now().Add(2 * time.Second)
var msgs []mail.QuestionAnswered
for time.Now().Before(deadline) {
msgs = recMail.Snapshot()
if len(msgs) > 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
if len(msgs) != 1 {
t.Fatalf("first answer notifies once, got %d", len(msgs))
}
if msgs[0].ToEmail != asker.Email || msgs[0].QuestionID != q.ID {
t.Fatalf("unexpected notify: %+v", msgs[0])
}
if msgs[0].AnswerBody != "First reply" {
t.Fatalf("answer body %q", msgs[0].AnswerBody)
}
postAnswer("Edited+reply")
time.Sleep(50 * time.Millisecond)
if recMail.Len() != 1 {
t.Fatalf("edit must not notify again, got %d", recMail.Len())
}
// Author without email is skipped
recMail2 := &mail.Recording{}
srv2, mem2 := newTestServer(t, Config{Mail: recMail2})
h2 := srv2.Handler()
admin2 := seedUser(t, mem2, uniq("adm2"), "hunter22", store.RoleAdmin)
noMail := &store.User{Username: uniq("silent"), PasswordHash: admin.PasswordHash, Role: store.RoleUser, Email: ""}
hash, _ := bcrypt.GenerateFromPassword([]byte("hunter22"), bcrypt.MinCost)
noMail.PasswordHash = string(hash)
if err := mem2.CreateUser(context.Background(), noMail); err != nil {
t.Fatal(err)
}
q2 := &store.RankedQuestion{AuthorID: noMail.ID, Title: "Quiet", Body: "x", HuntDate: pacific.Today()}
if err := mem2.CreateQuestion(context.Background(), q2); err != nil {
t.Fatal(err)
}
cookies := loginUser(t, h2, admin2.Username, "hunter22")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/questions/"+q2.ID, nil)
for _, c := range cookies {
req.AddCookie(c)
}
h2.ServeHTTP(w, req)
csrf := csrfFrom(w.Body.String())
form := strings.NewReader("_csrf=" + csrf + "&body=Hello")
req = httptest.NewRequest(http.MethodPost, "/questions/"+q2.ID+"/answer", form)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for _, c := range cookies {
req.AddCookie(c)
}
w = httptest.NewRecorder()
h2.ServeHTTP(w, req)
time.Sleep(50 * time.Millisecond)
if recMail2.Len() != 0 {
t.Fatalf("empty email must skip notify, got %d", recMail2.Len())
}
}
// TestRegisterThrottleUsesTCPPeerThroughRouter ensures forged X-Forwarded-For
// cannot bypass rate limits when the direct peer is outside TrustedProxies.
// This must go through Handler() so middleware ordering bugs are caught.