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.Token do
10 alias Pleroma.{User, Repo}
11 alias Pleroma.Web.OAuth.{Token, App, Authorization}
13 schema "oauth_tokens" do
14 field(:token, :string)
15 field(:refresh_token, :string)
16 field(:scopes, {:array, :string}, default: [])
17 field(:valid_until, :naive_datetime)
18 belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId)
24 def exchange_token(app, auth) do
25 with {:ok, auth} <- Authorization.use_token(auth),
26 true <- auth.app_id == app.id do
27 create_token(app, Repo.get(User, auth.user_id), auth.scopes)
31 def create_token(%App{} = app, %User{} = user, scopes \\ nil) do
32 scopes = scopes || app.scopes
33 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
34 refresh_token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
38 refresh_token: refresh_token,
42 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
48 def delete_user_tokens(%User{id: user_id}) do
50 t in Pleroma.Web.OAuth.Token,
51 where: t.user_id == ^user_id