Merge branch 'develop' into global-status-expiration
[akkoma] / lib / pleroma / web / mastodon_api / controllers / account_controller.ex
index be863d8ed3031b4262e0f401cb178ab42a8c88d0..21bc3d5a549d5fde33a633c00f1147df3968deb4 100644 (file)
@@ -1,5 +1,5 @@
 # Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
 # SPDX-License-Identifier: AGPL-3.0-only
 
 defmodule Pleroma.Web.MastodonAPI.AccountController do
@@ -8,6 +8,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
   import Pleroma.Web.ControllerHelper,
     only: [add_link_headers: 2, truthy_param?: 1, assign_account_by_id: 2, json_response: 3]
 
+  alias Pleroma.Plugs.OAuthScopesPlug
   alias Pleroma.Plugs.RateLimiter
   alias Pleroma.User
   alias Pleroma.Web.ActivityPub.ActivityPub
@@ -18,12 +19,59 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
   alias Pleroma.Web.OAuth.Token
   alias Pleroma.Web.TwitterAPI.TwitterAPI
 
-  @relations [:follow, :unfollow]
+  plug(
+    OAuthScopesPlug,
+    %{fallback: :proceed_unauthenticated, scopes: ["read:accounts"]}
+    when action == :show
+  )
+
+  plug(
+    OAuthScopesPlug,
+    %{scopes: ["read:accounts"]}
+    when action in [:endorsements, :verify_credentials, :followers, :following]
+  )
+
+  plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action == :update_credentials)
+
+  plug(OAuthScopesPlug, %{scopes: ["read:lists"]} when action == :lists)
+
+  plug(
+    OAuthScopesPlug,
+    %{scopes: ["follow", "read:blocks"]} when action == :blocks
+  )
+
+  plug(
+    OAuthScopesPlug,
+    %{scopes: ["follow", "write:blocks"]} when action in [:block, :unblock]
+  )
+
+  plug(OAuthScopesPlug, %{scopes: ["read:follows"]} when action == :relationships)
+
+  # Note: :follows (POST /api/v1/follows) is the same as :follow, consider removing :follows
+  plug(
+    OAuthScopesPlug,
+    %{scopes: ["follow", "write:follows"]} when action in [:follows, :follow, :unfollow]
+  )
+
+  plug(OAuthScopesPlug, %{scopes: ["follow", "read:mutes"]} when action == :mutes)
+
+  plug(OAuthScopesPlug, %{scopes: ["follow", "write:mutes"]} when action in [:mute, :unmute])
+
+  plug(
+    Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
+    when action not in [:create, :show, :statuses]
+  )
+
+  @relationship_actions [:follow, :unfollow]
   @needs_account ~W(followers following lists follow unfollow mute unmute block unblock)a
 
-  plug(RateLimiter, {:relations_id_action, params: ["id", "uri"]} when action in @relations)
-  plug(RateLimiter, :relations_actions when action in @relations)
-  plug(RateLimiter, :app_account_creation when action == :create)
+  plug(
+    RateLimiter,
+    [name: :relation_id_action, params: ["id", "uri"]] when action in @relationship_actions
+  )
+
+  plug(RateLimiter, [name: :relations_actions] when action in @relationship_actions)
+  plug(RateLimiter, [name: :app_account_creation] when action == :create)
   plug(:assign_account_by_id when action in @needs_account)
 
   action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
@@ -31,7 +79,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
   @doc "POST /api/v1/accounts"
   def create(
         %{assigns: %{app: app}} = conn,
-        %{"username" => nickname, "email" => _, "password" => _, "agreement" => true} = params
+        %{"username" => nickname, "password" => _, "agreement" => true} = params
       ) do
     params =
       params
@@ -48,7 +96,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
       |> Map.put("bio", params["bio"] || "")
       |> Map.put("confirm", params["password"])
 
-    with {:ok, user} <- TwitterAPI.register_user(params, need_confirmation: true),
+    with :ok <- validate_email_param(params),
+         {:ok, user} <- TwitterAPI.register_user(params, need_confirmation: true),
          {:ok, token} <- Token.create_token(app, user, %{scopes: app.scopes}) do
       json(conn, %{
         token_type: "Bearer",
@@ -69,6 +118,15 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
     render_error(conn, :forbidden, "Invalid credentials")
   end
 
+  defp validate_email_param(%{"email" => _}), do: :ok
+
+  defp validate_email_param(_) do
+    case Pleroma.Config.get([:instance, :account_activation_required]) do
+      true -> {:error, %{"error" => "Missing parameters"}}
+      _ -> :ok
+    end
+  end
+
   @doc "GET /api/v1/accounts/verify_credentials"
   def verify_credentials(%{assigns: %{user: user}} = conn, _) do
     chat_token = Phoenix.Token.sign(conn, "user socket", user.id)
@@ -81,6 +139,70 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
     )
   end
 
+  @doc "PATCH /api/v1/accounts/update_credentials"
+  def update_credentials(%{assigns: %{user: original_user}} = conn, params) do
+    user = original_user
+
+    user_params =
+      [
+        :no_rich_text,
+        :locked,
+        :hide_followers_count,
+        :hide_follows_count,
+        :hide_followers,
+        :hide_follows,
+        :hide_favorites,
+        :show_role,
+        :skip_thread_containment,
+        :allow_following_move,
+        :discoverable
+      ]
+      |> Enum.reduce(%{}, fn key, acc ->
+        add_if_present(acc, params, to_string(key), key, &{:ok, truthy_param?(&1)})
+      end)
+      |> add_if_present(params, "display_name", :name)
+      |> add_if_present(params, "note", :bio)
+      |> add_if_present(params, "avatar", :avatar)
+      |> add_if_present(params, "header", :banner)
+      |> add_if_present(params, "pleroma_background_image", :background)
+      |> add_if_present(
+        params,
+        "fields_attributes",
+        :raw_fields,
+        &{:ok, normalize_fields_attributes(&1)}
+      )
+      |> add_if_present(params, "pleroma_settings_store", :pleroma_settings_store)
+      |> add_if_present(params, "default_scope", :default_scope)
+      |> add_if_present(params, "actor_type", :actor_type)
+
+    changeset = User.update_changeset(user, user_params)
+
+    with {:ok, user} <- User.update_and_set_cache(changeset) do
+      if original_user != user, do: CommonAPI.update(user)
+
+      render(conn, "show.json", user: user, for: user, with_pleroma_settings: true)
+    else
+      _e -> render_error(conn, :forbidden, "Invalid request")
+    end
+  end
+
+  defp add_if_present(map, params, params_field, map_field, value_function \\ &{:ok, &1}) do
+    with true <- Map.has_key?(params, params_field),
+         {:ok, new_value} <- value_function.(params[params_field]) do
+      Map.put(map, map_field, new_value)
+    else
+      _ -> map
+    end
+  end
+
+  defp normalize_fields_attributes(fields) do
+    if Enum.all?(fields, &is_tuple/1) do
+      Enum.map(fields, fn {_, v} -> v end)
+    else
+      fields
+    end
+  end
+
   @doc "GET /api/v1/accounts/relationships"
   def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
     targets = User.get_all_by_ids(List.wrap(id))
@@ -94,7 +216,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
   @doc "GET /api/v1/accounts/:id"
   def show(%{assigns: %{user: for_user}} = conn, %{"id" => nickname_or_id}) do
     with %User{} = user <- User.get_cached_by_nickname_or_id(nickname_or_id, for: for_user),
-         true <- User.auth_active?(user) || user.id == for_user.id || User.superuser?(for_user) do
+         true <- User.visible_for?(user, for_user) do
       render(conn, "show.json", user: user, for: for_user)
     else
       _e -> render_error(conn, :not_found, "Can't find user")
@@ -103,14 +225,21 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
 
   @doc "GET /api/v1/accounts/:id/statuses"
   def statuses(%{assigns: %{user: reading_user}} = conn, params) do
-    with %User{} = user <- User.get_cached_by_nickname_or_id(params["id"], for: reading_user) do
-      params = Map.put(params, "tag", params["tagged"])
+    with %User{} = user <- User.get_cached_by_nickname_or_id(params["id"], for: reading_user),
+         true <- User.visible_for?(user, reading_user) do
+      params =
+        params
+        |> Map.put("tag", params["tagged"])
+        |> Map.delete("godmode")
+
       activities = ActivityPub.fetch_user_activities(user, reading_user, params)
 
       conn
       |> add_link_headers(activities)
       |> put_view(StatusView)
       |> render("index.json", activities: activities, for: reading_user, as: :activity)
+    else
+      _e -> render_error(conn, :not_found, "Can't find user")
     end
   end
 
@@ -119,7 +248,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
     followers =
       cond do
         for_user && user.id == for_user.id -> MastodonAPI.get_followers(user, params)
-        user.info.hide_followers -> []
+        user.hide_followers -> []
         true -> MastodonAPI.get_followers(user, params)
       end
 
@@ -133,7 +262,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
     followers =
       cond do
         for_user && user.id == for_user.id -> MastodonAPI.get_friends(user, params)
-        user.info.hide_follows -> []
+        user.hide_follows -> []
         true -> MastodonAPI.get_friends(user, params)
       end
 
@@ -179,7 +308,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
   def mute(%{assigns: %{user: muter, account: muted}} = conn, params) do
     notifications? = params |> Map.get("notifications", true) |> truthy_param?()
 
-    with {:ok, muter} <- User.mute(muter, muted, notifications?) do
+    with {:ok, _user_relationships} <- User.mute(muter, muted, notifications?) do
       render(conn, "relationship.json", user: muter, target: muted)
     else
       {:error, message} -> json_response(conn, :forbidden, %{error: message})
@@ -188,7 +317,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
 
   @doc "POST /api/v1/accounts/:id/unmute"
   def unmute(%{assigns: %{user: muter, account: muted}} = conn, _params) do
-    with {:ok, muter} <- User.unmute(muter, muted) do
+    with {:ok, _user_relationships} <- User.unmute(muter, muted) do
       render(conn, "relationship.json", user: muter, target: muted)
     else
       {:error, message} -> json_response(conn, :forbidden, %{error: message})
@@ -197,7 +326,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
 
   @doc "POST /api/v1/accounts/:id/block"
   def block(%{assigns: %{user: blocker, account: blocked}} = conn, _params) do
-    with {:ok, blocker} <- User.block(blocker, blocked),
+    with {:ok, _user_block} <- User.block(blocker, blocked),
          {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
       render(conn, "relationship.json", user: blocker, target: blocked)
     else
@@ -207,11 +336,39 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
 
   @doc "POST /api/v1/accounts/:id/unblock"
   def unblock(%{assigns: %{user: blocker, account: blocked}} = conn, _params) do
-    with {:ok, blocker} <- User.unblock(blocker, blocked),
+    with {:ok, _user_block} <- User.unblock(blocker, blocked),
          {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
       render(conn, "relationship.json", user: blocker, target: blocked)
     else
       {:error, message} -> json_response(conn, :forbidden, %{error: message})
     end
   end
+
+  @doc "POST /api/v1/follows"
+  def follows(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
+    with {_, %User{} = followed} <- {:followed, User.get_cached_by_nickname(uri)},
+         {_, true} <- {:followed, follower.id != followed.id},
+         {:ok, follower, followed, _} <- CommonAPI.follow(follower, followed) do
+      render(conn, "show.json", user: followed, for: follower)
+    else
+      {:followed, _} -> {:error, :not_found}
+      {:error, message} -> json_response(conn, :forbidden, %{error: message})
+    end
+  end
+
+  @doc "GET /api/v1/mutes"
+  def mutes(%{assigns: %{user: user}} = conn, _) do
+    users = User.muted_users(user, _restrict_deactivated = true)
+    render(conn, "index.json", users: users, for: user, as: :user)
+  end
+
+  @doc "GET /api/v1/blocks"
+  def blocks(%{assigns: %{user: user}} = conn, _) do
+    users = User.blocked_users(user, _restrict_deactivated = true)
+    render(conn, "index.json", users: users, for: user, as: :user)
+  end
+
+  @doc "GET /api/v1/endorsements"
+  def endorsements(conn, params),
+    do: Pleroma.Web.MastodonAPI.MastodonAPIController.empty_array(conn, params)
 end