Merge branch 'release/2.0.0' into 'stable'
[akkoma] / lib / pleroma / web / oauth / app.ex
index bccc2ac967f48c4394c9f3bc47e9bc48daafc8f2..01ed326f4b7a8ca2a902b824b813a3670fb2118c 100644 (file)
@@ -1,12 +1,14 @@
 # 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.OAuth.App do
   use Ecto.Schema
   import Ecto.Changeset
+  alias Pleroma.Repo
 
   @type t :: %__MODULE__{}
+
   schema "apps" do
     field(:client_name, :string)
     field(:redirect_uris, :string)
@@ -38,4 +40,29 @@ defmodule Pleroma.Web.OAuth.App do
       changeset
     end
   end
+
+  @doc """
+  Gets app by attrs or create new  with attrs.
+  And updates the scopes if need.
+  """
+  @spec get_or_make(map(), list(String.t())) :: {:ok, App.t()} | {:error, Ecto.Changeset.t()}
+  def get_or_make(attrs, scopes) do
+    with %__MODULE__{} = app <- Repo.get_by(__MODULE__, attrs) do
+      update_scopes(app, scopes)
+    else
+      _e ->
+        %__MODULE__{}
+        |> register_changeset(Map.put(attrs, :scopes, scopes))
+        |> Repo.insert()
+    end
+  end
+
+  defp update_scopes(%__MODULE__{} = app, []), do: {:ok, app}
+  defp update_scopes(%__MODULE__{scopes: scopes} = app, scopes), do: {:ok, app}
+
+  defp update_scopes(%__MODULE__{} = app, scopes) do
+    app
+    |> change(%{scopes: scopes})
+    |> Repo.update()
+  end
 end