Format the code.
[akkoma] / lib / pleroma / web / oauth / authorization.ex
1 defmodule Pleroma.Web.OAuth.Authorization do
2 use Ecto.Schema
3
4 alias Pleroma.{User, Repo}
5 alias Pleroma.Web.OAuth.{Authorization, App}
6
7 import Ecto.{Changeset}
8
9 schema "oauth_authorizations" do
10 field(:token, :string)
11 field(:valid_until, :naive_datetime)
12 field(:used, :boolean, default: false)
13 belongs_to(:user, Pleroma.User)
14 belongs_to(:app, Pleroma.App)
15
16 timestamps()
17 end
18
19 def create_authorization(%App{} = app, %User{} = user) do
20 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
21
22 authorization = %Authorization{
23 token: token,
24 used: false,
25 user_id: user.id,
26 app_id: app.id,
27 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
28 }
29
30 Repo.insert(authorization)
31 end
32
33 def use_changeset(%Authorization{} = auth, params) do
34 auth
35 |> cast(params, [:used])
36 |> validate_required([:used])
37 end
38
39 def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
40 if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
41 Repo.update(use_changeset(auth, %{used: true}))
42 else
43 {:error, "token expired"}
44 end
45 end
46
47 def use_token(%Authorization{used: true}), do: {:error, "already used"}
48 end