48 lines
1.2 KiB
PHP
48 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\User\UseCases;
|
|
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Exceptions\UnauthorizedException;
|
|
use App\User\User;
|
|
use App\User\UserRepository;
|
|
use App\ValueObjects\EmailAddress;
|
|
|
|
class AuthenticateUser
|
|
{
|
|
public function __construct(
|
|
private UserRepository $userRepo,
|
|
) {}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws UnauthorizedException
|
|
*/
|
|
public function execute(AuthenticateUserRequest $request): User
|
|
{
|
|
if ($request->email === null) {
|
|
throw new BadRequestException('email is required');
|
|
}
|
|
|
|
if ($request->password === null) {
|
|
throw new BadRequestException('password is required');
|
|
}
|
|
|
|
$user = $this->userRepo->findByEmail(
|
|
new EmailAddress($request->email)
|
|
);
|
|
if ($user === null) {
|
|
throw new UnauthorizedException('invalid credentials');
|
|
}
|
|
|
|
$passwordMatches = password_verify(
|
|
$request->password,
|
|
$user->getPasswordHash()
|
|
);
|
|
if (!$passwordMatches) {
|
|
throw new UnauthorizedException('invalid credentials');
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
}
|