object_validators: Group common fields in CommonValidations
[akkoma] / lib / pleroma / web / activity_pub / object_validators / update_validator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.ObjectValidators.UpdateValidator do
6 use Ecto.Schema
7
8 alias Pleroma.EctoType.ActivityPub.ObjectValidators
9
10 import Ecto.Changeset
11 import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
12
13 @primary_key false
14
15 embedded_schema do
16 quote do
17 unquote do
18 import Elixir.Pleroma.Web.ActivityPub.ObjectValidators.CommonFields
19 message_fields()
20 end
21 end
22
23 field(:actor, ObjectValidators.ObjectID)
24 # In this case, we save the full object in this activity instead of just a
25 # reference, so we can always see what was actually changed by this.
26 field(:object, :map)
27 end
28
29 def cast_data(data) do
30 %__MODULE__{}
31 |> cast(data, __schema__(:fields))
32 end
33
34 defp validate_data(cng) do
35 cng
36 |> validate_required([:id, :type, :actor, :to, :cc, :object])
37 |> validate_inclusion(:type, ["Update"])
38 |> validate_actor_presence()
39 |> validate_updating_rights()
40 end
41
42 def cast_and_validate(data) do
43 data
44 |> cast_data
45 |> validate_data
46 end
47
48 # For now we only support updating users, and here the rule is easy:
49 # object id == actor id
50 def validate_updating_rights(cng) do
51 with actor = get_field(cng, :actor),
52 object = get_field(cng, :object),
53 {:ok, object_id} <- ObjectValidators.ObjectID.cast(object),
54 true <- actor == object_id do
55 cng
56 else
57 _e ->
58 cng
59 |> add_error(:object, "Can't be updated by this actor")
60 end
61 end
62 end