Merge branch 'feature/create-tombstone-instead-of-delete' into 'develop'
[akkoma] / lib / pleroma / web / oauth / authorization.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 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(:valid_until, :naive_datetime)
16 field(:used, :boolean, default: false)
17 belongs_to(:user, Pleroma.User)
18 belongs_to(:app, App)
19
20 timestamps()
21 end
22
23 def create_authorization(%App{} = app, %User{} = user) do
24 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
25
26 authorization = %Authorization{
27 token: token,
28 used: false,
29 user_id: user.id,
30 app_id: app.id,
31 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
32 }
33
34 Repo.insert(authorization)
35 end
36
37 def use_changeset(%Authorization{} = auth, params) do
38 auth
39 |> cast(params, [:used])
40 |> validate_required([:used])
41 end
42
43 def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
44 if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
45 Repo.update(use_changeset(auth, %{used: true}))
46 else
47 {:error, "token expired"}
48 end
49 end
50
51 def use_token(%Authorization{used: true}), do: {:error, "already used"}
52
53 def delete_user_authorizations(%User{id: user_id}) do
54 from(
55 a in Pleroma.Web.OAuth.Authorization,
56 where: a.user_id == ^user_id
57 )
58 |> Repo.delete_all()
59 end
60 end