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.
19 config :pleroma, :rate_limit,
21 two: [{10_000, 10}, {10_000, 50}]
23 Here we have two limiters: `one` which is not over 10req/1s and `two` which has two limits 10req/10s for unauthenticated users and 50req/10s for authenticated users.
29 plug(Pleroma.Plugs.RateLimiter, :one when action == :one)
30 plug(Pleroma.Plugs.RateLimiter, :two when action in [:two, :three])
32 or inside a router pipiline:
36 plug(Pleroma.Plugs.RateLimiter, :one)
41 import Phoenix.Controller, only: [json: 2]
46 def init(limiter_name) do
47 case Pleroma.Config.get([:rate_limit, limiter_name]) do
49 config -> {limiter_name, config}
53 # do not limit if there is no limiter configuration
54 def call(conn, nil), do: conn
56 def call(conn, opts) do
57 case check_rate(conn, opts) do
59 {:error, _count} -> render_error(conn)
63 defp check_rate(%{assigns: %{user: %User{id: user_id}}}, {limiter_name, [_, {scale, limit}]}) do
64 ExRated.check_rate("#{limiter_name}:#{user_id}", scale, limit)
67 defp check_rate(conn, {limiter_name, [{scale, limit} | _]}) do
68 ExRated.check_rate("#{limiter_name}:#{ip(conn)}", scale, limit)
71 defp check_rate(conn, {limiter_name, {scale, limit}}) do
72 check_rate(conn, {limiter_name, [{scale, limit}]})
75 def ip(%{remote_ip: remote_ip}) do
81 defp render_error(conn) do
83 |> put_status(:too_many_requests)
84 |> json(%{error: "Throttled"})