input validation: email + password required. constructs EmailAddress vo (BadRequest on bad format). looks up user; absent or password-mismatch -> UnauthorizedException with constant 'invalid credentials' message (no enumeration leak). password verified through PasswordHasher->verify against stored hash on the User entity (no separate profile lookup -> tide keeps password on the user row). returns the User entity for the caller (typically CreateSession + AuthController). 27 tests pass.
54 lines
1.5 KiB
PHP
54 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Auth\UseCases\AuthenticateUser;
|
|
|
|
use App\Auth\PasswordHasher;
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Exceptions\UnauthorizedException;
|
|
use App\Shared\ValueObject\EmailAddress;
|
|
use App\User\User;
|
|
use App\User\UserRepository;
|
|
use InvalidArgumentException;
|
|
|
|
class AuthenticateUser
|
|
{
|
|
public function __construct(
|
|
private UserRepository $userRepo,
|
|
private PasswordHasher $hasher,
|
|
) {}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws UnauthorizedException
|
|
*/
|
|
public function execute(AuthenticateUserRequest $request): User
|
|
{
|
|
if ($request->email === null || $request->email === '') {
|
|
throw new BadRequestException('email is required');
|
|
}
|
|
if ($request->password === null || $request->password === '') {
|
|
throw new BadRequestException('password is required');
|
|
}
|
|
|
|
try {
|
|
$email = new EmailAddress($request->email);
|
|
} catch (InvalidArgumentException $exception) {
|
|
throw new BadRequestException($exception->getMessage());
|
|
}
|
|
|
|
$user = $this->userRepo->findByEmail($email);
|
|
if ($user === null) {
|
|
throw new UnauthorizedException('invalid credentials');
|
|
}
|
|
|
|
$passwordMatches = $this->hasher->verify(
|
|
$request->password,
|
|
$user->getPasswordHash(),
|
|
);
|
|
if (! $passwordMatches) {
|
|
throw new UnauthorizedException('invalid credentials');
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
}
|