Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
[akkoma] / lib / pleroma / web / oauth / authorization.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.Authorization do
6 use Ecto.Schema
7
8 alias Pleroma.Repo
9 alias Pleroma.User
10 alias Pleroma.Web.OAuth.App
11 alias Pleroma.Web.OAuth.Authorization
12
13 import Ecto.Changeset
14 import Ecto.Query
15
16 @type t :: %__MODULE__{}
17 schema "oauth_authorizations" do
18 field(:token, :string)
19 field(:scopes, {:array, :string}, default: [])
20 field(:valid_until, :naive_datetime_usec)
21 field(:used, :boolean, default: false)
22 belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId)
23 belongs_to(:app, App)
24
25 timestamps()
26 end
27
28 def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do
29 scopes = scopes || app.scopes
30 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
31
32 authorization = %Authorization{
33 token: token,
34 used: false,
35 user_id: user.id,
36 app_id: app.id,
37 scopes: scopes,
38 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
39 }
40
41 Repo.insert(authorization)
42 end
43
44 def use_changeset(%Authorization{} = auth, params) do
45 auth
46 |> cast(params, [:used])
47 |> validate_required([:used])
48 end
49
50 def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
51 if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
52 Repo.update(use_changeset(auth, %{used: true}))
53 else
54 {:error, "token expired"}
55 end
56 end
57
58 def use_token(%Authorization{used: true}), do: {:error, "already used"}
59
60 def delete_user_authorizations(%User{id: user_id}) do
61 from(
62 a in Pleroma.Web.OAuth.Authorization,
63 where: a.user_id == ^user_id
64 )
65 |> Repo.delete_all()
66 end
67
68 @doc "gets auth for app by token"
69 @spec get_by_token(App.t(), String.t()) :: {:ok, t()} | {:error, :not_found}
70 def get_by_token(%App{id: app_id} = _app, token) do
71 from(t in __MODULE__, where: t.app_id == ^app_id and t.token == ^token)
72 |> Repo.find_resource()
73 end
74 end