<repo_name>Avezen/telemedi-test<file_sep>/src/Controller/MainPageController.php
<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\Login;
use App\Form\RegisterUser;
use App\Utils\UserService;
use DateTime;
use Doctrine\DBAL\Types\DateType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;


class MainPageController extends AbstractController
{
    /**
     * @Route("/", name="main_page")
     */
    public function mainPage(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $register = new RegisterUser();
        $login = new Login();
        $userService = new UserService($em);
        $session = new Session();
        $session->clear();

        $loginForm = $this->get('form.factory')
            ->createNamedBuilder('login_form', FormType::class, $login)
            ->add('login', TextType::class)
            ->add('password', PasswordType::class)
            ->add('logIn', SubmitType::class, array('label' => 'Log In'))
            ->getForm();
        $loginForm->handleRequest($request);


        $registerForm = $this->get('form.factory')
            ->createNamedBuilder('register_form', FormType::class, $register)
            ->add('login', TextType::class)
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
            ->add('passwordRepeated', PasswordType::class)
            ->add('register', SubmitType::class, array('label' => 'Register!'))
            ->getForm();
        $registerForm->handleRequest($request);


        if (($registerForm->isSubmitted() && $registerForm->isValid()) || ($loginForm->isSubmitted() && $loginForm->isValid())) {

            if ($request->request->get('register_form')) {
                $register = $registerForm->getData();

                $isRegisteredSuccessfully = $userService->registerUser($register);

                if($isRegisteredSuccessfully === true){
                    return $this->render('base.html.twig', array(
                        'registerForm' => $registerForm->createView(),
                        'loginForm' => $loginForm->createView(),
                        'message'=>"Account successfully created - call admin to activate it",
                    ));
                }else{
                    return $this->render('base.html.twig', array(
                        'registerForm' => $registerForm->createView(),
                        'loginForm' => $loginForm->createView(),
                        'message'=>$isRegisteredSuccessfully,
                    ));
                }
            }else if ($request->request->get('login_form')) {
                $loggedUser = $userService->loginUser($login);

                if($loggedUser === 0){
                    return $this->render('base.html.twig', array(
                        'registerForm' => $registerForm->createView(),
                        'loginForm' => $loginForm->createView(),
                        'message'=>"Account not activated",
                    ));
                }else if ($loggedUser !== false){
                    $session->set('loggedUser', $login->getLogin());
                    $session->set('userRoles', unserialize($loggedUser['0']['roles']));

                    return $this->redirectToRoute('user_page');
                }else{
                    return $this->render('base.html.twig', array(
                        'registerForm' => $registerForm->createView(),
                        'loginForm' => $loginForm->createView(),
                        'message'=>"Wrong login or password",
                    ));
                }
            }
        }

        return $this->render('base.html.twig', array(
            'registerForm' => $registerForm->createView(),
            'loginForm' => $loginForm->createView(),
        ));
    }

    /**
     * @Route("/user", name="user_page")
     */
    public function users()
    {
        $session = new Session();
        $loggedUser = $session->get("loggedUser");

        if(!$loggedUser)
            return $this->redirectToRoute("main_page");

        $userRoles = $session->get("userRoles");

        return $this->render('user/index.html.twig', array("user"=>$loggedUser, "roles"=>$userRoles));
    }
}
<file_sep>/src/Controller/UserController.php
<?php

namespace App\Controller;

use App\Entity\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class UserController extends Controller
{

    /**
     * @Route("/getallusers", name="get_all_users")
     */
    public function getAllUsers()
    {
        $session = new Session();

        if($session->get('userRoles')[0] === "ROLE_ADMIN") {
            $em = $this->getDoctrine()->getManager();

            $users = $em->getRepository(User::class)->createQueryBuilder('u')
                ->getQuery()
                ->getArrayResult();

            if(count($users) !== 0) {
                for ($i = 0; $i < count($users); $i++) {
                    $users[$i]['registrationDate'] = $users[$i]['registrationDate']->format('Y-m-d');
                }
                return new JsonResponse($users);
            }
            return new JsonResponse(array("response"=>"No user exists"));
        }

        return new JsonResponse(array("response"=>"Access denied"));
    }

    /**
     * @Route("/deleteuser", name="delete_user")
     */
    public function deleteUser(Request $request)
    {
        $session = new Session();
        $id = json_decode($request->getContent(), true);

        if($session->get('userRoles')[0] === "ROLE_ADMIN"){
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository(User::class)->find($id);

            if($user !== null){
                $em->remove($user);
                $em->flush();

                return new JsonResponse(array("response"=>"User deleted successfully"));
            }
            return new JsonResponse(array("response"=>"No user with id: ".$id));
        }
        return new JsonResponse(array("response"=>"Access denied"));
    }

    /**
     * @Route("/changeuserstatus", name="change_user_status")
     */
    public function changeUserStatus(Request $request)
    {
        $session = new Session();
        $id = json_decode($request->getContent(), true);

        if($session->get('userRoles')[0] === "ROLE_ADMIN"){
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository(User::class)->find($id);

            if($user !== null){
                if($user->getIsActive()===1){
                    $user->setIsActive(0);
                }else {
                    $user->setIsActive(1);
                }

                $em->persist($user);
                $em->flush();

                return new JsonResponse(array("response"=>"User status changed successfully"));
            }
            return new JsonResponse(array("response"=>"No user with id: ".$id));
        }
        return new JsonResponse(array("response"=>"Access denied"));
    }
}
<file_sep>/src/Utils/UserService.php
<?php

namespace App\Utils;


use App\Entity\User;
use DateTime;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\ORMException;
use Symfony\Component\HttpFoundation\Session\Session;

class UserService{

    protected $em;

    public function __construct(ObjectManager $em)
    {
        $this->em = $em;
    }

    public function registerUser($registerData){
        $now = new \DateTime(date("Y-m-d"));

        $doUserExist = $this->em->getRepository(User::class)->findBy(array("login"=>$registerData->getLogin()));
        if($doUserExist !== []){
            return "Account with this login already exists";
        }
        if(strlen($registerData->getLogin()) > 5 || strlen($registerData->getPassword()) > 5) {
            if ($registerData->getPassword() === $registerData->getPasswordRepeated()) {
                $user = new User();
                $roles = array("0"=>"ROLE_USER");
                $user->setLogin($registerData->getLogin());
                $user->setPassword(password_hash($registerData->getPassword(), PASSWORD_BCRYPT, array('cost' => 11)));
                $user->setUsername($registerData->getUsername());
                $user->setRoles(serialize($roles));
                $user->setRegistrationDate($now);
                $user->setIsActive(0);
                $this->em->persist($user);
                $this->em->flush();

                return true;
            }

            return "Passwords are not the same";
        }
        return "Password or login are too short. They need to be longer than 5";
    }

    public function loginUser($loginData){
        $loggedUser = $this->em->getRepository(User::class);

        $loggedUser = $loggedUser->createQueryBuilder('u')
            ->andWhere('u.login = :login')
            ->setParameter('login', $loginData->getLogin())
            ->getQuery()
            ->getArrayResult();

        if($loggedUser !== []){
            if(password_verify($loginData->getPassword(), $loggedUser[0]['password'])) {
                if ($loggedUser[0]['isActive'] === 0)
                    return 0;

                return $loggedUser;
            }
        }
        return false;
    }
}
<file_sep>/src/Form/RegisterUser.php
<?php

namespace App\Form;


class RegisterUser
{

    private $login;
    private $password;
    private $passwordRepeated;
    private $roles;
    private $username;
    private $date;
    private $isActive;


    public function getLogin(): ?string
    {
        return $this->login;
    }

    public function setLogin(string $login): self
    {
        $this->login = $login;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getPasswordRepeated(): ?string
    {
        return $this->passwordRepeated;
    }

    public function setPasswordRepeated(string $passwordRepeated): self
    {
        $this->passwordRepeated = $passwordRepeated;

        return $this;
    }

    public function getRoles(): ?string
    {
        return $this->roles;
    }

    public function setRoles(string $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    public function getDate(): ?\DateTime
    {
        return $this->date;
    }

    public function setDate(\DateTime $date): self
    {
        $this->date = $date;

        return $this;
    }
    public function getIsActive(): ?int
    {
        return $this->isActive;
    }

    public function setIsActive(int $isActive): self
    {
        $this->isActive = $isActive;

        return $this;
    }

}
