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
10 alias Pleroma.Web.OAuth.App
11 alias Pleroma.Web.OAuth.Authorization
16 @type t :: %__MODULE__{}
17 schema "oauth_authorizations" do
18 field(:token, :string)
19 field(:scopes, {:array, :string}, default: [])
20 field(:valid_until, :naive_datetime_usec)
21 field(:used, :boolean, default: false)
22 belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId)
28 def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do
29 scopes = scopes || app.scopes
30 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
32 authorization = %Authorization{
38 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
41 Repo.insert(authorization)
44 def use_changeset(%Authorization{} = auth, params) do
46 |> cast(params, [:used])
47 |> validate_required([:used])
50 def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
51 if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
52 Repo.update(use_changeset(auth, %{used: true}))
54 {:error, "token expired"}
58 def use_token(%Authorization{used: true}), do: {:error, "already used"}
60 def delete_user_authorizations(%User{id: user_id}) do
62 a in Pleroma.Web.OAuth.Authorization,
63 where: a.user_id == ^user_id
68 @doc "gets auth for app by token"
69 @spec get_by_token(App.t(), String.t()) :: {:ok, t()} | {:error, :not_found}
70 def get_by_token(%App{id: app_id} = _app, token) do
71 from(t in __MODULE__, where: t.app_id == ^app_id and t.token == ^token)
72 |> Repo.find_resource()