Search⌘ K
AI Features

Challenge 1: Eliminate Exceptions Using the Either Monad

Explore how to refactor PHP authentication logic to eliminate exceptions by using the Either monad. Learn to handle invalid usernames and passwords with clear error messages and enhance user data by adding roles and removing sensitive information.

A code snippet is given below. It has an authenticateUser function that authenticates the provided username and password with the stored username and password. If ...

PHP
<?php
const USER_DATA = [
'password' => '$2y$10$gaGFDPMaVRS61ONjnkGQAODo64voLOUJK1AlokiZY2HY3QiPE4zHq',
'username' => 'kelly92',
'admin' => false,
]; // valid password is trap_223
function authenticateUser(string $username, string $password): array
{
if ($username !== USER_DATA['username']) {
throw new Exception('Sorry, your username is invalid');
}
if (!password_verify($password, USER_DATA['password'])) {
throw new Exception('Sorry, your password is invalid');
}
return USER_DATA;
}
authenticateUser('Some_User_Name','Some_Password');
?>

Problem

...