To prevent unauthorized account access due to weak passwords, which can be easily compromised by brute force or dictionary attacks.
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"password" => password}) do
hashed_password = Comeonin.Bcrypt.hashpwsalt(password)
# ... rest of the code
end
end
In the insecure code, the application accepts any password provided by the user, without any strength checks. This can lead to weak passwords that can be easily cracked by an attacker.
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"password" => password}) do
if strong_password?(password) do
hashed_password = Comeonin.Bcrypt.hashpwsalt(password)
# ... rest of the code
else
# Respond with an error
end
end
defp strong_password?(password) do
String.length(password) >= 12 && Regex.match?(~r/[A-Z]/, password) && Regex.match?(~r/[a-z]/, password) && Regex.match?(~r/[0-9]/, password) && Regex.match?(~r/[!@#\$%\^&]/, password)
end
end
In the secure code, the application checks the strength of the password before accepting it. This prevents users from creating accounts with weak passwords.