Prevent unauthorized access to protected resources
defmodule User do
defstruct [:id, :data]
end
user = %User{id: 1, data: 'secret'}
def access_data(user) do
IO.puts user.data
end
This Elixir code defines a user system using a struct User, which holds an id and data. The function 'access_data' allows any user to access data without any form of authentication. Therefore, any person can create a user struct and view sensitive data.
defmodule User do
defstruct [:id, :username, :password, :data]
end
user = %User{id: 1, username: 'user1', password: 'pass1', data: 'secret'}
def login(user, username, password) do
if user.username == username and user.password == password do
{:ok, user}
else
{:error, 'Incorrect username or password.'}
end
end
def access_data(user, username, password) do
case login(user, username, password) do
{:ok, user} -> IO.puts user.data
_ -> IO.puts 'Access denied.'
end
end
The revised code introduces a secure authentication mechanism. The User struct now includes 'username' and 'password' fields. The 'login' function checks these credentials and returns a session if they are correct. The 'access_data' function now requires a successful login before accessing data, effectively preventing unauthorized access.