diff --git a/changelog.d/oauth-app.fix b/changelog.d/oauth-app.fix new file mode 100644 index 000000000..eb917462f --- /dev/null +++ b/changelog.d/oauth-app.fix @@ -0,0 +1 @@ +Prevent OAuth App flow from creating duplicate entries diff --git a/lib/pleroma/web/mastodon_api/controllers/app_controller.ex b/lib/pleroma/web/mastodon_api/controllers/app_controller.ex index 844673ae0..e5e8ea8f5 100644 --- a/lib/pleroma/web/mastodon_api/controllers/app_controller.ex +++ b/lib/pleroma/web/mastodon_api/controllers/app_controller.ex @@ -33,11 +33,9 @@ defmodule Pleroma.Web.MastodonAPI.AppController do app_attrs = params |> Map.take([:client_name, :redirect_uris, :website]) - |> Map.put(:scopes, scopes) |> Maps.put_if_present(:user_id, user_id) - with cs <- App.register_changeset(%App{}, app_attrs), - {:ok, app} <- Repo.insert(cs) do + with {:ok, app} <- App.get_or_make(app_attrs, scopes) do render(conn, "show.json", app: app) end end diff --git a/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs index bc9d4048c..1e2e68791 100644 --- a/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs @@ -89,4 +89,51 @@ defmodule Pleroma.Web.MastodonAPI.AppControllerTest do assert expected == json_response_and_validate_schema(conn, 200) assert app.user_id == user.id end + + test "creates an oauth app without a user", %{conn: conn} do + app_attrs = build(:oauth_app) + + conn = + conn + |> put_req_header("content-type", "application/json") + |> post("/api/v1/apps", %{ + client_name: app_attrs.client_name, + redirect_uris: app_attrs.redirect_uris + }) + + [app] = Repo.all(App) + + expected = %{ + "name" => app.client_name, + "website" => app.website, + "client_id" => app.client_id, + "client_secret" => app.client_secret, + "id" => app.id |> to_string(), + "redirect_uri" => app.redirect_uris, + "vapid_key" => Push.vapid_config() |> Keyword.get(:public_key) + } + + assert expected == json_response_and_validate_schema(conn, 200) + end + + test "does not duplicate apps with the same client name", %{conn: conn} do + client_name = "BleromaSE" + redirect_uris = "https://bleroma.app/oauth-callback" + + for _i <- 1..3 do + conn + |> put_req_header("content-type", "application/json") + |> post("/api/v1/apps", %{ + client_name: client_name, + redirect_uris: redirect_uris + }) + |> json_response_and_validate_schema(200) + end + + apps = Repo.all(App) + + assert length(apps) == 1 + assert List.first(apps).client_name == client_name + assert List.first(apps).redirect_uris == redirect_uris + end end