1 defmodule Pleroma.Web.OAuth.Authorization do
4 alias Pleroma.{User, Repo}
5 alias Pleroma.Web.OAuth.{Authorization, App}
7 import Ecto.{Changeset, Query}
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)
19 def create_authorization(%App{} = app, %User{} = user) do
20 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
22 authorization = %Authorization{
27 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
30 Repo.insert(authorization)
33 def use_changeset(%Authorization{} = auth, params) do
35 |> cast(params, [:used])
36 |> validate_required([:used])
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}))
43 {:error, "token expired"}
47 def use_token(%Authorization{used: true}), do: {:error, "already used"}
49 def delete_user_authorizations(%User{id: user_id}) do
51 a in Pleroma.Web.OAuth.Authorization,
52 where: a.user_id == ^user_id