1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Plugs.RateLimiter do
10 A keyword list of rate limiters where a key is a limiter name and value is the limiter configuration. The basic configuration is a tuple where:
12 * The first element: `scale` (Integer). The time scale in milliseconds.
13 * The second element: `limit` (Integer). How many requests to limit in the time scale provided.
15 It is also possible to have different limits for unauthenticated and authenticated users: the keyword value must be a list of two tuples where the first one is a config for unauthenticated users and the second one is for authenticated.
17 To disable a limiter set its value to `nil`.
21 config :pleroma, :rate_limit,
23 two: [{10_000, 10}, {10_000, 50}],
26 Here we have three limiters:
28 * `one` which is not over 10req/1s
29 * `two` which has two limits: 10req/10s for unauthenticated users and 50req/10s for authenticated users
30 * `foobar` which is disabled
36 plug(Pleroma.Plugs.RateLimiter, :one when action == :one)
37 plug(Pleroma.Plugs.RateLimiter, :two when action in [:two, :three])
39 or inside a router pipiline:
43 plug(Pleroma.Plugs.RateLimiter, :one)
48 import Phoenix.Controller, only: [json: 2]
53 def init(limiter_name) do
54 case Pleroma.Config.get([:rate_limit, limiter_name]) do
56 config -> {limiter_name, config}
60 # do not limit if there is no limiter configuration
61 def call(conn, nil), do: conn
63 def call(conn, opts) do
64 case check_rate(conn, opts) do
66 {:error, _count} -> render_error(conn)
70 defp check_rate(%{assigns: %{user: %User{id: user_id}}}, {limiter_name, [_, {scale, limit}]}) do
71 ExRated.check_rate("#{limiter_name}:#{user_id}", scale, limit)
74 defp check_rate(conn, {limiter_name, [{scale, limit} | _]}) do
75 ExRated.check_rate("#{limiter_name}:#{ip(conn)}", scale, limit)
78 defp check_rate(conn, {limiter_name, {scale, limit}}) do
79 check_rate(conn, {limiter_name, [{scale, limit}]})
82 def ip(%{remote_ip: remote_ip}) do
88 defp render_error(conn) do
90 |> put_status(:too_many_requests)
91 |> json(%{error: "Throttled"})