feat(cabana): add backend user avatars to My account and the top bar

- cabana.BackendUser is an attach.Owner (MorphName Backend\Models\User,
  cabana.BackendUserMorphType) with one public attachOne avatar
  (cabana.BackendUserAvatarField), as WinterCMS stores it
- POST /account/avatar stores one file_data image (jpg, jpeg, png, gif or
  webp, image guard, at most cabana.AvatarMaxBytes = 2 MiB, under a
  server-generated name) and replaces the previous avatar: old rows are
  deleted in the transaction, their blobs after the commit
- DELETE /account/avatar removes the avatar and is idempotent
- GET /auth/me and the account routes return avatar {url, thumb_url}
  (250x250 crop); cabana.BackendUserAvatar lets plugins read it
- swag annotations, regenerated admin.json and schema.d.ts; route
  inventories, CSRF walk (29) and OpenAPI conformance learn both routes
- SPA: avatar upload and remove on My account, avatar image in the user
  menu trigger and header; backend::lang.myaccount avatar strings
- rebuilt boardwalk dist; cabana README, users-and-permissions and
  admin-spa docs
This commit is contained in:
2026-10-09 17:45:43 +02:00
parent 143eca5a1f
commit 64d21c8caf
25 changed files with 1012 additions and 49 deletions

View File

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"slices"
@@ -13,8 +14,10 @@ import (
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"github.com/jackc/pgx/v5/pgconn"
"gocloud.dev/blob"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@@ -23,6 +26,24 @@ import (
// the key WinterCMS's Journal author component reads.
const metadataSubtitle = "subtitle"
// AvatarMaxBytes is the largest avatar image POST /account/avatar accepts:
// 2 MiB. http.body_limits.upload_bytes still caps the whole request.
const AvatarMaxBytes int64 = 2 << 20
// avatarThumbEdge is the edge of the avatar's crop thumbnail, WinterCMS's
// myaccount avatar size.
const avatarThumbEdge = 250
// avatarLimits are the attach.Store rules of an avatar: a raster image (jpg,
// jpeg, png, gif or webp, a sniffed image MIME type and the decode guard) of
// at most AvatarMaxBytes.
var avatarLimits = attach.Limits{
MaxBytes: AvatarMaxBytes,
Extensions: attach.DefaultImageExtensions,
MIMETypes: attach.AllowedImageMIMEs,
Image: true,
}
// passwordMaxBytes is bcrypt's input limit: HashPassword refuses longer input.
const passwordMaxBytes = 72
@@ -120,8 +141,10 @@ func setMetadataString(raw *string, key, value string) (*string, error) {
}
// profileFor is the AdminProfile of user, the payload of GET /auth/me and of
// the My account routes.
func (s *service) profileFor(_ context.Context, _ *gorm.DB, user BackendUser) AdminProfile {
// the My account routes. The avatar is looked up through db; a lookup or
// thumbnail failure is logged and leaves the avatar (or its thumb_url) out,
// so the profile never fails on it.
func (s *service) profileFor(ctx context.Context, db *gorm.DB, user BackendUser) AdminProfile {
profile := AdminProfile{
ID: user.ID,
Login: user.Login,
@@ -134,9 +157,60 @@ func (s *service) profileFor(_ context.Context, _ *gorm.DB, user BackendUser) Ad
if user.Role.ID != 0 {
profile.Role = &AdminRoleSummary{ID: user.Role.ID, Code: user.Role.Code, Name: user.Role.Name}
}
if db != nil {
profile.Avatar = s.avatarOf(ctx, db, user.ID)
}
return profile
}
// avatarOf is the public URL and the 250x250 crop thumbnail URL of an
// admin's avatar, or nil when there is none. A protected row (is_public
// false, possible only in copied data) has no public URL and is left out.
func (s *service) avatarOf(ctx context.Context, db *gorm.DB, userID uint) *AdminAvatar {
f, err := BackendUserAvatar(ctx, db, userID)
if err != nil {
slog.Default().WarnContext(ctx, "cabana: avatar lookup failed", "admin_id", userID, "error", err)
return nil
}
if f == nil || !f.Public() {
return nil
}
out := &AdminAvatar{URL: f.URL()}
if bucket := s.bucket(); bucket != nil && slices.Contains(attach.AllowedImageMIMEs, f.ContentType) {
thumb, err := f.Thumb(ctx, bucket, avatarThumbEdge, avatarThumbEdge, "crop")
if err != nil {
slog.Default().WarnContext(ctx, "cabana: avatar thumbnail failed", "admin_id", userID, "file_id", f.ID, "error", err)
} else {
out.ThumbURL = thumb
}
}
return out
}
// BackendUserAvatar returns a backend user's avatar: the newest system_files
// row with attachment_type cabana.BackendUserMorphType, field
// cabana.BackendUserAvatarField and the user's id, or nil, nil when there is
// none. Plugins call it to show an author's picture (File.URL, File.Thumb).
func BackendUserAvatar(ctx context.Context, db *gorm.DB, userID uint) (*attach.File, error) {
if db == nil {
return nil, errors.New("cabana: avatar lookup without a database")
}
if ctx == nil {
ctx = context.Background()
}
var files []attach.File
err := db.Session(&gorm.Session{NewDB: true, Context: ctx}).
Where("attachment_type = ? AND field = ? AND attachment_id = ?", BackendUserMorphType, BackendUserAvatarField, uitoa(userID)).
Order("id DESC").Limit(1).Find(&files).Error
if err != nil {
return nil, err
}
if len(files) == 0 {
return nil, nil
}
return &files[0], nil
}
// accountPrincipal is the signed-in backend principal, or nil after a 401
// was written.
func accountPrincipal(w http.ResponseWriter, r *http.Request) *bouncer.Principal {
@@ -430,3 +504,208 @@ func (s *service) writeAccountError(w http.ResponseWriter, r *http.Request, err
}
writeCRUDError(w, err)
}
// avatarCap is the request body cap of an avatar upload: AvatarMaxBytes plus
// the multipart framing, lowered to http.body_limits.upload_bytes.
func (s *service) avatarCap() int64 {
limit := AvatarMaxBytes + multipartOverhead
if s != nil && s.uploadBytes > 0 && s.uploadBytes < limit {
limit = s.uploadBytes
}
return limit
}
// detachAvatars deletes every avatar row of an admin inside tx and returns
// the blob keys of the originals and their thumbnails. The rows are locked
// first; the caller deletes the blobs after the commit.
func detachAvatars(ctx context.Context, tx *gorm.DB, userID uint, keep uint) ([]string, error) {
var rows []attach.File
err := tx.Session(&gorm.Session{NewDB: true, Context: ctx}).
Clauses(clause.Locking{Strength: "UPDATE"}).
Where("attachment_type = ? AND field = ? AND attachment_id = ? AND id <> ?", BackendUserMorphType, BackendUserAvatarField, uitoa(userID), keep).
Order("id").Find(&rows).Error
if err != nil || len(rows) == 0 {
return nil, err
}
ids := make([]uint, 0, len(rows))
var keys []string
for _, f := range rows {
ids = append(ids, f.ID)
keys = append(keys, attach.BlobKeys(f)...)
}
if err := tx.Session(&gorm.Session{NewDB: true, Context: ctx}).Where("id IN ?", ids).Delete(&attach.File{}).Error; err != nil {
return nil, err
}
return keys, nil
}
// deleteAvatarBlobs removes detached avatar blobs once tx has committed; a
// failure is logged and never fails the request.
func deleteAvatarBlobs(ctx context.Context, tx *gorm.DB, bucket *blob.Bucket, userID uint, keys []string) {
if len(keys) == 0 {
return
}
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
if bucket == nil {
slog.Default().WarnContext(ctx, "cabana: no storage bucket; blobs of a removed avatar were kept", "admin_id", userID)
return
}
if err := attach.DeleteKeys(context.WithoutCancel(ctx), bucket, keys); err != nil {
slog.Default().WarnContext(ctx, "cabana: deleting a removed avatar's blobs failed", "admin_id", userID, "error", err)
}
})
}
// avatarUpload serves POST /account/avatar: one multipart file_data part,
// stored through attach.Store as a public image of at most AvatarMaxBytes
// under a server-generated disk name, attached to the signed-in admin as the
// avatar attachOne. The previous avatar row is deleted in the same
// transaction and its blobs after the commit.
func (s *service) avatarUpload(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r)
if principal == nil {
return
}
db, err := s.db()
if err != nil {
slog.Default().ErrorContext(r.Context(), "cabana: avatar upload without a database", "error", err)
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return
}
bucket := s.bucket()
if bucket == nil {
slog.Default().ErrorContext(r.Context(), "cabana: avatar upload without a storage bucket")
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return
}
body := &bodyReader{r: http.MaxBytesReader(w, r.Body, s.avatarCap())}
r.Body = io.NopCloser(body)
mr, err := r.MultipartReader()
if err != nil {
writeCRUDError(w, invalidBody())
return
}
part, err := mr.NextPart()
if err != nil {
s.writeAvatarError(w, r, body, err)
return
}
if part.FormName() != "file_data" || strings.TrimSpace(part.FileName()) == "" {
writeCRUDError(w, invalidBody())
return
}
var stored *attach.File
var saved BackendUser
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
// The row lock serialises concurrent avatar changes of one admin.
user, err := lockAccount(ctx, tx, principal.ID)
if err != nil {
return err
}
// Store keeps only a sanitized base name as file_name; the disk name
// and the blob key are generated, never taken from the client.
f, err := attach.Store(ctx, tx, bucket, attach.Upload{FileName: part.FileName(), Body: part, Public: true}, avatarLimits)
if err != nil {
return err
}
stored = f
// Exactly one part: anything after file_data is refused.
if _, err := mr.NextPart(); !errors.Is(err, io.EOF) {
if err == nil {
return invalidBody()
}
return err
}
q := tx.Session(&gorm.Session{NewDB: true, Context: ctx})
if err := q.Model(&attach.File{}).Where("id = ?", f.ID).Updates(map[string]any{
"attachment_id": uitoa(user.ID),
"attachment_type": BackendUserMorphType,
"field": BackendUserAvatarField,
}).Error; err != nil {
return err
}
keys, err := detachAvatars(ctx, tx, user.ID, f.ID)
if err != nil {
return err
}
deleteAvatarBlobs(ctx, tx, bucket, user.ID, keys)
saved = user
return nil
})
if err != nil {
// attach.Store wrote the blob before the row; a rolled-back
// transaction leaves it to this caller.
if stored != nil {
_ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored))
}
s.writeAvatarError(w, r, body, err)
return
}
WriteData(w, http.StatusOK, s.profileFor(r.Context(), db, saved), map[string]any{})
}
// avatarRemove serves DELETE /account/avatar: it deletes the signed-in
// admin's avatar rows now and their blobs after the commit. Removing an
// avatar that is not there also answers 200.
func (s *service) avatarRemove(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r)
if principal == nil {
return
}
db, err := s.db()
if err != nil {
slog.Default().ErrorContext(r.Context(), "cabana: avatar removal without a database", "error", err)
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return
}
bucket := s.bucket()
var saved BackendUser
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
user, err := lockAccount(ctx, tx, principal.ID)
if err != nil {
return err
}
keys, err := detachAvatars(ctx, tx, user.ID, 0)
if err != nil {
return err
}
deleteAvatarBlobs(ctx, tx, bucket, user.ID, keys)
saved = user
return nil
})
if err != nil {
s.writeAccountError(w, r, err)
return
}
WriteData(w, http.StatusOK, s.profileFor(r.Context(), db, saved), map[string]any{})
}
// writeAvatarError maps an avatar upload failure as writeFileError does,
// with the field name avatar: a body past the cap is 413, an attach.Store
// refusal a 422 on avatar and a malformed multipart body a 422 on body.
func (s *service) writeAvatarError(w http.ResponseWriter, r *http.Request, body *bodyReader, err error) {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) || (body != nil && errors.As(body.err, &tooBig)) {
WriteError(w, http.StatusRequestEntityTooLarge, "payload_too_large", msgPayloadTooLarge)
return
}
ctx, tr := r.Context(), s.translator()
var detail string
switch {
case errors.Is(err, attach.ErrTooLarge):
detail = fieldMessage(ctx, tr, "max.file", BackendUserAvatarField, map[string]string{"max": strconv.FormatInt(AvatarMaxBytes/1024, 10)})
case errors.Is(err, attach.ErrFileType), errors.Is(err, attach.ErrMIMEType):
detail = fieldMessage(ctx, tr, "mimes", BackendUserAvatarField, map[string]string{"values": strings.Join(attach.DefaultImageExtensions, ", ")})
case errors.Is(err, attach.ErrNotImage):
detail = fieldMessage(ctx, tr, "image", BackendUserAvatarField, nil)
}
if detail != "" {
writeCRUDError(w, &ValidationError{Details: fieldDetail(BackendUserAvatarField, detail)})
return
}
if body != nil && body.err != nil {
writeCRUDError(w, invalidBody())
return
}
s.writeAccountError(w, r, err)
}