[#468] Refactored OAuth scopes' defaults & missing selection handling.
[akkoma] / lib / pleroma / web / oauth / token.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.Token do
6 use Ecto.Schema
7
8 import Ecto.Query
9
10 alias Pleroma.{User, Repo}
11 alias Pleroma.Web.OAuth.{Token, App, Authorization}
12
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)
19 belongs_to(:app, App)
20
21 timestamps()
22 end
23
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)
28 end
29 end
30
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()
35
36 token = %Token{
37 token: token,
38 refresh_token: refresh_token,
39 scopes: scopes,
40 user_id: user.id,
41 app_id: app.id,
42 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
43 }
44
45 Repo.insert(token)
46 end
47
48 def delete_user_tokens(%User{id: user_id}) do
49 from(
50 t in Pleroma.Web.OAuth.Token,
51 where: t.user_id == ^user_id
52 )
53 |> Repo.delete_all()
54 end
55 end