Prevent unauthorized access to user data
def show(conn, %{'id' => id}) do
user = Repo.get(User, id)
render(conn, 'show.json', user: user)
end
The insecure code example takes an 'id' parameter from the incoming request and directly uses it to fetch the user data from the database. This means that an attacker can modify the 'id' in the request to access data of any user.
def show(conn, %{'id' => id}) do
if conn.assigns.current_user.id == id do
user = Repo.get(User, id)
render(conn, 'show.json', user: user)
else
send_resp(conn, :forbidden, 'Access denied')
end
end
In the secure code example, the server first checks whether the authenticated user's 'id' matches the 'id' in the request. If it does not, the server returns a '403 Forbidden' response. This ensures that users can only access their own data.