1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.Authorization do
10 alias Pleroma.Web.OAuth.App
11 alias Pleroma.Web.OAuth.Authorization
12 alias Pleroma.Web.OAuth.Token
17 @type t :: %__MODULE__{}
19 schema "oauth_authorizations" do
20 field(:token, :string)
21 field(:scopes, {:array, :string}, default: [])
22 field(:valid_until, :naive_datetime_usec)
23 field(:used, :boolean, default: false)
24 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
30 @spec create_authorization(App.t(), User.t() | %{}, [String.t()] | nil) ::
31 {:ok, Authorization.t()} | {:error, Ecto.Changeset.t()}
32 def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do
34 scopes: scopes || app.scopes,
42 @spec create_changeset(map()) :: Ecto.Changeset.t()
43 def create_changeset(attrs \\ %{}) do
45 |> cast(attrs, [:user_id, :app_id, :scopes, :valid_until])
46 |> validate_required([:app_id, :scopes])
51 defp add_token(changeset) do
52 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
53 put_change(changeset, :token, token)
56 defp add_lifetime(changeset) do
57 lifespan = Token.lifespan()
58 put_change(changeset, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), lifespan))
61 @spec use_changeset(Authorization.t(), map()) :: Ecto.Changeset.t()
62 def use_changeset(%Authorization{} = auth, params) do
64 |> cast(params, [:used])
65 |> validate_required([:used])
68 @spec use_token(Authorization.t()) ::
69 {:ok, Authorization.t()} | {:error, Ecto.Changeset.t()} | {:error, String.t()}
70 def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
71 if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
72 Repo.update(use_changeset(auth, %{used: true}))
74 {:error, "token expired"}
78 def use_token(%Authorization{used: true}), do: {:error, "already used"}
80 @spec delete_user_authorizations(User.t()) :: {integer(), any()}
81 def delete_user_authorizations(%User{} = user) do
83 |> delete_by_user_query
87 def delete_by_user_query(%User{id: user_id}) do
88 from(a in __MODULE__, where: a.user_id == ^user_id)
91 @doc "gets auth for app by token"
92 @spec get_by_token(App.t(), String.t()) :: {:ok, t()} | {:error, :not_found}
93 def get_by_token(%App{id: app_id} = _app, token) do
94 from(t in __MODULE__, where: t.app_id == ^app_id and t.token == ^token)
95 |> Repo.find_resource()