1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.Authorization do
8 alias Pleroma.{User, Repo}
9 alias Pleroma.Web.OAuth.{Authorization, App}
11 import Ecto.{Changeset, Query}
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)
23 def create_authorization(%App{} = app, %User{} = user) do
24 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
26 authorization = %Authorization{
31 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
34 Repo.insert(authorization)
37 def use_changeset(%Authorization{} = auth, params) do
39 |> cast(params, [:used])
40 |> validate_required([:used])
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}))
47 {:error, "token expired"}
51 def use_token(%Authorization{used: true}), do: {:error, "already used"}
53 def delete_user_authorizations(%User{id: user_id}) do
55 a in Pleroma.Web.OAuth.Authorization,
56 where: a.user_id == ^user_id