fix: allow changing recipe owner from recipe update payloads (#9054)
This commit is contained in:
1 parent
8933244814
commit
76cca686ae
3 files changed
+165
-4
No files matched your search
@@ -319,10 +319,16 @@ class RepositoryRecipes(RecipeSuggestionMixin, HouseholdRepositoryGeneric[Recipe
|
||||
if new_name := new_data.get("name"):
|
||||
new_data["slug"] = entry.slug if new_name == entry.name else create_recipe_slug(new_name)
|
||||
|
||||
# Always preserve identity/ownership fields from the existing DB entry.
|
||||
# User-provided JSON may omit or null these, which would cause integrity errors.
|
||||
for field in ("id", "user_id", "household_id", "group_id"):
|
||||
new_data[field] = getattr(entry, field)
|
||||
# Never let a payload move the row onto another recipe, or out of this group.
|
||||
new_data["id"] = entry.id
|
||||
new_data["group_id"] = entry.group_id
|
||||
|
||||
# Ownership may be reassigned by the payload (validated by RecipeService);
|
||||
# a missing or null owner/household keeps the stored one, so payloads that
|
||||
# omit them can't cause integrity errors.
|
||||
for field in ("user_id", "household_id"):
|
||||
if new_data.get(field) is None:
|
||||
new_data[field] = getattr(entry, field)
|
||||
|
||||
# If slug is still missing after name-based recalculation, fall back to existing slug.
|
||||
if not new_data.get("slug"):
|
||||
|
||||
@@ -659,6 +659,51 @@ class RecipeService(RecipeServiceBase):
|
||||
|
||||
return recipe
|
||||
|
||||
def _validate_reassignment(self, recipe: RecipeOut, new_data: RecipeDraft) -> RecipeDraft:
|
||||
"""Validates an ownership change, keeping every other field as-is.
|
||||
|
||||
Updates normally leave ownership alone: the repository keeps the stored owner
|
||||
whenever the payload doesn't name one. When the payload does name a different
|
||||
owner or household, that request may only come from the recipe owner or an
|
||||
admin, and the new owner and household must belong to this group. Unless the
|
||||
payload explicitly moves the recipe to another household, its household
|
||||
becomes the new owner's household, so the new owner finds the recipe in
|
||||
their own household.
|
||||
"""
|
||||
new_user_id = (
|
||||
new_data.user_id if new_data.user_id is not None and str(new_data.user_id) != str(recipe.user_id) else None
|
||||
)
|
||||
new_household_id = (
|
||||
new_data.household_id
|
||||
if new_data.household_id is not None and str(new_data.household_id) != str(recipe.household_id)
|
||||
else None
|
||||
)
|
||||
|
||||
if new_user_id is None and new_household_id is None:
|
||||
return new_data
|
||||
|
||||
if not self.user.admin and str(recipe.user_id) != str(self.user.id):
|
||||
raise exceptions.PermissionDenied(
|
||||
"Only the recipe owner or an admin can change the recipe's owner or household."
|
||||
)
|
||||
|
||||
if new_user_id is not None:
|
||||
new_owner = self.repos.users.get_one(new_user_id)
|
||||
if new_owner is None:
|
||||
raise exceptions.NoEntryFound(f"User with id '{new_user_id}' not found in this group")
|
||||
|
||||
# the UI sends only the new owner, so default that owner's household
|
||||
if new_household_id is None:
|
||||
new_household_id = new_owner.household_id
|
||||
new_data = new_data.model_copy(update={"household_id": new_household_id})
|
||||
|
||||
if new_household_id is not None:
|
||||
household = self.repos.households.get_one(new_household_id)
|
||||
if household is None or str(household.group_id) != str(self.user.group_id):
|
||||
raise exceptions.NoEntryFound(f"Household with id '{new_household_id}' not found in this group")
|
||||
|
||||
return new_data
|
||||
|
||||
@staticmethod
|
||||
def _preserve_omitted_image(recipe: RecipeOut, update_data: RecipeDraft) -> RecipeDraft:
|
||||
"""Keeps the stored image when the payload doesn't mention it.
|
||||
@@ -735,6 +780,7 @@ class RecipeService(RecipeServiceBase):
|
||||
update_data = self._remove_non_existent_ingredient_references(update_data)
|
||||
update_data = self._remove_non_existent_note_references(update_data)
|
||||
update_data = self._resolve_ingredient_sub_recipes(update_data)
|
||||
update_data = self._validate_reassignment(recipe, update_data)
|
||||
|
||||
new_data = self.group_recipes.update(recipe.slug, update_data)
|
||||
self.check_assets(new_data, recipe.slug)
|
||||
@@ -764,6 +810,7 @@ class RecipeService(RecipeServiceBase):
|
||||
def patch_one(self, slug_or_id: str | UUID, patch_data: RecipeDraft) -> RecipeOut:
|
||||
recipe = self._pre_update_check(slug_or_id, patch_data)
|
||||
|
||||
patch_data = self._validate_reassignment(recipe, patch_data)
|
||||
new_data = self.group_recipes.patch(recipe.slug, patch_data.model_dump(exclude_unset=True))
|
||||
|
||||
self.check_assets(new_data, recipe.slug)
|
||||
|
||||
@@ -527,3 +527,111 @@ def test_forbidden_asset_from_url_downloads_nothing(
|
||||
assert response.status_code == 403
|
||||
assert not downloads
|
||||
assert not any(f.is_file() for f in recipe.asset_dir.rglob("*"))
|
||||
|
||||
|
||||
def test_owner_change_via_patch(api_client: TestClient, user_tuple: list[TestUser]):
|
||||
usr_1, usr_2 = user_tuple
|
||||
recipe = _create_recipe(usr_1, locked=False)
|
||||
|
||||
response = api_client.patch(
|
||||
api_routes.recipes + f"/{recipe.slug}", json={"userId": str(usr_2.user_id)}, headers=usr_1.token
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["userId"] == str(usr_2.user_id)
|
||||
|
||||
updated = usr_1.repos.recipes.get_one(recipe.slug)
|
||||
assert updated is not None
|
||||
assert str(updated.user_id) == str(usr_2.user_id)
|
||||
assert str(updated.household_id) == str(usr_2.household_id)
|
||||
|
||||
|
||||
def test_owner_change_via_put(api_client: TestClient, user_tuple: list[TestUser]):
|
||||
usr_1, usr_2 = user_tuple
|
||||
recipe = _create_recipe(usr_1, locked=False)
|
||||
|
||||
# simulate the editor save: a full recipe round trip with the owner changed
|
||||
response = api_client.get(api_routes.recipes + f"/{recipe.slug}", headers=usr_1.token)
|
||||
assert response.status_code == 200
|
||||
recipe_json = response.json()
|
||||
recipe_json["userId"] = str(usr_2.user_id)
|
||||
|
||||
response = api_client.put(api_routes.recipes + f"/{recipe.slug}", json=recipe_json, headers=usr_1.token)
|
||||
assert response.status_code == 200
|
||||
|
||||
response = api_client.get(api_routes.recipes + f"/{recipe.slug}", headers=usr_2.token)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["userId"] == str(usr_2.user_id)
|
||||
assert response.json()["householdId"] == str(usr_2.household_id)
|
||||
|
||||
|
||||
def test_owner_change_moves_recipe_to_new_owner_household(
|
||||
api_client: TestClient, unique_user: TestUser, h2_user: TestUser
|
||||
):
|
||||
recipe = _create_recipe(unique_user, locked=False)
|
||||
assert str(recipe.household_id) != str(h2_user.household_id)
|
||||
|
||||
response = api_client.patch(
|
||||
api_routes.recipes + f"/{recipe.slug}", json={"userId": str(h2_user.user_id)}, headers=unique_user.token
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
# the recipe moved with the new owner, so the new owner can see it
|
||||
response = api_client.get(api_routes.recipes + f"/{recipe.slug}", headers=h2_user.token)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["userId"] == str(h2_user.user_id)
|
||||
assert response.json()["householdId"] == str(h2_user.household_id)
|
||||
|
||||
|
||||
def test_non_owner_cannot_change_owner(api_client: TestClient, user_tuple: list[TestUser]):
|
||||
usr_1, usr_2 = user_tuple
|
||||
recipe = _create_recipe(usr_1, locked=False)
|
||||
|
||||
response = api_client.patch(
|
||||
api_routes.recipes + f"/{recipe.slug}", json={"userId": str(usr_2.user_id)}, headers=usr_2.token
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
unchanged = usr_1.repos.recipes.get_one(recipe.slug)
|
||||
assert unchanged is not None
|
||||
assert str(unchanged.user_id) == str(usr_1.user_id)
|
||||
assert str(unchanged.household_id) == str(usr_1.household_id)
|
||||
|
||||
|
||||
def test_owner_change_rejects_user_of_other_group(api_client: TestClient, unique_user: TestUser, g2_user: TestUser):
|
||||
recipe = _create_recipe(unique_user, locked=False)
|
||||
|
||||
response = api_client.patch(
|
||||
api_routes.recipes + f"/{recipe.slug}", json={"userId": str(g2_user.user_id)}, headers=unique_user.token
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
unchanged = unique_user.repos.recipes.get_one(recipe.slug)
|
||||
assert unchanged is not None
|
||||
assert str(unchanged.user_id) == str(unique_user.user_id)
|
||||
|
||||
|
||||
def test_admin_can_change_owner(
|
||||
api_client: TestClient, unique_user: TestUser, unique_admin: TestUser, h2_user: TestUser
|
||||
):
|
||||
recipe = _create_recipe(unique_user, locked=False)
|
||||
|
||||
response = api_client.patch(
|
||||
api_routes.recipes + f"/{recipe.slug}", json={"userId": str(h2_user.user_id)}, headers=unique_admin.token
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
updated = h2_user.repos.recipes.get_one(recipe.slug)
|
||||
assert updated is not None
|
||||
assert str(updated.user_id) == str(h2_user.user_id)
|
||||
|
||||
|
||||
def test_patch_with_null_user_id_keeps_owner(api_client: TestClient, user_tuple: list[TestUser]):
|
||||
usr_1, usr_2 = user_tuple
|
||||
recipe = _create_recipe(usr_1, locked=False)
|
||||
|
||||
response = api_client.patch(api_routes.recipes + f"/{recipe.slug}", json={"userId": None}, headers=usr_2.token)
|
||||
assert response.status_code == 200
|
||||
|
||||
unchanged = usr_1.repos.recipes.get_one(recipe.slug)
|
||||
assert unchanged is not None
|
||||
assert str(unchanged.user_id) == str(usr_1.user_id)
|
||||
Reference in new issue
Block a user