Merge branch 'develop' into tests/mastodon_api_controller.ex
[akkoma] / test / plugs / oauth_plug_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.Plugs.OAuthPlugTest do
6 use Pleroma.Web.ConnCase, async: true
7
8 alias Pleroma.Plugs.OAuthPlug
9 import Pleroma.Factory
10
11 @session_opts [
12 store: :cookie,
13 key: "_test",
14 signing_salt: "cooldude"
15 ]
16
17 setup %{conn: conn} do
18 user = insert(:user)
19 {:ok, %{token: token}} = Pleroma.Web.OAuth.Token.create_token(insert(:oauth_app), user)
20 %{user: user, token: token, conn: conn}
21 end
22
23 test "with valid token(uppercase), it assigns the user", %{conn: conn} = opts do
24 conn =
25 conn
26 |> put_req_header("authorization", "BEARER #{opts[:token]}")
27 |> OAuthPlug.call(%{})
28
29 assert conn.assigns[:user] == opts[:user]
30 end
31
32 test "with valid token(downcase), it assigns the user", %{conn: conn} = opts do
33 conn =
34 conn
35 |> put_req_header("authorization", "bearer #{opts[:token]}")
36 |> OAuthPlug.call(%{})
37
38 assert conn.assigns[:user] == opts[:user]
39 end
40
41 test "with valid token(downcase) in url parameters, it assings the user", opts do
42 conn =
43 :get
44 |> build_conn("/?access_token=#{opts[:token]}")
45 |> put_req_header("content-type", "application/json")
46 |> fetch_query_params()
47 |> OAuthPlug.call(%{})
48
49 assert conn.assigns[:user] == opts[:user]
50 end
51
52 test "with valid token(downcase) in body parameters, it assigns the user", opts do
53 conn =
54 :post
55 |> build_conn("/api/v1/statuses", access_token: opts[:token], status: "test")
56 |> OAuthPlug.call(%{})
57
58 assert conn.assigns[:user] == opts[:user]
59 end
60
61 test "with invalid token, it not assigns the user", %{conn: conn} do
62 conn =
63 conn
64 |> put_req_header("authorization", "bearer TTTTT")
65 |> OAuthPlug.call(%{})
66
67 refute conn.assigns[:user]
68 end
69
70 test "when token is missed but token in session, it assigns the user", %{conn: conn} = opts do
71 conn =
72 conn
73 |> Plug.Session.call(Plug.Session.init(@session_opts))
74 |> fetch_session()
75 |> put_session(:oauth_token, opts[:token])
76 |> OAuthPlug.call(%{})
77
78 assert conn.assigns[:user] == opts[:user]
79 end
80 end