Merge remote-tracking branch 'origin/develop' into remote-follow-api
[akkoma] / lib / pleroma / web / activity_pub / object_validators / undo_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.UndoValidator do
6 use Ecto.Schema
7
8 alias Pleroma.Activity
9 alias Pleroma.User
10
11 import Ecto.Changeset
12 import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
13
14 @primary_key false
15
16 embedded_schema do
17 quote do
18 unquote do
19 import Elixir.Pleroma.Web.ActivityPub.ObjectValidators.CommonFields
20 message_fields()
21 activity_fields()
22 end
23 end
24 end
25
26 def cast_and_validate(data) do
27 data
28 |> cast_data()
29 |> validate_data()
30 end
31
32 def cast_data(data) do
33 %__MODULE__{}
34 |> changeset(data)
35 end
36
37 def changeset(struct, data) do
38 struct
39 |> cast(data, __schema__(:fields))
40 end
41
42 defp validate_data(data_cng) do
43 data_cng
44 |> validate_inclusion(:type, ["Undo"])
45 |> validate_required([:id, :type, :object, :actor, :to, :cc])
46 |> validate_undo_actor(:actor)
47 |> validate_object_presence()
48 |> validate_undo_rights()
49 end
50
51 def validate_undo_rights(cng) do
52 actor = get_field(cng, :actor)
53 object = get_field(cng, :object)
54
55 with %Activity{data: %{"actor" => object_actor}} <- Activity.get_by_ap_id(object),
56 true <- object_actor != actor do
57 cng
58 |> add_error(:actor, "not the same as object actor")
59 else
60 _ -> cng
61 end
62 end
63
64 defp validate_undo_actor(cng, field_name) do
65 validate_change(cng, field_name, fn field_name, actor ->
66 case User.get_cached_by_ap_id(actor) do
67 %User{} -> []
68 _ -> [{field_name, "can't find user"}]
69 end
70 end)
71 end
72 end