philomena/lib/philomena_web/plugs/current_ban_plug.ex

50 lines
1.1 KiB
Elixir
Raw Permalink Normal View History

2019-11-17 19:18:21 +01:00
defmodule PhilomenaWeb.CurrentBanPlug do
2019-11-16 01:40:32 +01:00
@moduledoc """
This plug loads the ban for the current user.
## Example
2019-11-17 19:18:21 +01:00
plug PhilomenaWeb.CurrentBanPlug
2019-11-16 01:40:32 +01:00
"""
alias Philomena.Bans
alias Plug.Conn
@doc false
@spec init(any()) :: any()
def init(opts), do: opts
@doc false
@spec call(Conn.t(), any()) :: Conn.t()
def call(conn, _opts) do
conn = Conn.fetch_cookies(conn)
2019-11-16 01:40:32 +01:00
fingerprint = conn.cookies["_ses"]
user = conn.assigns.current_user
2019-11-16 01:40:32 +01:00
ip = conn.remote_ip
ban = Bans.exists_for?(user, ip, fingerprint)
2020-06-04 02:47:36 +02:00
cond do
discourage?(ban) ->
Conn.register_before_send(conn, fn conn ->
:timer.sleep(normal_time())
pass(error?(), conn)
end)
2020-06-04 03:26:38 +02:00
|> Conn.assign(:current_ban, nil)
2020-06-04 02:47:36 +02:00
true ->
Conn.assign(conn, :current_ban, ban)
end
2019-11-16 01:40:32 +01:00
end
2020-06-04 02:47:36 +02:00
defp discourage?(%{note: note}) when is_binary(note), do: String.contains?(note, "discourage")
defp discourage?(_ban), do: false
2020-06-04 03:18:31 +02:00
defp normal_time, do: :rand.normal(5_000, 25_000_000) |> trunc() |> max(0)
2020-06-04 02:47:36 +02:00
defp error?, do: :rand.uniform() < 0.05
defp pass(false, conn), do: conn
defp pass(_true, _conn), do: nil
2020-01-11 05:20:19 +01:00
end