Prevent unauthorized access by implementing proper authentication
defmodule MyAppWeb.SessionController do
use MyAppWeb, :controller
def create(conn, %{"user" => user_params, "redirect" => redirect_url}) do
case MyApp.Auth.authenticate(user_params) do
{:ok, user} ->
conn
|> put_session(:user_id, user.id)
|> redirect(to: redirect_url)
_ ->
conn
end
end
end
The code provided shows a function that uses a URL parameter to determine where to redirect the user after login. An attacker could change this parameter to bypass authentication, gaining unauthorized access to the application.
defmodule MyAppWeb.SessionController do
use MyAppWeb, :controller
def create(conn, %{"user" => user_params}) do
case MyApp.Auth.authenticate(user_params) do
{:ok, user} ->
conn
|> put_session(:user_id, user.id)
|> redirect(to: "/dashboard")
_ ->
conn
end
end
end
The code now redirects to a static page instead of using a URL parameter. This ensures that the redirection process cannot be manipulated by attackers.