Add Twitter API verify_credentials endpoint.
[akkoma] / test / plugs / authentication_plug_test.exs
1 defmodule Pleroma.Plugs.AuthenticationPlugTest do
2 use Pleroma.Web.ConnCase, async: true
3
4 alias Pleroma.Plugs.AuthenticationPlug
5
6 defp fetch_nil(_name) do
7 {:ok, nil}
8 end
9
10 @user %{
11 id: 1,
12 name: "dude",
13 password_hash: Comeonin.Pbkdf2.hashpwsalt("guy")
14 }
15
16 defp fetch_user(_name) do
17 {:ok, @user}
18 end
19
20 defp basic_auth_enc(username, password) do
21 "Basic " <> Base.encode64("#{username}:#{password}")
22 end
23
24 describe "without an authorization header" do
25 test "it halts the application" do
26 conn = build_conn() |> AuthenticationPlug.call(%{})
27
28 assert conn.status == 403
29 assert conn.halted == true
30 end
31
32 test "it assigns a nil user if the 'optional' option is used" do
33 conn = build_conn() |> AuthenticationPlug.call(%{optional: true})
34
35 assert %{ user: nil } == conn.assigns
36 end
37 end
38
39 describe "with an authorization header for a nonexisting user" do
40 test "it halts the application" do
41 conn =
42 build_conn()
43 |> AuthenticationPlug.call(%{fetcher: &fetch_nil/1})
44
45 assert conn.status == 403
46 assert conn.halted == true
47 end
48
49 test "it assigns a nil user if the 'optional' option is used" do
50 conn =
51 build_conn()
52 |> AuthenticationPlug.call(%{optional: true, fetcher: &fetch_nil/1 })
53
54 assert %{ user: nil } == conn.assigns
55 end
56 end
57
58 describe "with an incorrect authorization header for a enxisting user" do
59 test "it halts the application" do
60 opts = %{
61 fetcher: &fetch_user/1
62 }
63
64 header = basic_auth_enc("dude", "man")
65
66 conn =
67 build_conn()
68 |> put_req_header("authorization", header)
69 |> AuthenticationPlug.call(opts)
70
71 assert conn.status == 403
72 assert conn.halted == true
73 end
74
75 test "it assigns a nil user if the 'optional' option is used" do
76 opts = %{
77 optional: true,
78 fetcher: &fetch_user/1
79 }
80
81 header = basic_auth_enc("dude", "man")
82
83 conn =
84 build_conn()
85 |> put_req_header("authorization", header)
86 |> AuthenticationPlug.call(opts)
87
88 assert %{ user: nil } == conn.assigns
89 end
90 end
91
92 describe "with a correct authorization header for an existing user" do
93 test "it assigns the user" do
94 opts = %{
95 optional: true,
96 fetcher: &fetch_user/1
97 }
98
99 header = basic_auth_enc("dude", "guy")
100
101 conn =
102 build_conn()
103 |> put_req_header("authorization", header)
104 |> AuthenticationPlug.call(opts)
105
106 assert %{ user: @user } == conn.assigns
107 assert conn.halted == false
108 end
109 end
110 end