1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.TokenTest do
8 alias Pleroma.Web.OAuth.App
9 alias Pleroma.Web.OAuth.Authorization
10 alias Pleroma.Web.OAuth.Token
12 import Pleroma.Factory
14 test "exchanges a auth token for an access token, preserving `scopes`" do
17 App.register_changeset(%App{}, %{
18 client_name: "client",
19 scopes: ["read", "write"],
26 {:ok, auth} = Authorization.create_authorization(app, user, ["read"])
27 assert auth.scopes == ["read"]
29 {:ok, token} = Token.exchange_token(app, auth)
31 assert token.app_id == app.id
32 assert token.user_id == user.id
33 assert token.scopes == auth.scopes
34 assert String.length(token.token) > 10
35 assert String.length(token.refresh_token) > 10
37 auth = Repo.get(Authorization, auth.id)
38 {:error, "already used"} = Token.exchange_token(app, auth)
41 test "deletes all tokens of a user" do
44 App.register_changeset(%App{}, %{
45 client_name: "client1",
53 App.register_changeset(%App{}, %{
54 client_name: "client2",
62 {:ok, auth1} = Authorization.create_authorization(app1, user)
63 {:ok, auth2} = Authorization.create_authorization(app2, user)
65 {:ok, _token1} = Token.exchange_token(app1, auth1)
66 {:ok, _token2} = Token.exchange_token(app2, auth2)
68 {tokens, _} = Token.delete_user_tokens(user)
73 test "deletes expired tokens" do
74 insert(:oauth_token, valid_until: Timex.shift(Timex.now(), days: -3))
75 insert(:oauth_token, valid_until: Timex.shift(Timex.now(), days: -3))
76 t3 = insert(:oauth_token)
77 t4 = insert(:oauth_token, valid_until: Timex.shift(Timex.now(), minutes: 10))
78 {tokens, _} = Token.delete_expired_tokens()
80 available_tokens = Pleroma.Repo.all(Token)
82 token_ids = available_tokens |> Enum.map(& &1.id)
83 assert token_ids == [t3.id, t4.id]