password-reset: a confirmed e-mail, then a link to reset the password
Agreed by the owner on 2026-10-13 ("the e-mail must be confirmed");
notifications to an unconfirmed address settled on 2026-10-17: "Без
подтверждения слать". Mockups 2f5f5b2, route guard b7bbb2c, panel guard
0774da2.
Migration 0013: users.email_confirmed_at ('' for every address saved
before it) and user_links - the SHA-256 of a link's token, its user,
purpose (confirm, reset), address, created and expiry. A changed address
loses its mark (keepConfirmed, in UpdateUser and SaveUser).
internal/web/auth/links.go. A link is 256 bits from crypto/rand, mailed as
https://SELFPOST_HOSTNAME/... - never the request's Host. Confirmation:
24 h, sent when an address is saved (Account, or the global role's user
form) and by Account's Send the link again; its page /confirm/<token> has
a button (a GET changes nothing) and confirms only for a session of its
own account. Reset: /login/reset asks for a username and answers the same
for every name (the sign-in page, "If that account has a confirmed e-mail,
the link is on its way"), mailing after the answer; only a confirmed
address gets one, none within ten minutes of the last, five links an hour
per account, five requests in 15 minutes per client address;
/login/reset/<token> (30 min) sets the password with the link taken in
the same transaction that checks the address again
(store.TakeResetLink), then ends every session. Changing the e-mail on
Account asks for the current password. A password set on Account or the
user form removes the reset links; a restore removes every link; the stop
waits for links being mailed (Server.Drain); a rejected request's log line
hides a link's token (loggedPath).
Reviewed for security before the commit (2026-10-17): no high; two
medium and five low, all fixed here - confirming needs the account's
session and the mail does not name the account (a mistyped address was a
takeover); a reset request neither replaces the links already sent nor
spends the account's quota inside ten minutes; take-and-set atomic; the
confirmation mail sent after the answer; the stop waits for mail; a
restore deletes the links; the token kept out of the log.
Tests: store TestUserLinks, TestUserLinkTakenOnce, TestEmailConfirmation,
TestTakeResetLink; auth TestResetSendsALinkOnlyToAConfirmedAddress,
TestResetLinkSetsThePasswordOnce, TestResetLinkDiesWithTheAddress,
TestResetRequestsAreLimited, TestResetRequestsAreSpaced, TestConfirmLink,
TestLinkPathsWithoutAToken; handlers TestAccountEmailIsConfirmedByItsLink,
TestUserFormSendsANewAddressItsLink; web TestLoggedPathHidesTokens; the
view's pages and fixtures; e2e password_reset_by_e_mail runs it through
the sink (and checks a link from before the restore is dead). go vet +
go test (26 packages) and make e2e on the test server for this tree.
Docs: guide § Account, security.md (the bullet and what ends sessions),
architecture (routes), schema-migrations (row 13, users, user_links),
help #account (word for word with the mockup), roadmap row done,
CHANGELOG [Unreleased].
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mixeme/selfpost/internal/store"
|
||||
"github.com/mixeme/selfpost/internal/web/validate"
|
||||
@@ -60,6 +61,11 @@ func (h *Handlers) HandleAccount(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *Handlers) renderAccount(w http.ResponseWriter, r *http.Request, status int, u store.User, f accountForm) {
|
||||
page := view.NewAccount(h.shellMeta(r), string(u.Role))
|
||||
page.Username, page.Email, page.Notify = f.Username, f.Email, f.Notify
|
||||
var sent time.Time
|
||||
if l, err := h.store.LatestUserLink(u.ID, store.LinkConfirm, time.Now()); err == nil && l.Email == u.Email {
|
||||
sent = l.CreatedAt
|
||||
}
|
||||
page.WithEmailState(u.Email, !u.EmailConfirmed.IsZero(), sent)
|
||||
page.WithResult(accountFlash(r), f.Err)
|
||||
h.view.Render(w, status, "account", page)
|
||||
}
|
||||
@@ -68,6 +74,10 @@ func accountFlash(r *http.Request) string {
|
||||
switch r.URL.Query().Get("done") {
|
||||
case "profile":
|
||||
return "Profile saved."
|
||||
case "profile-link":
|
||||
return "Profile saved. A link to confirm the new address is on its way."
|
||||
case "link":
|
||||
return "A new link is on its way."
|
||||
case "password":
|
||||
return "Password changed. Any other signed-in sessions were signed out."
|
||||
}
|
||||
@@ -108,6 +118,25 @@ func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request)
|
||||
fail(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// The e-mail is where a reset link goes once it is confirmed, so
|
||||
// changing it asks for the password, as changing the password does
|
||||
// (roadmap password-reset; 2.0 security review), on the same limit.
|
||||
emailChanged := f.Email != u.Email
|
||||
if emailChanged {
|
||||
if !h.auth.AllowPasswordChange(u.ID) {
|
||||
fail(http.StatusTooManyRequests, "Too many attempts. Please wait and try again.")
|
||||
return
|
||||
}
|
||||
current := r.PostFormValue("current_password")
|
||||
if current == "" {
|
||||
fail(http.StatusUnauthorized, "Your current password is needed to change the e-mail.")
|
||||
return
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(current)); err != nil {
|
||||
fail(http.StatusUnauthorized, "Current password is incorrect.")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := h.store.UpdateUser(u.ID, f.Username, u.PasswordHash, f.Email); err != nil {
|
||||
if errors.Is(err, store.ErrUserExists) {
|
||||
fail(http.StatusConflict, "That username is already in use.")
|
||||
@@ -125,9 +154,54 @@ func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
logf("panel: user %d profile updated (username: %t, e-mail: %t, notifications: %t)", u.ID, f.Username != u.Username, f.Email != u.Email, f.Notify)
|
||||
if emailChanged && f.Email != "" && h.sendConfirmation(u.ID) {
|
||||
http.Redirect(w, r, "/account?done=profile-link", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/account?done=profile", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// HandleAccountConfirmLink sends the account's unconfirmed address its link
|
||||
// again (Account, "Send the link again").
|
||||
func (h *Handlers) HandleAccountConfirmLink(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.accountUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if u.Email == "" || !u.EmailConfirmed.IsZero() {
|
||||
http.Redirect(w, r, "/account", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
f := formOf(u)
|
||||
if !h.auth.AllowConfirmationLink(u.ID) {
|
||||
f.Err = "Too many links asked for. Please wait and try again."
|
||||
h.renderAccount(w, r, http.StatusTooManyRequests, u, f)
|
||||
return
|
||||
}
|
||||
h.auth.SendConfirmationLater(u)
|
||||
http.Redirect(w, r, "/account?done=link", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// sendConfirmation mails the user's unconfirmed address its link after the
|
||||
// answer, within the limit of links to one address; whether one was sent off.
|
||||
// A link that cannot go is logged: the address is saved all the same, and
|
||||
// Account offers to send it again.
|
||||
func (h *Handlers) sendConfirmation(userID int64) bool {
|
||||
if h.auth == nil || !h.auth.CanMail() {
|
||||
return false
|
||||
}
|
||||
u, err := h.store.GetUser(userID)
|
||||
if err != nil || u.Email == "" || !u.EmailConfirmed.IsZero() {
|
||||
return false
|
||||
}
|
||||
if !h.auth.AllowConfirmationLink(u.ID) {
|
||||
logf("panel: user %d: confirmation links asked for too often; none was sent", u.ID)
|
||||
return false
|
||||
}
|
||||
h.auth.SendConfirmationLater(u)
|
||||
return true
|
||||
}
|
||||
|
||||
// HandleAccountPassword changes the password. It asks for the current one and
|
||||
// is rate-limited like a sign-in: the form is a place to guess a password from
|
||||
// an unattended session.
|
||||
@@ -178,6 +252,10 @@ func (h *Handlers) HandleAccountPassword(w http.ResponseWriter, r *http.Request)
|
||||
if token, ok := h.auth.SessionToken(r); ok {
|
||||
h.auth.DestroyOtherSessions(u.ID, token)
|
||||
}
|
||||
// A password set another way leaves no reset link behind it.
|
||||
if err := h.store.DeleteUserLinks(u.ID, store.LinkReset); err != nil {
|
||||
logf("panel: account: %v", err)
|
||||
}
|
||||
logf("panel: user %d changed their password", u.ID)
|
||||
http.Redirect(w, r, "/account?done=password", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mixeme/selfpost/internal/store"
|
||||
"github.com/mixeme/selfpost/internal/web/auth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -32,10 +36,11 @@ func TestAccountPageShowsTwoForms(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The profile form saves the name and the e-mail without asking for the
|
||||
// password and without changing the password or any domain's report address.
|
||||
// The profile form saves the name and the e-mail - a new e-mail with the
|
||||
// current password - without changing the password or any domain's report
|
||||
// address.
|
||||
func TestAccountProfile(t *testing.T) {
|
||||
h, _ := settingsServer(t)
|
||||
h, password := settingsServer(t)
|
||||
before, _ := h.store.GetUser(globalPrincipal.ID)
|
||||
d, _ := h.store.AddDomain("example.com", "mail")
|
||||
if err := h.store.SetDomainDMARCAddress(d.ID, "reports@hub.example"); err != nil {
|
||||
@@ -43,7 +48,7 @@ func TestAccountProfile(t *testing.T) {
|
||||
}
|
||||
|
||||
rec := postFormAs(h.HandleAccountProfile, globalPrincipal, "/account/profile", nil,
|
||||
url.Values{"username": {"operator"}, "email": {"mix@example.org"}})
|
||||
url.Values{"username": {"operator"}, "email": {"mix@example.org"}, "current_password": {password}})
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/account?done=profile" {
|
||||
t.Fatalf("POST /account/profile = %d to %q:\n%s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
|
||||
}
|
||||
@@ -70,12 +75,91 @@ func TestAccountProfile(t *testing.T) {
|
||||
if _, err := h.store.CreateUser("taken", "h", store.RoleGlobal, store.Reach{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = postFormAs(h.HandleAccountProfile, globalPrincipal, "/account/profile", nil, url.Values{"username": {"taken"}, "email": {"other@example.org"}})
|
||||
rec = postFormAs(h.HandleAccountProfile, globalPrincipal, "/account/profile", nil, url.Values{"username": {"taken"}, "email": {"other@example.org"}, "current_password": {password}})
|
||||
if u, _ = h.store.GetUser(globalPrincipal.ID); rec.Code != http.StatusConflict || u.Username != "operator" || u.Email != "mix@example.org" {
|
||||
t.Errorf("a taken username = %d, profile now %q / %q", rec.Code, u.Username, u.Email)
|
||||
}
|
||||
}
|
||||
|
||||
// linkMailer keeps the links the panel would have mailed.
|
||||
type linkMailer struct{ sent []string }
|
||||
|
||||
func (r *linkMailer) Send(to, subject, body string) error {
|
||||
r.sent = append(r.sent, to+" | "+subject+" | "+body)
|
||||
return nil
|
||||
}
|
||||
|
||||
// sentBy is what ml has been given once h's links sent after their answers
|
||||
// have gone.
|
||||
func sentBy(h *Handlers, ml *linkMailer) []string {
|
||||
h.auth.Wait(context.Background())
|
||||
return ml.sent
|
||||
}
|
||||
|
||||
// withMail gives h an auth module that mails, as mail.example.org, to a
|
||||
// linkMailer.
|
||||
func withMail(t *testing.T, h *Handlers) *linkMailer {
|
||||
t.Helper()
|
||||
h.auth = auth.New(h.store, auth.Config{Hostname: "mail.example.org"}, h.view, filepath.Join(t.TempDir(), "setup-token"))
|
||||
ml := &linkMailer{}
|
||||
h.auth.SetMailer(ml)
|
||||
return ml
|
||||
}
|
||||
|
||||
// The e-mail is where a reset link goes once confirmed, so changing it asks
|
||||
// for the password; the new address is sent its link and shows as not
|
||||
// confirmed, with Send the link again; a confirmed address shows as such and
|
||||
// keeps its mark when only the name changes.
|
||||
func TestAccountEmailIsConfirmedByItsLink(t *testing.T) {
|
||||
h, password := settingsServer(t)
|
||||
ml := withMail(t, h)
|
||||
change := url.Values{"username": {"admin"}, "email": {"mix@example.org"}}
|
||||
for name, pw := range map[string]string{"no password": "", "wrong password": "nope"} {
|
||||
form := url.Values{"username": change["username"], "email": change["email"], "current_password": {pw}}
|
||||
if rec := postFormAs(h.HandleAccountProfile, globalPrincipal, "/account/profile", nil, form); rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s: %d", name, rec.Code)
|
||||
}
|
||||
}
|
||||
if u, _ := h.store.GetUser(globalPrincipal.ID); u.Email != "" || len(sentBy(h, ml)) != 0 {
|
||||
t.Fatalf("a refused change saved %q, sent %d", u.Email, len(sentBy(h, ml)))
|
||||
}
|
||||
change.Set("current_password", password)
|
||||
rec := postFormAs(h.HandleAccountProfile, globalPrincipal, "/account/profile", nil, change)
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/account?done=profile-link" {
|
||||
t.Fatalf("change: %d %q\n%s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
|
||||
}
|
||||
if len(sentBy(h, ml)) != 1 || !strings.HasPrefix(sentBy(h, ml)[0], "mix@example.org | [SelfPost] Confirm your e-mail | ") ||
|
||||
!strings.Contains(sentBy(h, ml)[0], "https://mail.example.org/confirm/") {
|
||||
t.Fatalf("sent = %q", sentBy(h, ml))
|
||||
}
|
||||
out := getBody(t, h.HandleAccount, "/account")
|
||||
for _, want := range []string{`<span class="tag is-warning is-light">not confirmed</span>`, `action="/account/email/confirm"`, `A link was sent to`} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("account page missing %q", want)
|
||||
}
|
||||
}
|
||||
// Send the link again: a second link.
|
||||
if rec := postFormAs(h.HandleAccountConfirmLink, globalPrincipal, "/account/email/confirm", nil, nil); rec.Code != http.StatusSeeOther || len(sentBy(h, ml)) != 2 {
|
||||
t.Fatalf("send again: %d, sent %d", rec.Code, len(sentBy(h, ml)))
|
||||
}
|
||||
// Confirmed: the tag says so, the form is gone, and a new name keeps it
|
||||
// without the password.
|
||||
if ok, _ := h.store.ConfirmEmail(globalPrincipal.ID, "mix@example.org", time.Now()); !ok {
|
||||
t.Fatal("confirm")
|
||||
}
|
||||
out = getBody(t, h.HandleAccount, "/account")
|
||||
if !strings.Contains(out, `<span class="tag is-success is-light">confirmed</span>`) || strings.Contains(out, `action="/account/email/confirm"`) {
|
||||
t.Errorf("a confirmed address:\n%s", out)
|
||||
}
|
||||
if rec := postFormAs(h.HandleAccountProfile, globalPrincipal, "/account/profile", nil,
|
||||
url.Values{"username": {"operator"}, "email": {"mix@example.org"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("a new name: %d", rec.Code)
|
||||
}
|
||||
if u, _ := h.store.GetUser(globalPrincipal.ID); u.EmailConfirmed.IsZero() || len(sentBy(h, ml)) != 2 {
|
||||
t.Errorf("a new name: confirmed %v, sent %d", u.EmailConfirmed, len(sentBy(h, ml)))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountPassword(t *testing.T) {
|
||||
h, password := settingsServer(t)
|
||||
const next = "another-long-password-2"
|
||||
@@ -110,7 +194,12 @@ func TestAccountIsOpenToADomainAdministrator(t *testing.T) {
|
||||
h, _ := settingsServer(t)
|
||||
d, _ := h.store.AddDomain("example.com", "mail")
|
||||
p := domainAdmin(t, h.store, "ops", d.ID)
|
||||
rec := postFormAs(h.HandleAccountProfile, p, "/account/profile", nil, url.Values{"username": {"ops"}, "email": {"ops@example.org"}})
|
||||
// A new e-mail asks for the password: the administrator's is set here.
|
||||
hash, _ := bcrypt.GenerateFromPassword([]byte("ops-password-1234"), bcrypt.MinCost)
|
||||
if err := h.store.SetUserPassword(p.ID, string(hash)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := postFormAs(h.HandleAccountProfile, p, "/account/profile", nil, url.Values{"username": {"ops"}, "email": {"ops@example.org"}, "current_password": {"ops-password-1234"}})
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("POST /account/profile as a domain administrator = %d:\n%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mixeme/selfpost/internal/store"
|
||||
)
|
||||
|
||||
// An address the global administrator types for a user is unconfirmed until
|
||||
// that user opens its link: creating the user with one, or saving a new one,
|
||||
// sends it; the form tags it either way.
|
||||
func TestUserFormSendsANewAddressItsLink(t *testing.T) {
|
||||
h, st := inboundHandlers(t)
|
||||
ml := withMail(t, h)
|
||||
out1, _ := st.AddDomain("one.example.com", "mail")
|
||||
root := userWith(t, st, "root", store.RoleGlobal, store.Reach{})
|
||||
|
||||
rec := send(h.HandleUserNew, &root, "POST", "/server/users/new", nil, url.Values{
|
||||
"username": {"ops"}, "email": {"ops@acme.io"}, "password": {"a-long-enough-password-1"}, "role": {"domain"},
|
||||
"domain_ids": {idStr(out1.ID)},
|
||||
})
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("create = %d:\n%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(sentBy(h, ml)) != 1 || !strings.HasPrefix(sentBy(h, ml)[0], "ops@acme.io | [SelfPost] Confirm your e-mail | ") {
|
||||
t.Fatalf("sent = %q", sentBy(h, ml))
|
||||
}
|
||||
u, _ := st.GetUserByUsername("ops")
|
||||
path, pv := "/server/users/"+idStr(u.ID), map[string]string{"uid": idStr(u.ID)}
|
||||
if out := send(h.HandleUserEdit, &root, "GET", path, pv, nil).Body.String(); !strings.Contains(out, `<span class="tag is-warning is-light">not confirmed</span>`) {
|
||||
t.Errorf("an unconfirmed address is not tagged:\n%s", out)
|
||||
}
|
||||
if ok, _ := st.ConfirmEmail(u.ID, "ops@acme.io", time.Now()); !ok {
|
||||
t.Fatal("confirm")
|
||||
}
|
||||
if out := send(h.HandleUserEdit, &root, "GET", path, pv, nil).Body.String(); !strings.Contains(out, `<span class="tag is-success is-light">confirmed</span>`) {
|
||||
t.Errorf("a confirmed address is not tagged:\n%s", out)
|
||||
}
|
||||
// The same address saved again keeps its mark and sends nothing; a new
|
||||
// one loses it and is sent its link.
|
||||
form := url.Values{"username": {"ops"}, "role": {"domain"}, "domain_ids": {idStr(out1.ID)}, "email": {"ops@acme.io"}}
|
||||
if rec := send(h.HandleUserEdit, &root, "POST", path, pv, form); rec.Code != http.StatusSeeOther || len(sentBy(h, ml)) != 1 {
|
||||
t.Fatalf("the same address: %d, sent %d", rec.Code, len(sentBy(h, ml)))
|
||||
}
|
||||
form.Set("email", "new@acme.io")
|
||||
if rec := send(h.HandleUserEdit, &root, "POST", path, pv, form); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("a new address: %d", rec.Code)
|
||||
}
|
||||
if got, _ := st.GetUser(u.ID); !got.EmailConfirmed.IsZero() || len(sentBy(h, ml)) != 2 || !strings.HasPrefix(sentBy(h, ml)[1], "new@acme.io | ") {
|
||||
t.Errorf("a new address: confirmed %v, sent %q", got.EmailConfirmed, sentBy(h, ml))
|
||||
}
|
||||
}
|
||||
@@ -26,14 +26,14 @@ const notifyHost = "mail.example.org"
|
||||
// stored, Save profile writes it, and an unchecked box is a form without the
|
||||
// field, which means off. Saving it changes nothing else of the profile.
|
||||
func TestAccountNotifyCheckbox(t *testing.T) {
|
||||
h, _ := settingsServer(t)
|
||||
h, password := settingsServer(t)
|
||||
notify := func() bool {
|
||||
u, _ := h.store.GetUser(globalPrincipal.ID)
|
||||
return u.Notify
|
||||
}
|
||||
save := func(extra url.Values) {
|
||||
t.Helper()
|
||||
form := url.Values{"username": {"admin"}, "email": {"mix@example.org"}}
|
||||
form := url.Values{"username": {"admin"}, "email": {"mix@example.org"}, "current_password": {password}}
|
||||
for k, v := range extra {
|
||||
form[k] = v
|
||||
}
|
||||
|
||||
@@ -153,7 +153,13 @@ func (h *Handlers) renderUserForm(w http.ResponseWriter, r *http.Request, status
|
||||
in.InDomains = append(in.InDomains, view.DomainChoice{ID: d.ID, Name: d.Name, Checked: inb[d.ID]})
|
||||
}
|
||||
}
|
||||
h.view.Render(w, status, "user", view.NewUserForm(h.shellMeta(r), in))
|
||||
page := view.NewUserForm(h.shellMeta(r), in)
|
||||
if userID != 0 {
|
||||
if u, err := h.store.GetUser(userID); err == nil {
|
||||
page.WithEmailState(u.Email, !u.EmailConfirmed.IsZero())
|
||||
}
|
||||
}
|
||||
h.view.Render(w, status, "user", page)
|
||||
}
|
||||
|
||||
// lastGlobalLocked is whether the form's user is the only global one, whose role
|
||||
@@ -206,7 +212,8 @@ func (h *Handlers) submitUserCreate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// The user, the e-mail and the reach in one transaction: a failure leaves
|
||||
// no user rather than half of one (audit 2026-10-12, M9).
|
||||
if _, err := h.store.AddUser(store.UserChange{Username: username, PasswordHash: string(hash), Email: email, Role: role, Reach: reach}); err != nil {
|
||||
id, err := h.store.AddUser(store.UserChange{Username: username, PasswordHash: string(hash), Email: email, Role: role, Reach: reach})
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUserExists) {
|
||||
h.renderUserForm(w, r, http.StatusConflict, 0, userFormView{FormErr: "That username is already in use.", FormUsername: username, FormEmail: email, FormRole: string(role), Reach: reach})
|
||||
return
|
||||
@@ -219,6 +226,11 @@ func (h *Handlers) submitUserCreate(w http.ResponseWriter, r *http.Request) {
|
||||
h.renderUserForm(w, r, http.StatusInternalServerError, 0, userFormView{FormErr: "Could not create user. Please check the logs."})
|
||||
return
|
||||
}
|
||||
// An address typed for a user is unconfirmed until that user opens its
|
||||
// link (roadmap password-reset).
|
||||
if email != "" {
|
||||
h.sendConfirmation(id)
|
||||
}
|
||||
http.Redirect(w, r, "/server/users?done=created", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -316,6 +328,10 @@ func (h *Handlers) submitUserUpdate(w http.ResponseWriter, r *http.Request, u st
|
||||
}
|
||||
if password != "" {
|
||||
h.endSessionsAfterPasswordSet(r, p, u)
|
||||
h.endResetLinks(u.ID)
|
||||
}
|
||||
if email != "" && email != u.Email {
|
||||
h.sendConfirmation(u.ID)
|
||||
}
|
||||
http.Redirect(w, r, "/server/users?done=updated", http.StatusSeeOther)
|
||||
}
|
||||
@@ -333,6 +349,14 @@ func (h *Handlers) endSessionsAfterPasswordSet(r *http.Request, by auth.Principa
|
||||
h.auth.DestroyUserSessions(u.ID)
|
||||
}
|
||||
|
||||
// endResetLinks removes the reset links of a user whose password was just set
|
||||
// on the user form: a password set another way leaves none behind it.
|
||||
func (h *Handlers) endResetLinks(userID int64) {
|
||||
if err := h.store.DeleteUserLinks(userID, store.LinkReset); err != nil {
|
||||
logf("panel: user form: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserDeleteConfirm shows the cascade warning before a panel user is
|
||||
// removed — the same pattern as HandleDeleteConfirm for domains, so a single
|
||||
// mis-click on Delete cannot remove a user (P3, code-review.md).
|
||||
|
||||
Reference in New Issue
Block a user