2018-12-23 13:04:54 -07:00
|
|
|
# Pleroma: A lightweight social networking server
|
2018-12-31 08:41:47 -07:00
|
|
|
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
2018-12-23 13:04:54 -07:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2017-09-07 00:58:10 -06:00
|
|
|
defmodule Pleroma.Web.OAuth.App do
|
2017-09-06 11:06:25 -06:00
|
|
|
use Ecto.Schema
|
2019-02-09 08:20:18 -07:00
|
|
|
import Ecto.Changeset
|
2019-09-06 12:50:00 -06:00
|
|
|
alias Pleroma.Repo
|
2017-09-06 11:06:25 -06:00
|
|
|
|
2019-05-06 11:51:03 -06:00
|
|
|
@type t :: %__MODULE__{}
|
2019-05-13 12:35:45 -06:00
|
|
|
|
2017-09-06 11:06:25 -06:00
|
|
|
schema "apps" do
|
2018-03-30 07:01:53 -06:00
|
|
|
field(:client_name, :string)
|
|
|
|
field(:redirect_uris, :string)
|
2019-02-13 14:29:29 -07:00
|
|
|
field(:scopes, {:array, :string}, default: [])
|
2018-03-30 07:01:53 -06:00
|
|
|
field(:website, :string)
|
|
|
|
field(:client_id, :string)
|
|
|
|
field(:client_secret, :string)
|
2017-09-06 11:06:25 -06:00
|
|
|
|
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
|
|
|
def register_changeset(struct, params \\ %{}) do
|
2018-03-30 07:01:53 -06:00
|
|
|
changeset =
|
|
|
|
struct
|
|
|
|
|> cast(params, [:client_name, :redirect_uris, :scopes, :website])
|
|
|
|
|> validate_required([:client_name, :redirect_uris, :scopes])
|
2017-09-06 11:06:25 -06:00
|
|
|
|
|
|
|
if changeset.valid? do
|
|
|
|
changeset
|
2019-02-13 18:05:25 -07:00
|
|
|
|> put_change(
|
|
|
|
:client_id,
|
|
|
|
:crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
|
|
|
|
)
|
|
|
|
|> put_change(
|
|
|
|
:client_secret,
|
|
|
|
:crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
|
|
|
|
)
|
2017-09-06 11:06:25 -06:00
|
|
|
else
|
|
|
|
changeset
|
|
|
|
end
|
|
|
|
end
|
2019-09-06 12:50:00 -06:00
|
|
|
|
|
|
|
@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
|
2017-09-06 11:06:25 -06:00
|
|
|
end
|