Add the Login action.

This commit is contained in:
Dave Smith-Hayes 2024-06-16 21:26:10 -04:00
parent 079bcb0f06
commit 2b75ea2dea

View File

@ -0,0 +1,40 @@
<?php
namespace Slovocast\Controller\User;
use Slovocast\Controller\Controller;
use Slovocast\Domain\Repository\UserRepositoryInterface;
use Slovocast\Infrastructure\User\UserAuthorizationInterface;
use Slovocast\Exception\EntityNotFoundException;
use Psr\Http\Message\ResponseInterface as Response;
use Odan\Session\SessionInterface;
class LoginUserAction extends Controller
{
public function __construct(
private UserAuthorizationInterface $auth,
private UserRepositoryInterface $userRepository,
private SessionInterface $session
) { }
public function handle(): Response
{
$credentials = $this->request->getParsedBody();
try {
$user = $this->userRepository->getFromEmail($credentials['email']);
} catch (EntityNotFoundException $e) {
$this->session->getFlash()->add('error', "Unable to login user.");
return $this->response->withStatus(400);
}
if (!$this->auth->verify($credentials['password'], $user->getPassword())) {
$this->session->getFlash()->add('error', 'Unable to login.');
return $this->response->withStatus(400);
}
// start the session
$this->session->set('user', [ 'id' => $user->getId() ]);
return $this->response;
}
}