[#468] Refactored OAuth scopes' defaults & missing selection handling.
[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.{User, Repo}
9 alias Pleroma.Web.OAuth.{Authorization, App}
10
11 import Ecto.{Changeset, Query}
12
13 schema "oauth_authorizations" do
14 field(:token, :string)
15 field(:scopes, {:array, :string}, default: [])
16 field(:valid_until, :naive_datetime)
17 field(:used, :boolean, default: false)
18 belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId)
19 belongs_to(:app, App)
20
21 timestamps()
22 end
23
24 def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do
25 scopes = scopes || app.scopes
26 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
27
28 authorization = %Authorization{
29 token: token,
30 used: false,
31 user_id: user.id,
32 app_id: app.id,
33 scopes: scopes,
34 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
35 }
36
37 Repo.insert(authorization)
38 end
39
40 def use_changeset(%Authorization{} = auth, params) do
41 auth
42 |> cast(params, [:used])
43 |> validate_required([:used])
44 end
45
46 def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
47 if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
48 Repo.update(use_changeset(auth, %{used: true}))
49 else
50 {:error, "token expired"}
51 end
52 end
53
54 def use_token(%Authorization{used: true}), do: {:error, "already used"}
55
56 def delete_user_authorizations(%User{id: user_id}) do
57 from(
58 a in Pleroma.Web.OAuth.Authorization,
59 where: a.user_id == ^user_id
60 )
61 |> Repo.delete_all()
62 end
63 end