From fe5dea35d432d9de8897dc4b3acf29db1d49b486 Mon Sep 17 00:00:00 2001
From: Moreau Elise <moreau.elise13@gmail.com>
Date: Sun, 4 Oct 2020 18:01:06 +0200
Subject: [PATCH] add Log in action which use Session variables

---
 .../Actions/User/LogInUserAction.php          | 50 +++++++++++++++++++
 1 file changed, 50 insertions(+)
 create mode 100644 src/Application/Actions/User/LogInUserAction.php

diff --git a/src/Application/Actions/User/LogInUserAction.php b/src/Application/Actions/User/LogInUserAction.php
new file mode 100644
index 0000000..63e2e73
--- /dev/null
+++ b/src/Application/Actions/User/LogInUserAction.php
@@ -0,0 +1,50 @@
+<?php
+declare(strict_types=1);
+
+namespace App\Application\Actions\User;
+
+use Psr\Http\Message\ResponseInterface as Response;
+use App\Domain\User\UserNotFoundException;
+
+class LogInUserAction extends UserAction
+{
+    /**
+     * {@inheritdoc}
+     */
+    protected function action(): Response
+    {
+        $parsedRequestBody = (array)$this->request->getParsedBody();
+        $username = $this->checkvalue($parsedRequestBody['username']);
+        $password = $this->checkvalue($parsedRequestBody['password']);
+
+        $user = $this->userRepository->findOneBy(array('username' => $username));
+
+        if (!isset($user)) {
+            throw new UserNotFoundException();
+        }
+
+        if (!password_verify($password, $user->getPassword())) {
+            $_SESSION['message'] = 'Username or password unknown.';
+            return $this->twig->render($this->response, "/user/log_in.twig", ["formstatus" => "error", "session" => $_SESSION]);
+        }
+
+        $_SESSION['userId'] = $user->getId();
+        $_SESSION['logged'] = true;
+
+        return $this->response
+            ->withHeader('Location', '/account')
+            ->withStatus(302);
+    }
+
+    /**
+     * Remove html chars
+     * @return string
+     */
+    protected function checkValue($value): string
+    {
+        $value = strip_tags($value);
+        $value = htmlspecialchars_decode($value);
+        return $value;
+    }
+
+}
-- 
GitLab