@@ -0,0 +1,141 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +package auth |
| 4 | + |
| 5 | +import ( |
| 6 | + "bytes" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + |
| 11 | + "github.com/jackc/pgx/v5/pgtype" |
| 12 | + |
| 13 | + "github.com/tenseleyFlow/shithub/internal/avatars" |
| 14 | + "github.com/tenseleyFlow/shithub/internal/infra/storage" |
| 15 | + usersdb "github.com/tenseleyFlow/shithub/internal/users/sqlc" |
| 16 | + "github.com/tenseleyFlow/shithub/internal/web/middleware" |
| 17 | +) |
| 18 | + |
| 19 | +// avatarUploadCap is the multipart-parse cap. Slightly larger than the |
| 20 | +// per-image cap inside `avatars.Process` to leave room for the form |
| 21 | +// envelope without rejecting valid uploads. |
| 22 | +const avatarUploadCap = avatars.MaxUploadBytes + 64*1024 |
| 23 | + |
| 24 | +// settingsAvatarUpload handles POST /settings/profile/avatar. |
| 25 | +// |
| 26 | +// On success: writes 3 PNG variants to the object store, points the |
| 27 | +// user's avatar_object_key at the largest variant, and redirects back |
| 28 | +// to /settings/profile with a flash on the next render. |
| 29 | +func (h *Handlers) settingsAvatarUpload(w http.ResponseWriter, r *http.Request) { |
| 30 | + if h.d.ObjectStore == nil { |
| 31 | + h.d.Render.HTTPError(w, r, http.StatusServiceUnavailable, "avatar storage is not configured") |
| 32 | + return |
| 33 | + } |
| 34 | + // Hard cap on the request body BEFORE multipart parsing so a large |
| 35 | + // upload can't soak memory even via the chunked-encoding path. |
| 36 | + r.Body = http.MaxBytesReader(w, r.Body, avatarUploadCap) |
| 37 | + //nolint:gosec // G120 false positive: avatarUploadCap is a constant bound, and MaxBytesReader above is the real cap. |
| 38 | + if err := r.ParseMultipartForm(avatarUploadCap); err != nil { |
| 39 | + h.renderAvatarError(w, r, "Could not parse upload (file too large?).") |
| 40 | + return |
| 41 | + } |
| 42 | + defer func() { |
| 43 | + if r.MultipartForm != nil { |
| 44 | + _ = r.MultipartForm.RemoveAll() |
| 45 | + } |
| 46 | + }() |
| 47 | + |
| 48 | + file, _, err := r.FormFile("avatar") |
| 49 | + if err != nil { |
| 50 | + h.renderAvatarError(w, r, "Choose a file to upload.") |
| 51 | + return |
| 52 | + } |
| 53 | + defer func() { _ = file.Close() }() |
| 54 | + |
| 55 | + variants, hash, err := avatars.Process(file) |
| 56 | + if err != nil { |
| 57 | + h.renderAvatarError(w, r, friendlyAvatarError(err)) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + user := middleware.CurrentUserFromContext(r.Context()) |
| 62 | + prefix := fmt.Sprintf("avatars/%d/%s", user.ID, hash) |
| 63 | + // Largest variant lives at <prefix>.png and is what the public |
| 64 | + // avatar route serves. |
| 65 | + largestKey := prefix + ".png" |
| 66 | + for _, v := range variants { |
| 67 | + key := fmt.Sprintf("%s-%d.png", prefix, v.Size) |
| 68 | + if v.Size == variants[0].Size { |
| 69 | + key = largestKey |
| 70 | + } |
| 71 | + if _, err := h.d.ObjectStore.Put(r.Context(), key, |
| 72 | + bytes.NewReader(v.Data), |
| 73 | + storage.PutOpts{ContentType: "image/png", ContentLength: int64(len(v.Data))}, |
| 74 | + ); err != nil { |
| 75 | + h.d.Logger.ErrorContext(r.Context(), "avatar: put", "error", err, "key", key) |
| 76 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 77 | + return |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + if err := h.q.UpdateUserAvatarKey(r.Context(), h.d.Pool, usersdb.UpdateUserAvatarKeyParams{ |
| 82 | + ID: user.ID, |
| 83 | + AvatarObjectKey: pgtype.Text{String: largestKey, Valid: true}, |
| 84 | + }); err != nil { |
| 85 | + h.d.Logger.ErrorContext(r.Context(), "avatar: db update", "error", err) |
| 86 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 87 | + return |
| 88 | + } |
| 89 | + |
| 90 | + http.Redirect(w, r, "/settings/profile", http.StatusSeeOther) |
| 91 | +} |
| 92 | + |
| 93 | +// settingsAvatarRemove handles POST /settings/profile/avatar/remove. |
| 94 | +// |
| 95 | +// We clear avatar_object_key on the user but DO NOT delete the stored |
| 96 | +// objects. The current key is content-addressed so future uploads land |
| 97 | +// at a new path; old objects stop being referenced and a future |
| 98 | +// orphan-sweep job (post-MVP) will purge them. |
| 99 | +func (h *Handlers) settingsAvatarRemove(w http.ResponseWriter, r *http.Request) { |
| 100 | + user := middleware.CurrentUserFromContext(r.Context()) |
| 101 | + if err := h.q.UpdateUserAvatarKey(r.Context(), h.d.Pool, usersdb.UpdateUserAvatarKeyParams{ |
| 102 | + ID: user.ID, |
| 103 | + AvatarObjectKey: pgtype.Text{Valid: false}, |
| 104 | + }); err != nil { |
| 105 | + h.d.Logger.ErrorContext(r.Context(), "avatar: db clear", "error", err) |
| 106 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 107 | + return |
| 108 | + } |
| 109 | + http.Redirect(w, r, "/settings/profile", http.StatusSeeOther) |
| 110 | +} |
| 111 | + |
| 112 | +func (h *Handlers) renderAvatarError(w http.ResponseWriter, r *http.Request, msg string) { |
| 113 | + row, err := h.q.GetUserByID(r.Context(), h.d.Pool, middleware.CurrentUserFromContext(r.Context()).ID) |
| 114 | + if err != nil { |
| 115 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 116 | + return |
| 117 | + } |
| 118 | + h.renderProfileForm(w, r, profileForm{ |
| 119 | + DisplayName: row.DisplayName, |
| 120 | + Bio: row.Bio, |
| 121 | + Location: row.Location, |
| 122 | + Website: row.Website, |
| 123 | + Company: row.Company, |
| 124 | + Pronouns: row.Pronouns, |
| 125 | + }, msg, "") |
| 126 | +} |
| 127 | + |
| 128 | +func friendlyAvatarError(err error) string { |
| 129 | + switch { |
| 130 | + case errors.Is(err, avatars.ErrTooLarge): |
| 131 | + return "Image is too large (max 5 MB)." |
| 132 | + case errors.Is(err, avatars.ErrUnsupported): |
| 133 | + return "That format isn't accepted. Use PNG, JPEG, or GIF." |
| 134 | + case errors.Is(err, avatars.ErrDecompression): |
| 135 | + return "Image dimensions are too large." |
| 136 | + case errors.Is(err, avatars.ErrDecode): |
| 137 | + return "We couldn't decode that image." |
| 138 | + default: |
| 139 | + return "Could not process upload." |
| 140 | + } |
| 141 | +} |