Files
pages/internal/server/profile_handler.go
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
2026-11-01 15:23:31 +09:00

285 lines
10 KiB
Go

package server
import (
"database/sql"
"errors"
"html/template"
"io"
"mime"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"pageswiki/internal/store"
)
func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) {
principal, err := s.store.PrincipalForSession(s.domainUUIDForRequest(r), s.authTokenFromRequest(r))
if err != nil {
s.authRequired(w, r)
return
}
http.Redirect(w, r, "/u/"+url.PathEscape(principal.Username)+"/_/edit", http.StatusFound)
}
func profileHost(r *http.Request) string {
host := r.Host
if value, _, err := net.SplitHostPort(host); err == nil {
host = value
}
return strings.TrimSuffix(strings.ToLower(host), ".")
}
func (s *Server) handleUserProfile(w http.ResponseWriter, r *http.Request) {
domainUUID := s.domainUUIDForRequest(r)
relative := strings.Trim(strings.TrimPrefix(r.URL.Path, "/u/"), "/")
parts := strings.Split(relative, "/")
if len(parts) == 0 || parts[0] == "" {
http.NotFound(w, r)
return
}
username, err := url.PathUnescape(parts[0])
if err != nil {
http.NotFound(w, r)
return
}
profile, err := s.store.PrincipalByUsername(domainUUID, username)
if err != nil {
http.NotFound(w, r)
return
}
viewer, viewerErr := s.store.PrincipalForSession(domainUUID, s.authTokenFromRequest(r))
if viewerErr != nil {
if s.servePublicUserSpace(w, r) {
return
}
s.authRequired(w, r)
return
}
if len(parts) > 1 && parts[1] != "_" {
allowed, audienceErr := s.store.UserSpaceCanReadAuthenticated(r.Context(), domainUUID, viewer.UUID, r.URL.Path)
if audienceErr != nil || !allowed {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
s.handleSemanticRoute(w, r)
return
}
if len(parts) > 1 && !(len(parts) == 3 && (parts[2] == "edit" || parts[2] == "avatar")) {
http.NotFound(w, r)
return
}
if len(parts) == 3 && parts[2] == "avatar" {
allowed, audienceErr := s.store.UserSpaceCanReadAuthenticated(r.Context(), domainUUID, viewer.UUID, "/u/"+profile.Username+"/_/avatar")
if audienceErr != nil || !allowed {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
s.serveProfileAvatar(w, r, profile.UUID)
return
}
editing := len(parts) == 3 && parts[2] == "edit"
if editing {
current := viewer
if current.UUID != profile.UUID {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if r.Method == http.MethodPost {
r.Body = http.MaxBytesReader(w, r.Body, 6<<20)
contentType, _, parseTypeErr := mime.ParseMediaType(r.Header.Get("Content-Type"))
var parseErr error
switch contentType {
case "multipart/form-data":
parseErr = r.ParseMultipartForm(6 << 20)
case "application/x-www-form-urlencoded":
parseErr = r.ParseForm()
default:
if parseTypeErr != nil {
parseErr = parseTypeErr
} else {
parseErr = http.ErrNotMultipart
}
}
if parseErr != nil {
http.Error(w, parseErr.Error(), http.StatusBadRequest)
return
}
action := r.FormValue("action")
if action == "contact" {
version, err := strconv.ParseInt(r.FormValue("contact_version"), 10, 64)
if err != nil {
http.Error(w, "invalid contact version", http.StatusBadRequest)
return
}
err = s.store.SaveProfileContact(r.Context(), domainUUID, current.UUID, store.ProfileContact{PhoneDisplay: r.FormValue("phone"), Visibility: r.FormValue("contact_visibility"), Version: version}, r.FormValue("contact_confirm_public") == "on")
if err != nil {
status := http.StatusBadRequest
if errors.Is(err, store.ErrGovernanceConflict) {
status = http.StatusConflict
}
http.Error(w, translate(s.getLocale(domainUUID), err.Error()), status)
return
}
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?contact=saved#contact", http.StatusSeeOther)
return
}
if action == "visibility" {
version, parseErr := strconv.ParseInt(r.FormValue("visibility_version"), 10, 64)
if parseErr != nil {
http.Error(w, "invalid visibility version", http.StatusBadRequest)
return
}
policy := store.UserSpacePolicy{
PrincipalUUID: current.UUID, Username: current.Username, Version: version,
ProfileVisibility: r.FormValue("profile_visibility"), AvatarVisibility: r.FormValue("avatar_visibility"),
RootVisibility: r.FormValue("root_visibility"), DescendantVisibility: r.FormValue("descendant_visibility"),
}
paths, values := r.Form["visibility_path"], r.Form["visibility_value"]
if len(paths) != len(values) || len(paths) > 512 {
http.Error(w, "invalid visibility overrides", http.StatusBadRequest)
return
}
for i, itemPath := range paths {
if values[i] == "inherit" || strings.TrimSpace(itemPath) == "" {
continue
}
policy.Overrides = append(policy.Overrides, store.UserSpacePathPolicy{Path: itemPath, Visibility: values[i]})
}
if _, saveErr := s.store.SaveUserSpacePolicy(r.Context(), domainUUID, current.UUID, policy); saveErr != nil {
status := http.StatusBadRequest
if errors.Is(saveErr, store.ErrGovernanceConflict) {
status = http.StatusConflict
}
http.Error(w, translate(s.getLocale(domainUUID), saveErr.Error()), status)
return
}
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?visibility=saved", http.StatusSeeOther)
return
}
if action == "totp_begin" {
if _, err := s.store.BeginTOTPEnrollment(current.UUID); err != nil {
http.Error(w, err.Error(), 500)
return
}
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?totp=pending", http.StatusSeeOther)
return
}
if action == "totp_confirm" {
if err := s.store.ConfirmTOTPEnrollment(current.UUID, r.FormValue("code")); err != nil {
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?totp=invalid", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?totp=enabled", http.StatusSeeOther)
return
}
if action == "totp_disable" {
if err := s.store.DisableTOTP(current.UUID); err != nil {
http.Error(w, err.Error(), 500)
return
}
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?totp=disabled", http.StatusSeeOther)
return
}
if err := s.store.UpdatePrincipalProfile(current.UUID, r.FormValue("display_name"), r.FormValue("email")); err != nil {
http.Error(w, err.Error(), 400)
return
}
file, _, fileErr := r.FormFile("avatar")
if fileErr == nil {
defer file.Close()
data, readErr := io.ReadAll(io.LimitReader(file, (5<<20)+1))
if readErr != nil || len(data) > 5<<20 {
http.Error(w, "avatar exceeds 5 MiB", 413)
return
}
contentType := http.DetectContentType(data)
if contentType != "image/jpeg" && contentType != "image/png" && contentType != "image/gif" && contentType != "image/webp" {
http.Error(w, "unsupported avatar image", 400)
return
}
if err := s.store.SetPrincipalAvatar(current.UUID, contentType, data); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
http.Redirect(w, r, "/u/"+url.PathEscape(profile.Username)+"/_/edit?saved=1", http.StatusSeeOther)
return
}
profile.DisplayName, profile.Email, profile.HasAvatar = current.DisplayName, current.Email, current.HasAvatar
}
visibility, visibilityErr := s.store.UserSpacePolicy(r.Context(), domainUUID, profile.UUID)
if visibilityErr != nil {
http.Error(w, "user visibility unavailable", http.StatusServiceUnavailable)
return
}
isOwnerOrAdmin := viewer.UUID == profile.UUID || s.store.IsBuiltinGroupAdmin(domainUUID, viewer.UUID, "domain_admin")
canProfile := isOwnerOrAdmin || visibility.ProfileVisibility != "private"
canRoot := isOwnerOrAdmin || visibility.RootVisibility != "private"
if !editing && !canProfile && !canRoot {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if !editing && !canProfile {
profile.DisplayName, profile.Email = profile.Username, ""
}
if !editing && !(isOwnerOrAdmin || visibility.AvatarVisibility != "private") {
profile.HasAvatar = false
}
rendered := ""
if !editing && canRoot && s.pathReadFilter(r)("/u/"+profile.Username) {
objectUUID, resolveErr := s.store.ResolvePathInDomain(domainUUID, "/u/"+profile.Username)
if resolveErr == nil {
if revision, latestErr := s.latestRevisionForRequest(r, objectUUID); latestErr == nil {
view := revisionContentView(revision, "/u/"+profile.Username)
if view.Kind == "html" {
rendered = s.safeHTMLProjection(r, revision.Body, "/u/"+profile.Username, true)
}
}
} else if !errors.Is(resolveErr, sql.ErrNoRows) {
http.Error(w, resolveErr.Error(), 500)
return
}
}
pendingSecret := ""
totpEnabled := false
if editing {
pendingSecret = s.store.PendingTOTPSecret(profile.UUID)
totpEnabled = s.store.HasTOTP(profile.UUID)
}
var userPages []store.UserSpacePage
if editing {
userPages, _ = s.store.ListUserSpacePages(r.Context(), domainUUID, profile.UUID, 512)
}
contact, contactErr := s.store.ProfileContactForViewer(r.Context(), domainUUID, profile.UUID, viewer.UUID)
if contactErr != nil {
http.Error(w, "contact unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Cache-Control", "private, no-store")
s.renderWithContext(w, r, "profile.gohtml", map[string]any{"Principal": profile, "Editing": editing, "Saved": r.URL.Query().Get("saved") == "1", "VisibilitySaved": r.URL.Query().Get("visibility") == "saved", "Handle": profile.Username + "@" + profileHost(r), "RenderedHTML": template.HTML(rendered), "TOTPEnabled": totpEnabled, "TOTPSecret": pendingSecret, "TOTPUri": store.TOTPURI(pendingSecret, profile.Username, s.getWikiName(domainUUID)), "TOTPStatus": r.URL.Query().Get("totp"), "UserSpacePolicy": visibility, "UserSpacePages": userPages, "Contact": contact, "ContactHref": profileContactHref(contact), "ContactSaved": r.URL.Query().Get("contact") == "saved", "Locale": s.getLocale(domainUUID)})
}
func profileContactHref(contact store.ProfileContact) template.URL {
_, number, err := store.NormalizeContactPhone(contact.PhoneNumber)
if err != nil || number == "" {
return ""
}
// Only digits and an optional leading '+' survive validation above.
return template.URL("tel:" + number)
}
func (s *Server) serveProfileAvatar(w http.ResponseWriter, r *http.Request, principalUUID string) {
contentType, data, err := s.store.PrincipalAvatar(principalUUID)
if err != nil || len(data) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", "private, max-age=300")
w.Header().Add("Vary", "Cookie, Authorization")
_, _ = w.Write(data)
}