cap again
[akkoma] / lib / pleroma / web / oauth / authorization.ex
index 9423c9632b6570b7c6ff67fcf509a5c432fcd36e..5a68bd5932a1419d6ae6c1189a79f0c0cf1dec0e 100644 (file)
@@ -1,8 +1,10 @@
 defmodule Pleroma.Web.OAuth.Authorization do
   use Ecto.Schema
 
-  alias Pleroma.{App, User, Repo}
-  alias Pleroma.Web.OAuth.Authorization
+  alias Pleroma.{User, Repo}
+  alias Pleroma.Web.OAuth.{Authorization, App}
+
+  import Ecto.{Changeset}
 
   schema "oauth_authorizations" do
     field :token, :string
@@ -27,4 +29,19 @@ defmodule Pleroma.Web.OAuth.Authorization do
 
     Repo.insert(authorization)
   end
+
+  def use_changeset(%Authorization{} = auth, params) do
+    auth
+    |> cast(params, [:used])
+    |> validate_required([:used])
+  end
+
+  def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
+    if NaiveDateTime.diff(NaiveDateTime.utc_now, valid_until) < 0 do
+      Repo.update(use_changeset(auth, %{used: true}))
+    else
+      {:error, "Token expired"}
+    end
+  end
+  def use_token(%Authorization{used: true}), do: {:error, "Already used"}
 end