1 defmodule Pleroma.Web.OAuth.Authorization do
4 alias Pleroma.{User, Repo}
5 alias Pleroma.Web.OAuth.{Authorization, App}
7 import Ecto.{Changeset}
9 schema "oauth_authorizations" do
11 field :valid_until, :naive_datetime
12 field :used, :boolean, default: false
13 belongs_to :user, Pleroma.User
14 belongs_to :app, Pleroma.App
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"}
46 def use_token(%Authorization{used: true}), do: {:error, "already used"}