Fork of Pleroma with site-specific changes and feature branches https://git.pleroma.social/pleroma/pleroma
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.4KB

  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Web.OAuth.TokenTest do
  5. use Pleroma.DataCase
  6. alias Pleroma.Repo
  7. alias Pleroma.Web.OAuth.App
  8. alias Pleroma.Web.OAuth.Authorization
  9. alias Pleroma.Web.OAuth.Token
  10. import Pleroma.Factory
  11. test "exchanges a auth token for an access token, preserving `scopes`" do
  12. {:ok, app} =
  13. Repo.insert(
  14. App.register_changeset(%App{}, %{
  15. client_name: "client",
  16. scopes: ["read", "write"],
  17. redirect_uris: "url"
  18. })
  19. )
  20. user = insert(:user)
  21. {:ok, auth} = Authorization.create_authorization(app, user, ["read"])
  22. assert auth.scopes == ["read"]
  23. {:ok, token} = Token.exchange_token(app, auth)
  24. assert token.app_id == app.id
  25. assert token.user_id == user.id
  26. assert token.scopes == auth.scopes
  27. assert String.length(token.token) > 10
  28. assert String.length(token.refresh_token) > 10
  29. auth = Repo.get(Authorization, auth.id)
  30. {:error, "already used"} = Token.exchange_token(app, auth)
  31. end
  32. test "deletes all tokens of a user" do
  33. {:ok, app1} =
  34. Repo.insert(
  35. App.register_changeset(%App{}, %{
  36. client_name: "client1",
  37. scopes: ["scope"],
  38. redirect_uris: "url"
  39. })
  40. )
  41. {:ok, app2} =
  42. Repo.insert(
  43. App.register_changeset(%App{}, %{
  44. client_name: "client2",
  45. scopes: ["scope"],
  46. redirect_uris: "url"
  47. })
  48. )
  49. user = insert(:user)
  50. {:ok, auth1} = Authorization.create_authorization(app1, user)
  51. {:ok, auth2} = Authorization.create_authorization(app2, user)
  52. {:ok, _token1} = Token.exchange_token(app1, auth1)
  53. {:ok, _token2} = Token.exchange_token(app2, auth2)
  54. {tokens, _} = Token.delete_user_tokens(user)
  55. assert tokens == 2
  56. end
  57. test "deletes expired tokens" do
  58. insert(:oauth_token, valid_until: Timex.shift(Timex.now(), days: -3))
  59. insert(:oauth_token, valid_until: Timex.shift(Timex.now(), days: -3))
  60. t3 = insert(:oauth_token)
  61. t4 = insert(:oauth_token, valid_until: Timex.shift(Timex.now(), minutes: 10))
  62. {tokens, _} = Token.delete_expired_tokens()
  63. assert tokens == 2
  64. available_tokens = Pleroma.Repo.all(Token)
  65. token_ids = available_tokens |> Enum.map(& &1.id)
  66. assert token_ids == [t3.id, t4.id]
  67. end
  68. end