Prevent mass messages from being sent to a single user, causing resource saturation.
defmodule MyApp.MessageController do
use MyApp.Web, :controller
def send_message(conn, %{"recipient" => recipient, "message" => message}) do
MyApp.Messaging.send_email(recipient, message)
MyApp.Messaging.send_sms(recipient, message)
send_resp(conn, :ok, "Message sent")
end
end
This code is insecure because it allows for repeated and rapid message sending to the same recipient without any form of rate limiting or restriction. This can lead to message flooding, causing the recipient's resources to be unnecessarily consumed and possibly causing important information to be lost in the flood.
defmodule MyApp.MessageController do
use MyApp.Web, :controller
def send_message(conn, %{"recipient" => recipient, "message" => message}) do
if MyApp.Messaging.can_send_message?(recipient) do
MyApp.Messaging.send_email(recipient, message)
MyApp.Messaging.send_sms(recipient, message)
MyApp.Messaging.record_message_sent(recipient)
send_resp(conn, :ok, "Message sent")
else
send_resp(conn, :too_many_requests, "Too many messages have been sent. Please wait before sending again.")
end
end
end
This code is secure because it implements a rate limiting mechanism that restricts the number of messages that can be sent to a single recipient in a given time frame. It checks if a message can be sent before actually sending the message and records the sent message for future checks. This prevents message flooding and conserves the recipient's resources.