[#468] Prototype of OAuth2 scopes support. TwitterAPI scope restrictions.
[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
12 alias Pleroma.Web.OAuth.{Token, App, Authorization}
13
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)
20 belongs_to(:app, App)
21
22 timestamps()
23 end
24
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)
29 end
30 end
31
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()
36
37 token = %Token{
38 token: token,
39 refresh_token: refresh_token,
40 scope: Enum.join(scopes, " "),
41 user_id: user.id,
42 app_id: app.id,
43 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
44 }
45
46 Repo.insert(token)
47 end
48
49 def delete_user_tokens(%User{id: user_id}) do
50 from(
51 t in Pleroma.Web.OAuth.Token,
52 where: t.user_id == ^user_id
53 )
54 |> Repo.delete_all()
55 end
56 end