Stage 2, step 6. Written by Sonnet, reviewed by Opus.
- Six pages named after their mockups: system-log, backup, users,
user, user-delete, help, with typed page data (view/server.go,
help.go), fixtures and tests. The old templates of the six are gone
(user_form.html, encrypt_fields.html deleted, the others rewritten)
and their names are off legacy_pages.txt, which now holds mail_queue
alone.
- Help is six help_topic blocks (checks, certificate, rdns, dns, apps,
limits); a test renders every fixture page and fails on a Help link
without a topic. The help drawer (help_drawer.html and its includes
in layout_legacy.html) is removed; its rules in legacy.css go with
the next step.
- The user form sets the user's e-mail (plan, Account e-mail): create
and update, validated, and a changed address resyncs DMARC for a
user whose default is the account e-mail - through the helper the
Account profile now shares.
- Handlers pass typed data; routes, POST targets, field names,
validation and authorization are unchanged. A test loads the user
form for four reach combinations and for the only global user, posts
it back untouched and finds the user unchanged.
Fixed on the way
- The user delete confirmation said the domains were not affected. A
domain that follows the user's default report address is left with
none; the page names those domains now.
- A refused backup lost the encryption choice and printed a literal
<code> element in its message.
Differences from the mockups, for the owner:
- Help has no DMARC and no Inbound topic: its outline fixes two boxes
of three topics, although other mockups link to #dmarc and #inbound.
Until the owner decides, Account's Help link goes to #dns and the
inbound MX box has none;
- system log: newest line first, as drawn; "refreshes on its own" (5 s
active, 30 s idle); only status=, warning: and error: lines are
coloured;
- backup: the file field is a plain file input; the encryption box is
ticked, as drawn and as on the domain export, so a plain download
means unticking it first;
- users: an E-mail column; the flash does not name the user;
- user form: no lead; the domain lists are no longer hidden by script
when Global is chosen (the server ignores them for that role).
Evidence
- docs/assets/panel-redesign/evidence/system-log.png, backup.png,
users.png, user.png, user-delete.png, help.png: 1440 px wide,
headless Edge, real templates served locally with their fixtures -
NOT from the container (no Docker on this machine).
- panel/audit.js on the six pages at 1440 and 1280: 720 texts checked,
problems: [].
- The system log's polling swap was not exercised in a browser; it
uses the mechanism of Overview and Health.
- go test -count=1 ./internal/web/... ./cmd/panel
ok internal/web
ok internal/web/auth
ok internal/web/handlers
ok internal/web/validate
ok internal/web/view
ok cmd/panel
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
298 lines
10 KiB
Go
298 lines
10 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/mixeme/selfpost/internal/dnscheck"
|
|
"github.com/mixeme/selfpost/internal/store"
|
|
"github.com/mixeme/selfpost/internal/web/validate"
|
|
"github.com/mixeme/selfpost/internal/web/view"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// Account is the signed-in user's own half of what used to be one Settings
|
|
// page: who they are to the panel (username, e-mail), their password, and their
|
|
// default DMARC report address. Every role has it. Each part is its own form
|
|
// and its own POST, so changing one never asks for the others.
|
|
//
|
|
// The e-mail is the user's — what the panel writes to. The DMARC default is a
|
|
// separate choice that may use it: a domain whose report address is "this
|
|
// user's default" resolves to whatever is chosen here (store.DMARCDefault).
|
|
|
|
// accountForm is what the page shows back: the stored values, or the ones just
|
|
// submitted when a form is re-rendered with an error.
|
|
type accountForm struct {
|
|
Err string
|
|
Username string
|
|
Email string
|
|
DMARCMode string
|
|
DMARCAddress string
|
|
}
|
|
|
|
func (h *Handlers) accountUser(w http.ResponseWriter, r *http.Request) (store.User, bool) {
|
|
p, ok := h.principal(r)
|
|
if !ok {
|
|
http.NotFound(w, r)
|
|
return store.User{}, false
|
|
}
|
|
u, err := h.store.GetUser(p.ID)
|
|
if err != nil {
|
|
logf("panel: account: get user %d: %v", p.ID, err)
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return store.User{}, false
|
|
}
|
|
return u, true
|
|
}
|
|
|
|
func formOf(u store.User) accountForm {
|
|
return accountForm{Username: u.Username, Email: u.Email, DMARCMode: u.DMARCDefaultMode, DMARCAddress: u.DMARCDefaultAddress}
|
|
}
|
|
|
|
// HandleAccount shows the Account page.
|
|
func (h *Handlers) HandleAccount(w http.ResponseWriter, r *http.Request) {
|
|
u, ok := h.accountUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
h.renderAccount(w, r, http.StatusOK, u, formOf(u))
|
|
}
|
|
|
|
func (h *Handlers) renderAccount(w http.ResponseWriter, r *http.Request, status int, u store.User, f accountForm) {
|
|
hosted := h.dmarc != nil && h.cfg.DMARCEnabled
|
|
page := view.NewAccount(h.shellMeta(r), string(u.Role), hosted, u.Email)
|
|
page.Username, page.Email = f.Username, f.Email
|
|
page.DMARCSelected, page.DMARCAddress = f.DMARCMode, f.DMARCAddress
|
|
page.WithResult(accountFlash(r), f.Err)
|
|
page.WithDomainUse(h.domainsFollowing(r, u))
|
|
|
|
// The stored default, not the one being typed: the authorization record
|
|
// belongs to the address domains are actually told to publish.
|
|
def := u.DMARCDefault()
|
|
if addr := def.Resolve(""); addr != "" && def.Mode != store.DMARCDefaultHosted {
|
|
if hub := dnscheck.EmailDomain(addr); hub != "" {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
ra := h.dns.ReportAuth(ctx, hub)
|
|
cancel()
|
|
page.WithAuthorization(dnscheck.ReportAuthRecordName(hub), dnscheck.ReportAuthExample(),
|
|
string(ra.Status), ra.Detail, ra.Records)
|
|
}
|
|
}
|
|
h.view.Render(w, status, "account", page)
|
|
}
|
|
|
|
// domainsFollowing counts the outbound domains the user reaches and how many of
|
|
// them take their report address from this user's default.
|
|
func (h *Handlers) domainsFollowing(r *http.Request, u store.User) (following, total int) {
|
|
p, ok := h.principal(r)
|
|
if !ok {
|
|
return 0, 0
|
|
}
|
|
domains, err := h.assignedDomains(p)
|
|
if err != nil {
|
|
logf("panel: account: list domains: %v", err)
|
|
return 0, 0
|
|
}
|
|
for _, d := range domains {
|
|
if d.DMARCRuaUserID.Valid && d.DMARCRuaUserID.Int64 == u.ID {
|
|
following++
|
|
}
|
|
}
|
|
return following, len(domains)
|
|
}
|
|
|
|
func accountFlash(r *http.Request) string {
|
|
switch r.URL.Query().Get("done") {
|
|
case "profile":
|
|
return "Profile saved."
|
|
case "password":
|
|
return "Password changed. Any other signed-in sessions were signed out."
|
|
case "dmarc":
|
|
return "Default report address saved."
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// HandleAccountProfile saves the username and the account e-mail.
|
|
func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request) {
|
|
u, ok := h.accountUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
f := formOf(u)
|
|
fail := func(status int, msg string) {
|
|
f.Err = msg
|
|
h.renderAccount(w, r, status, u, f)
|
|
}
|
|
if err := r.ParseForm(); err != nil {
|
|
fail(http.StatusBadRequest, "Invalid form submission.")
|
|
return
|
|
}
|
|
f.Username = strings.TrimSpace(r.PostFormValue("username"))
|
|
f.Email = strings.TrimSpace(r.PostFormValue("email"))
|
|
if f.Username == "" {
|
|
f.Username = u.Username
|
|
}
|
|
if f.Username != u.Username {
|
|
if err := validate.Username(f.Username); err != nil {
|
|
fail(http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
}
|
|
if err := validate.Email(f.Email); err != nil {
|
|
fail(http.StatusBadRequest, err.Error())
|
|
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.")
|
|
return
|
|
}
|
|
logf("panel: account: update user %d: %v", u.ID, err)
|
|
fail(http.StatusInternalServerError, "Could not save the profile. Please check the logs and try again.")
|
|
return
|
|
}
|
|
if f.Username != u.Username {
|
|
if token, ok := h.auth.SessionToken(r); ok {
|
|
h.auth.RenameSession(token, f.Username)
|
|
}
|
|
}
|
|
// The e-mail is the report address of every domain that follows this
|
|
// user's "my account e-mail" default.
|
|
h.resyncAfterEmailChange(u, f.Email)
|
|
logf("panel: user %d profile updated (username: %t, e-mail: %t)", u.ID, f.Username != u.Username, f.Email != u.Email)
|
|
http.Redirect(w, r, "/account?done=profile", http.StatusSeeOther)
|
|
}
|
|
|
|
// 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.
|
|
func (h *Handlers) HandleAccountPassword(w http.ResponseWriter, r *http.Request) {
|
|
u, ok := h.accountUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
f := formOf(u)
|
|
fail := func(status int, msg string) {
|
|
f.Err = msg
|
|
h.renderAccount(w, r, status, u, f)
|
|
}
|
|
if !h.auth.AllowLoginAttempt(r) {
|
|
fail(http.StatusTooManyRequests, "Too many attempts. Please wait and try again.")
|
|
return
|
|
}
|
|
if err := r.ParseForm(); err != nil {
|
|
fail(http.StatusBadRequest, "Invalid form submission.")
|
|
return
|
|
}
|
|
current := r.PostFormValue("current_password")
|
|
password := r.PostFormValue("new_password")
|
|
confirm := r.PostFormValue("new_password_confirm")
|
|
if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(current)); err != nil {
|
|
fail(http.StatusUnauthorized, "Current password is incorrect.")
|
|
return
|
|
}
|
|
if password != confirm {
|
|
fail(http.StatusBadRequest, "New passwords do not match.")
|
|
return
|
|
}
|
|
if err := validate.AdminPassword(password); err != nil {
|
|
fail(http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
|
|
if err != nil {
|
|
logf("panel: account: hashing password failed: %v", err)
|
|
fail(http.StatusInternalServerError, "Internal error. Please try again.")
|
|
return
|
|
}
|
|
if err := h.store.UpdateUser(u.ID, u.Username, string(hash), u.Email); err != nil {
|
|
logf("panel: account: update password of user %d: %v", u.ID, err)
|
|
fail(http.StatusInternalServerError, "Could not save the password. Please check the logs and try again.")
|
|
return
|
|
}
|
|
if token, ok := h.auth.SessionToken(r); ok {
|
|
h.auth.DestroyOtherSessions(token)
|
|
}
|
|
logf("panel: user %d changed their password", u.ID)
|
|
http.Redirect(w, r, "/account?done=password", http.StatusSeeOther)
|
|
}
|
|
|
|
// HandleAccountDMARC saves the user's default report address: SelfPost hosted,
|
|
// the account e-mail, another address, or none.
|
|
func (h *Handlers) HandleAccountDMARC(w http.ResponseWriter, r *http.Request) {
|
|
u, ok := h.accountUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
f := formOf(u)
|
|
fail := func(status int, msg string) {
|
|
f.Err = msg
|
|
h.renderAccount(w, r, status, u, f)
|
|
}
|
|
if err := r.ParseForm(); err != nil {
|
|
fail(http.StatusBadRequest, "Invalid form submission.")
|
|
return
|
|
}
|
|
f.DMARCMode = strings.TrimSpace(r.PostFormValue("dmarc_default"))
|
|
f.DMARCAddress = strings.TrimSpace(r.PostFormValue("dmarc_default_address"))
|
|
switch f.DMARCMode {
|
|
case store.DMARCDefaultNone:
|
|
case store.DMARCDefaultHosted:
|
|
if h.dmarc == nil || !h.dmarc.Enabled() {
|
|
fail(http.StatusBadRequest, "SelfPost-hosted reports are not enabled on this server.")
|
|
return
|
|
}
|
|
case store.DMARCDefaultAccount:
|
|
if u.Email == "" {
|
|
fail(http.StatusBadRequest, "Your account has no e-mail yet. Save one under Profile first, or choose another address.")
|
|
return
|
|
}
|
|
case store.DMARCDefaultCustom:
|
|
if f.DMARCAddress == "" {
|
|
fail(http.StatusBadRequest, "Enter the report address or choose another option.")
|
|
return
|
|
}
|
|
if err := validate.Email(f.DMARCAddress); err != nil {
|
|
fail(http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
default:
|
|
fail(http.StatusBadRequest, "Choose where your DMARC reports go.")
|
|
return
|
|
}
|
|
if err := h.store.SetDMARCDefault(u.ID, f.DMARCMode, f.DMARCAddress); err != nil {
|
|
logf("panel: account: set dmarc default of user %d: %v", u.ID, err)
|
|
fail(http.StatusInternalServerError, "Could not save the report address. Please check the logs and try again.")
|
|
return
|
|
}
|
|
h.resyncDMARC("default report address")
|
|
logf("panel: user %d set their default report address to %q", u.ID, f.DMARCMode)
|
|
http.Redirect(w, r, "/account?done=dmarc", http.StatusSeeOther)
|
|
}
|
|
|
|
// resyncAfterEmailChange is what changing a user's account e-mail does for
|
|
// DMARC: the address is the report address of every domain that follows a user
|
|
// whose default is "my account e-mail", so the ingest allow-list is rebuilt. It
|
|
// is the one path both the Account page and the user form take.
|
|
func (h *Handlers) resyncAfterEmailChange(u store.User, newEmail string) {
|
|
if newEmail != u.Email && u.DMARCDefaultMode == store.DMARCDefaultAccount {
|
|
h.resyncDMARC("account e-mail")
|
|
}
|
|
}
|
|
|
|
// resyncDMARC rebuilds the ingest allow-list after something that changes
|
|
// where a domain's reports go. A failure is logged, not shown: the setting is
|
|
// saved, and the next resync picks it up.
|
|
func (h *Handlers) resyncDMARC(why string) {
|
|
if h.dmarc == nil || !h.dmarc.Enabled() {
|
|
return
|
|
}
|
|
if err := h.dmarc.Resync(); err != nil {
|
|
logf("panel: dmarc resync after %s change: %v", why, err)
|
|
}
|
|
}
|