summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/farside/application.ex3
-rw-r--r--lib/farside/router.ex1
-rw-r--r--lib/farside/throttle.ex19
3 files changed, 22 insertions, 1 deletions
diff --git a/lib/farside/application.ex b/lib/farside/application.ex
index 708ff0d..fd199e1 100644
--- a/lib/farside/application.ex
+++ b/lib/farside/application.ex
@@ -8,7 +8,8 @@ defmodule Farside.Application do
def start(_type, _args) do
children = [
Plug.Cowboy.child_spec(scheme: :http, plug: Farside.Router, options: [port: 4001]),
- {Redix, {@redis_conn, [name: :redix]}}
+ {Redix, {@redis_conn, [name: :redix]}},
+ {PlugAttack.Storage.Ets, name: Farside.Throttle.Storage, clean_period: 60_000}
]
opts = [strategy: :one_for_one, name: Farside.Supervisor]
diff --git a/lib/farside/router.ex b/lib/farside/router.ex
index 7f31e04..e2014b2 100644
--- a/lib/farside/router.ex
+++ b/lib/farside/router.ex
@@ -3,6 +3,7 @@ defmodule Farside.Router do
use Plug.Router
+ plug(Farside.Throttle)
plug(:match)
plug(:dispatch)
diff --git a/lib/farside/throttle.ex b/lib/farside/throttle.ex
new file mode 100644
index 0000000..fc8b591
--- /dev/null
+++ b/lib/farside/throttle.ex
@@ -0,0 +1,19 @@
+defmodule Farside.Throttle do
+ import Plug.Conn
+ use PlugAttack
+
+ rule "throttle per ip", conn do
+ # throttle to 1 request per second
+ throttle conn.remote_ip,
+ period: 1_000, limit: 1,
+ storage: {PlugAttack.Storage.Ets, Farside.Throttle.Storage}
+ end
+
+ def allow_action(conn, _data, _opts), do: conn
+
+ def block_action(conn, _data, _opts) do
+ conn
+ |> send_resp(:forbidden, "Exceeded rate limit\n")
+ |> halt
+ end
+end