Prevent unauthorized users from creating files
defmodule MyApp.FileController do
use MyApp, :controller
def create(conn, %{"file" => file_params}) do
# Create a new file
{:ok, file} = MyApp.File.create_file(file_params)
conn
|> put_status(:created)
|> render("show.json", file: file)
end
end
This code is vulnerable because it does not perform any access control check before creating a file. If a malicious user could craft a request to this endpoint, they could create a file regardless of their authorization level.
defmodule MyApp.FileController do
use MyApp, :controller
def create(conn, %{"file" => file_params}) do
# Check if the user has the necessary permissions
if MyApp.Authorization.check_permission(conn.assigns[:current_user], :create_file) do
# Create a new file
{:ok, file} = MyApp.File.create_file(file_params)
conn
|> put_status(:created)
|> render("show.json", file: file)
else
conn
|> put_status(:forbidden)
|> json(%{error: "You do not have the necessary permissions to perform this action."})
end
end
end
In the secure version, the application checks if the current user has the necessary permissions to create a file before performing the action. If they do not, the request is denied.