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