1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Plugs.EnsureAuthenticatedPlugTest do
6 use Pleroma.Web.ConnCase, async: true
9 alias Pleroma.Web.Plugs.EnsureAuthenticatedPlug
11 describe "without :if_func / :unless_func options" do
12 test "it halts if user is NOT assigned", %{conn: conn} do
13 conn = EnsureAuthenticatedPlug.call(conn, %{})
15 assert conn.status == 403
16 assert conn.halted == true
19 test "it continues if a user is assigned", %{conn: conn} do
20 conn = assign(conn, :user, %User{})
21 ret_conn = EnsureAuthenticatedPlug.call(conn, %{})
23 refute ret_conn.halted
27 test "it halts if user is assigned and MFA enabled", %{conn: conn} do
30 |> assign(:user, %User{multi_factor_authentication_settings: %{enabled: true}})
31 |> assign(:auth_credentials, %{password: "xd-42"})
32 |> EnsureAuthenticatedPlug.call(%{})
34 assert conn.status == 403
35 assert conn.halted == true
37 assert conn.resp_body ==
38 "{\"error\":\"Two-factor authentication enabled, you must use a access token.\"}"
41 test "it continues if user is assigned and MFA disabled", %{conn: conn} do
44 |> assign(:user, %User{multi_factor_authentication_settings: %{enabled: false}})
45 |> assign(:auth_credentials, %{password: "xd-42"})
46 |> EnsureAuthenticatedPlug.call(%{})
48 refute conn.status == 403
52 describe "with :if_func / :unless_func options" do
55 true_fn: fn _conn -> true end,
56 false_fn: fn _conn -> false end
60 test "it continues if a user is assigned", %{conn: conn, true_fn: true_fn, false_fn: false_fn} do
61 conn = assign(conn, :user, %User{})
62 refute EnsureAuthenticatedPlug.call(conn, if_func: true_fn).halted
63 refute EnsureAuthenticatedPlug.call(conn, if_func: false_fn).halted
64 refute EnsureAuthenticatedPlug.call(conn, unless_func: true_fn).halted
65 refute EnsureAuthenticatedPlug.call(conn, unless_func: false_fn).halted
68 test "it continues if a user is NOT assigned but :if_func evaluates to `false`",
69 %{conn: conn, false_fn: false_fn} do
70 ret_conn = EnsureAuthenticatedPlug.call(conn, if_func: false_fn)
71 refute ret_conn.halted
74 test "it continues if a user is NOT assigned but :unless_func evaluates to `true`",
75 %{conn: conn, true_fn: true_fn} do
76 ret_conn = EnsureAuthenticatedPlug.call(conn, unless_func: true_fn)
77 refute ret_conn.halted
80 test "it halts if a user is NOT assigned and :if_func evaluates to `true`",
81 %{conn: conn, true_fn: true_fn} do
82 conn = EnsureAuthenticatedPlug.call(conn, if_func: true_fn)
84 assert conn.status == 403
85 assert conn.halted == true
88 test "it halts if a user is NOT assigned and :unless_func evaluates to `false`",
89 %{conn: conn, false_fn: false_fn} do
90 conn = EnsureAuthenticatedPlug.call(conn, unless_func: false_fn)
92 assert conn.status == 403
93 assert conn.halted == true