Clean up account aliases
[akkoma] / lib / pleroma / web / mastodon_api / controllers / account_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.AccountController do
6 use Pleroma.Web, :controller
7
8 import Pleroma.Web.ControllerHelper,
9 only: [
10 add_link_headers: 2,
11 truthy_param?: 1,
12 assign_account_by_id: 2,
13 embed_relationships?: 1,
14 json_response: 3
15 ]
16
17 alias Pleroma.Maps
18 alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
19 alias Pleroma.Plugs.OAuthScopesPlug
20 alias Pleroma.Plugs.RateLimiter
21 alias Pleroma.User
22 alias Pleroma.Web.ActivityPub.ActivityPub
23 alias Pleroma.Web.ActivityPub.Builder
24 alias Pleroma.Web.ActivityPub.Pipeline
25 alias Pleroma.Web.CommonAPI
26 alias Pleroma.Web.MastodonAPI.ListView
27 alias Pleroma.Web.MastodonAPI.MastodonAPI
28 alias Pleroma.Web.MastodonAPI.MastodonAPIController
29 alias Pleroma.Web.MastodonAPI.StatusView
30 alias Pleroma.Web.OAuth.OAuthController
31 alias Pleroma.Web.OAuth.OAuthView
32 alias Pleroma.Web.TwitterAPI.TwitterAPI
33
34 plug(Pleroma.Web.ApiSpec.CastAndValidate)
35
36 plug(:skip_plug, [OAuthScopesPlug, EnsurePublicOrAuthenticatedPlug] when action == :create)
37
38 plug(:skip_plug, EnsurePublicOrAuthenticatedPlug when action in [:show, :statuses])
39
40 plug(
41 OAuthScopesPlug,
42 %{fallback: :proceed_unauthenticated, scopes: ["read:accounts"]}
43 when action in [:show, :followers, :following]
44 )
45
46 plug(
47 OAuthScopesPlug,
48 %{fallback: :proceed_unauthenticated, scopes: ["read:statuses"]}
49 when action == :statuses
50 )
51
52 plug(
53 OAuthScopesPlug,
54 %{scopes: ["read:accounts"]}
55 when action in [:verify_credentials, :endorsements, :identity_proofs]
56 )
57
58 plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action == :update_credentials)
59
60 plug(OAuthScopesPlug, %{scopes: ["read:lists"]} when action == :lists)
61
62 plug(
63 OAuthScopesPlug,
64 %{scopes: ["follow", "read:blocks"]} when action == :blocks
65 )
66
67 plug(
68 OAuthScopesPlug,
69 %{scopes: ["follow", "write:blocks"]} when action in [:block, :unblock]
70 )
71
72 plug(OAuthScopesPlug, %{scopes: ["read:follows"]} when action == :relationships)
73
74 plug(
75 OAuthScopesPlug,
76 %{scopes: ["follow", "write:follows"]} when action in [:follow_by_uri, :follow, :unfollow]
77 )
78
79 plug(OAuthScopesPlug, %{scopes: ["follow", "read:mutes"]} when action == :mutes)
80
81 plug(OAuthScopesPlug, %{scopes: ["follow", "write:mutes"]} when action in [:mute, :unmute])
82
83 @relationship_actions [:follow, :unfollow]
84 @needs_account ~W(followers following lists follow unfollow mute unmute block unblock)a
85
86 plug(
87 RateLimiter,
88 [name: :relation_id_action, params: [:id, :uri]] when action in @relationship_actions
89 )
90
91 plug(RateLimiter, [name: :relations_actions] when action in @relationship_actions)
92 plug(RateLimiter, [name: :app_account_creation] when action == :create)
93 plug(:assign_account_by_id when action in @needs_account)
94
95 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
96
97 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.AccountOperation
98
99 @doc "POST /api/v1/accounts"
100 def create(%{assigns: %{app: app}, body_params: params} = conn, _params) do
101 with :ok <- validate_email_param(params),
102 :ok <- TwitterAPI.validate_captcha(app, params),
103 {:ok, user} <- TwitterAPI.register_user(params),
104 {_, {:ok, token}} <-
105 {:login, OAuthController.login(user, app, app.scopes)} do
106 json(conn, OAuthView.render("token.json", %{user: user, token: token}))
107 else
108 {:login, {:account_status, :confirmation_pending}} ->
109 json_response(conn, :ok, %{
110 message: "You have been registered. Please check your email for further instructions.",
111 identifier: "missing_confirmed_email"
112 })
113
114 {:login, {:account_status, :approval_pending}} ->
115 json_response(conn, :ok, %{
116 message:
117 "You have been registered. You'll be able to log in once your account is approved.",
118 identifier: "awaiting_approval"
119 })
120
121 {:login, _} ->
122 json_response(conn, :ok, %{
123 message:
124 "You have been registered. Some post-registration steps may be pending. " <>
125 "Please log in manually.",
126 identifier: "manual_login_required"
127 })
128
129 {:error, error} ->
130 json_response(conn, :bad_request, %{error: error})
131 end
132 end
133
134 def create(%{assigns: %{app: _app}} = conn, _) do
135 render_error(conn, :bad_request, "Missing parameters")
136 end
137
138 def create(conn, _) do
139 render_error(conn, :forbidden, "Invalid credentials")
140 end
141
142 defp validate_email_param(%{email: email}) when not is_nil(email), do: :ok
143
144 defp validate_email_param(_) do
145 case Pleroma.Config.get([:instance, :account_activation_required]) do
146 true -> {:error, dgettext("errors", "Missing parameter: %{name}", name: "email")}
147 _ -> :ok
148 end
149 end
150
151 @doc "GET /api/v1/accounts/verify_credentials"
152 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
153 chat_token = Phoenix.Token.sign(conn, "user socket", user.id)
154
155 render(conn, "show.json",
156 user: user,
157 for: user,
158 with_pleroma_settings: true,
159 with_chat_token: chat_token
160 )
161 end
162
163 @doc "PATCH /api/v1/accounts/update_credentials"
164 def update_credentials(%{assigns: %{user: user}, body_params: params} = conn, _params) do
165 params =
166 params
167 |> Enum.filter(fn {_, value} -> not is_nil(value) end)
168 |> Enum.into(%{})
169
170 # We use an empty string as a special value to reset
171 # avatars, banners, backgrounds
172 user_image_value = fn
173 "" -> {:ok, nil}
174 value -> {:ok, value}
175 end
176
177 user_params =
178 [
179 :no_rich_text,
180 :locked,
181 :hide_followers_count,
182 :hide_follows_count,
183 :hide_followers,
184 :hide_follows,
185 :hide_favorites,
186 :show_role,
187 :skip_thread_containment,
188 :allow_following_move,
189 :also_known_as,
190 :discoverable,
191 :accepts_chat_messages
192 ]
193 |> Enum.reduce(%{}, fn key, acc ->
194 Maps.put_if_present(acc, key, params[key], &{:ok, truthy_param?(&1)})
195 end)
196 |> Maps.put_if_present(:name, params[:display_name])
197 |> Maps.put_if_present(:bio, params[:note])
198 |> Maps.put_if_present(:raw_bio, params[:note])
199 |> Maps.put_if_present(:avatar, params[:avatar], user_image_value)
200 |> Maps.put_if_present(:banner, params[:header], user_image_value)
201 |> Maps.put_if_present(:background, params[:pleroma_background_image], user_image_value)
202 |> Maps.put_if_present(
203 :raw_fields,
204 params[:fields_attributes],
205 &{:ok, normalize_fields_attributes(&1)}
206 )
207 |> Maps.put_if_present(:pleroma_settings_store, params[:pleroma_settings_store])
208 |> Maps.put_if_present(:default_scope, params[:default_scope])
209 |> Maps.put_if_present(:default_scope, params["source"]["privacy"])
210 |> Maps.put_if_present(:actor_type, params[:bot], fn bot ->
211 if bot, do: {:ok, "Service"}, else: {:ok, "Person"}
212 end)
213 |> Maps.put_if_present(:actor_type, params[:actor_type])
214 |> Maps.put_if_present(:also_known_as, params[:also_known_as])
215
216 # What happens here:
217 #
218 # We want to update the user through the pipeline, but the ActivityPub
219 # update information is not quite enough for this, because this also
220 # contains local settings that don't federate and don't even appear
221 # in the Update activity.
222 #
223 # So we first build the normal local changeset, then apply it to the
224 # user data, but don't persist it. With this, we generate the object
225 # data for our update activity. We feed this and the changeset as meta
226 # inforation into the pipeline, where they will be properly updated and
227 # federated.
228 with changeset <- User.update_changeset(user, user_params),
229 {:ok, unpersisted_user} <- Ecto.Changeset.apply_action(changeset, :update),
230 updated_object <-
231 Pleroma.Web.ActivityPub.UserView.render("user.json", user: user)
232 |> Map.delete("@context"),
233 {:ok, update_data, []} <- Builder.update(user, updated_object),
234 {:ok, _update, _} <-
235 Pipeline.common_pipeline(update_data,
236 local: true,
237 user_update_changeset: changeset
238 ) do
239 render(conn, "show.json",
240 user: unpersisted_user,
241 for: unpersisted_user,
242 with_pleroma_settings: true
243 )
244 else
245 _e -> render_error(conn, :forbidden, "Invalid request")
246 end
247 end
248
249 defp normalize_fields_attributes(fields) do
250 if Enum.all?(fields, &is_tuple/1) do
251 Enum.map(fields, fn {_, v} -> v end)
252 else
253 Enum.map(fields, fn
254 %{} = field -> %{"name" => field.name, "value" => field.value}
255 field -> field
256 end)
257 end
258 end
259
260 @doc "GET /api/v1/accounts/relationships"
261 def relationships(%{assigns: %{user: user}} = conn, %{id: id}) do
262 targets = User.get_all_by_ids(List.wrap(id))
263
264 render(conn, "relationships.json", user: user, targets: targets)
265 end
266
267 # Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array.
268 def relationships(%{assigns: %{user: _user}} = conn, _), do: json(conn, [])
269
270 @doc "GET /api/v1/accounts/:id"
271 def show(%{assigns: %{user: for_user}} = conn, %{id: nickname_or_id}) do
272 with %User{} = user <- User.get_cached_by_nickname_or_id(nickname_or_id, for: for_user),
273 :visible <- User.visible_for(user, for_user) do
274 render(conn, "show.json", user: user, for: for_user)
275 else
276 error -> user_visibility_error(conn, error)
277 end
278 end
279
280 @doc "GET /api/v1/accounts/:id/statuses"
281 def statuses(%{assigns: %{user: reading_user}} = conn, params) do
282 with %User{} = user <- User.get_cached_by_nickname_or_id(params.id, for: reading_user),
283 :visible <- User.visible_for(user, reading_user) do
284 params =
285 params
286 |> Map.delete(:tagged)
287 |> Map.put(:tag, params[:tagged])
288
289 activities = ActivityPub.fetch_user_activities(user, reading_user, params)
290
291 conn
292 |> add_link_headers(activities)
293 |> put_view(StatusView)
294 |> render("index.json",
295 activities: activities,
296 for: reading_user,
297 as: :activity
298 )
299 else
300 error -> user_visibility_error(conn, error)
301 end
302 end
303
304 defp user_visibility_error(conn, error) do
305 case error do
306 :restrict_unauthenticated ->
307 render_error(conn, :unauthorized, "This API requires an authenticated user")
308
309 _ ->
310 render_error(conn, :not_found, "Can't find user")
311 end
312 end
313
314 @doc "GET /api/v1/accounts/:id/followers"
315 def followers(%{assigns: %{user: for_user, account: user}} = conn, params) do
316 params =
317 params
318 |> Enum.map(fn {key, value} -> {to_string(key), value} end)
319 |> Enum.into(%{})
320
321 followers =
322 cond do
323 for_user && user.id == for_user.id -> MastodonAPI.get_followers(user, params)
324 user.hide_followers -> []
325 true -> MastodonAPI.get_followers(user, params)
326 end
327
328 conn
329 |> add_link_headers(followers)
330 # https://git.pleroma.social/pleroma/pleroma-fe/-/issues/838#note_59223
331 |> render("index.json",
332 for: for_user,
333 users: followers,
334 as: :user,
335 embed_relationships: embed_relationships?(params)
336 )
337 end
338
339 @doc "GET /api/v1/accounts/:id/following"
340 def following(%{assigns: %{user: for_user, account: user}} = conn, params) do
341 params =
342 params
343 |> Enum.map(fn {key, value} -> {to_string(key), value} end)
344 |> Enum.into(%{})
345
346 followers =
347 cond do
348 for_user && user.id == for_user.id -> MastodonAPI.get_friends(user, params)
349 user.hide_follows -> []
350 true -> MastodonAPI.get_friends(user, params)
351 end
352
353 conn
354 |> add_link_headers(followers)
355 # https://git.pleroma.social/pleroma/pleroma-fe/-/issues/838#note_59223
356 |> render("index.json",
357 for: for_user,
358 users: followers,
359 as: :user,
360 embed_relationships: embed_relationships?(params)
361 )
362 end
363
364 @doc "GET /api/v1/accounts/:id/lists"
365 def lists(%{assigns: %{user: user, account: account}} = conn, _params) do
366 lists = Pleroma.List.get_lists_account_belongs(user, account)
367
368 conn
369 |> put_view(ListView)
370 |> render("index.json", lists: lists)
371 end
372
373 @doc "POST /api/v1/accounts/:id/follow"
374 def follow(%{assigns: %{user: %{id: id}, account: %{id: id}}}, _params) do
375 {:error, "Can not follow yourself"}
376 end
377
378 def follow(%{body_params: params, assigns: %{user: follower, account: followed}} = conn, _) do
379 with {:ok, follower} <- MastodonAPI.follow(follower, followed, params) do
380 render(conn, "relationship.json", user: follower, target: followed)
381 else
382 {:error, message} -> json_response(conn, :forbidden, %{error: message})
383 end
384 end
385
386 @doc "POST /api/v1/accounts/:id/unfollow"
387 def unfollow(%{assigns: %{user: %{id: id}, account: %{id: id}}}, _params) do
388 {:error, "Can not unfollow yourself"}
389 end
390
391 def unfollow(%{assigns: %{user: follower, account: followed}} = conn, _params) do
392 with {:ok, follower} <- CommonAPI.unfollow(follower, followed) do
393 render(conn, "relationship.json", user: follower, target: followed)
394 end
395 end
396
397 @doc "POST /api/v1/accounts/:id/mute"
398 def mute(%{assigns: %{user: muter, account: muted}, body_params: params} = conn, _params) do
399 with {:ok, _user_relationships} <- User.mute(muter, muted, params.notifications) do
400 render(conn, "relationship.json", user: muter, target: muted)
401 else
402 {:error, message} -> json_response(conn, :forbidden, %{error: message})
403 end
404 end
405
406 @doc "POST /api/v1/accounts/:id/unmute"
407 def unmute(%{assigns: %{user: muter, account: muted}} = conn, _params) do
408 with {:ok, _user_relationships} <- User.unmute(muter, muted) do
409 render(conn, "relationship.json", user: muter, target: muted)
410 else
411 {:error, message} -> json_response(conn, :forbidden, %{error: message})
412 end
413 end
414
415 @doc "POST /api/v1/accounts/:id/block"
416 def block(%{assigns: %{user: blocker, account: blocked}} = conn, _params) do
417 with {:ok, _activity} <- CommonAPI.block(blocker, blocked) do
418 render(conn, "relationship.json", user: blocker, target: blocked)
419 else
420 {:error, message} -> json_response(conn, :forbidden, %{error: message})
421 end
422 end
423
424 @doc "POST /api/v1/accounts/:id/unblock"
425 def unblock(%{assigns: %{user: blocker, account: blocked}} = conn, _params) do
426 with {:ok, _activity} <- CommonAPI.unblock(blocker, blocked) do
427 render(conn, "relationship.json", user: blocker, target: blocked)
428 else
429 {:error, message} -> json_response(conn, :forbidden, %{error: message})
430 end
431 end
432
433 @doc "POST /api/v1/follows"
434 def follow_by_uri(%{body_params: %{uri: uri}} = conn, _) do
435 case User.get_cached_by_nickname(uri) do
436 %User{} = user ->
437 conn
438 |> assign(:account, user)
439 |> follow(%{})
440
441 nil ->
442 {:error, :not_found}
443 end
444 end
445
446 @doc "GET /api/v1/mutes"
447 def mutes(%{assigns: %{user: user}} = conn, _) do
448 users = User.muted_users(user, _restrict_deactivated = true)
449 render(conn, "index.json", users: users, for: user, as: :user)
450 end
451
452 @doc "GET /api/v1/blocks"
453 def blocks(%{assigns: %{user: user}} = conn, _) do
454 users = User.blocked_users(user, _restrict_deactivated = true)
455 render(conn, "index.json", users: users, for: user, as: :user)
456 end
457
458 @doc "GET /api/v1/endorsements"
459 def endorsements(conn, params), do: MastodonAPIController.empty_array(conn, params)
460
461 @doc "GET /api/v1/identity_proofs"
462 def identity_proofs(conn, params), do: MastodonAPIController.empty_array(conn, params)
463 end