implement authenticate user use case
Green phase: AuthenticateUser validates credentials, throws BadRequestException for empty fields, UnauthorizedException for unknown email or wrong password.
This commit is contained in:
parent
57c75f64c4
commit
b14cd565bb
2 changed files with 62 additions and 0 deletions
|
|
@ -0,0 +1,51 @@
|
||||||
|
<?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;
|
||||||
|
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = $this->userRepo->findByEmail(
|
||||||
|
new EmailAddress($request->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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Auth\UseCases\AuthenticateUser;
|
||||||
|
|
||||||
|
class AuthenticateUserRequest
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public ?string $email,
|
||||||
|
public ?string $password,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue