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
12 alias Pleroma.Web.OAuth.{Token, App, Authorization}
14 schema "oauth_tokens" do
15 field(:token, :string)
16 field(:refresh_token, :string)
17 field(:scope, :string)
18 field(:valid_until, :naive_datetime)
19 belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId)
25 def exchange_token(app, auth) do
26 with {:ok, auth} <- Authorization.use_token(auth),
27 true <- auth.app_id == app.id do
28 create_token(app, Repo.get(User, auth.user_id), auth.scope)
32 def create_token(%App{} = app, %User{} = user, scope \\ nil) do
33 scopes = OAuth.parse_scopes(scope || app.scopes)
34 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
35 refresh_token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
39 refresh_token: refresh_token,
40 scope: Enum.join(scopes, " "),
43 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
49 def delete_user_tokens(%User{id: user_id}) do
51 t in Pleroma.Web.OAuth.Token,
52 where: t.user_id == ^user_id