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