Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / test / web / oauth / authorization_test.exs
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.AuthorizationTest do
6 use Pleroma.DataCase
7 alias Pleroma.Web.OAuth.App
8 alias Pleroma.Web.OAuth.Authorization
9 import Pleroma.Factory
10
11 setup 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
21 %{app: app}
22 end
23
24 test "create an authorization token for a valid app", %{app: app} do
25 user = insert(:user)
26
27 {:ok, auth1} = Authorization.create_authorization(app, user)
28 assert auth1.scopes == app.scopes
29
30 {:ok, auth2} = Authorization.create_authorization(app, user, ["read"])
31 assert auth2.scopes == ["read"]
32
33 for auth <- [auth1, auth2] do
34 assert auth.user_id == user.id
35 assert auth.app_id == app.id
36 assert String.length(auth.token) > 10
37 assert auth.used == false
38 end
39 end
40
41 test "use up a token", %{app: app} do
42 user = insert(:user)
43
44 {:ok, auth} = Authorization.create_authorization(app, user)
45
46 {:ok, auth} = Authorization.use_token(auth)
47
48 assert auth.used == true
49
50 assert {:error, "already used"} == Authorization.use_token(auth)
51
52 expired_auth = %Authorization{
53 user_id: user.id,
54 app_id: app.id,
55 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -10),
56 token: "mytoken",
57 used: false
58 }
59
60 {:ok, expired_auth} = Repo.insert(expired_auth)
61
62 assert {:error, "token expired"} == Authorization.use_token(expired_auth)
63 end
64
65 test "delete authorizations", %{app: app} do
66 user = insert(:user)
67
68 {:ok, auth} = Authorization.create_authorization(app, user)
69 {:ok, auth} = Authorization.use_token(auth)
70
71 Authorization.delete_user_authorizations(user)
72
73 {_, invalid} = Authorization.use_token(auth)
74
75 assert auth != invalid
76 end
77 end