odysseus-dev/odysseus · error · HTTPException

Not your image

Error message

Not your image

What it means

HTTP 403 raised by POST /api/gallery/{image_id}/replace when the authenticated user does not own the target GalleryImage row. The handler compares img.owner (the DB owner column) against the username resolved by get_current_user(request); a missing session user or a mismatched owner both trigger it. It is an authorization guard, not a library error.

Source

Thrown at routes/gallery/gallery_routes.py:444

            resp = {"ok": True, "filename": filename, "id": img_id}
            if exif.get("exif_error"):
                resp["exif_warning"] = exif["exif_error"]
            return resp
        finally:
            db.close()

    # ---- POST /api/gallery/{id}/replace ----
    @router.post("/api/gallery/{image_id}/replace")
    async def gallery_replace(request: Request, image_id: str):
        """Replace an existing gallery image file with a new one."""
        user = get_current_user(request)
        db = SessionLocal()
        try:
            img = db.query(GalleryImage).filter(GalleryImage.id == image_id).first()
            if not img:
                raise HTTPException(404, "Image not found")
            if not user or img.owner != user:
                raise HTTPException(403, "Not your image")

            form = await request.form()
            file = form.get("image")
            if not file or not hasattr(file, 'read'):
                raise HTTPException(400, "No image provided")

            content = await read_upload_limited(file, GALLERY_UPLOAD_MAX_BYTES, "Gallery replacement")
            GALLERY_IMAGE_DIR.mkdir(parents=True, exist_ok=True)
            img_path = _gallery_image_path(img.filename)
            img_path.write_bytes(content)

            # Refresh dimensions in case the editor resized the canvas.
            # updated_at auto-bumps via TimestampMixin's onupdate hook.
            try:
                from PIL import Image
                from io import BytesIO
                with Image.open(BytesIO(content)) as new_im:
                    img.width = new_im.width

View on GitHub (pinned to f9235ebbf1)

Solutions

  1. Verify the session cookie/token is valid and the user is logged in before initiating the replace.
  2. Confirm the image_id being replaced was returned by a gallery list call for the same user (frontend id drift after refresh).
  3. If the owner column is wrong after an account rename/migration, fix the owner values in the DB.
  4. Treat 403 as terminal for that id: do not retry, prompt the user or reload the gallery.

Example fix

// before
await fetch(`/api/gallery/${imageId}/replace`, {method:'POST', body}); // 403 surprises user
// after
if (!image.ownerIsCurrentUser) { alert('You can only replace your own uploads'); return; }
await fetch(`/api/gallery/${imageId}/replace`, {method:'POST', body});
Defensive patterns

Strategy: validation

Validate before calling

const canReplace = image && image.owner === currentUser;
if (!canReplace) throw new Error('Not your image');

Type guard

const isOwnedBy = (img, user) => Boolean(img && user && img.owner === user);

Try / catch

try { await replaceImage(id, fd); } catch (e) { if (e.status === 403) { await refreshSession(); showError('You can only replace your own images'); return; } throw e; }

Prevention

When it happens

Trigger: POST /api/gallery/{id}/replace where the image id belongs to another user, or where get_current_user returns None/falsy because the session cookie is absent, expired, or the token is invalid.

Common situations: Shared or multi-user deployments where image ids are enumerable; logged-out browser tabs with stale cookies; frontend sending the upload to the wrong image id after a gallery refresh; impersonating/renamed user accounts so img.owner no longer matches.

Related errors


AI-assisted analysis of odysseus-dev/odysseus@f9235ebbf1 (2026-08-14). Data as JSON: /api/errors/76413d723aa1b9ad. Report an issue: GitHub.