To protect the application against automated attacks aimed at guessing promotional codes.
defmodule MyAppWeb.PromoController do
use MyAppWeb, :controller
def check_promo(conn, %{"promo_code" => promo_code}) do
if PromoCode.valid?(promo_code) do
render(conn, "success.html")
else
render(conn, "failure.html")
end
end
end
The code above is vulnerable because it directly accepts and verifies promo codes without any rate limiting or captcha protection. This can be exploited by an attacker to conduct brute force attacks, i.e., trying different codes until a valid one is found.
defmodule MyAppWeb.PromoController do
use MyAppWeb, :controller
plug MyAppWeb.Plugs.RateLimiter when action in [:check_promo]
def check_promo(conn, %{"promo_code" => promo_code}) do
if PromoCode.valid?(promo_code) do
render(conn, "success.html")
else
render(conn, "failure.html")
end
end
end
The updated code now includes a rate limiter which limits the number of requests that can be made to the 'check_promo' endpoint within a certain timeframe. This mitigates the risk of brute force attacks by making it infeasible to guess a valid promo code within a reasonable time.