Passed
Pull Request — master (#5621)
by
unknown
07:07
created

SecurityController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 53
c 1
b 0
f 0
dl 0
loc 100
rs 10
wmc 15

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
C loginJson() 0 78 12
A checkSession() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
10
use Chamilo\CoreBundle\Entity\Legal;
11
use Chamilo\CoreBundle\Repository\TrackELoginRecordRepository;
12
use Chamilo\CoreBundle\ServiceHelper\UserHelper;
13
use Chamilo\CoreBundle\Settings\SettingsManager;
14
use DateTime;
15
use Doctrine\ORM\EntityManager;
16
use Doctrine\ORM\EntityManagerInterface;
17
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\Routing\Attribute\Route;
22
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
23
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
24
use Symfony\Component\Serializer\SerializerInterface;
25
use Symfony\Contracts\Translation\TranslatorInterface;
26
27
class SecurityController extends AbstractController
28
{
29
    public function __construct(
30
        private SerializerInterface $serializer,
31
        private TrackELoginRecordRepository $trackELoginRecordRepository,
32
        private EntityManagerInterface $entityManager,
33
        private SettingsManager $settingsManager,
34
        private TokenStorageInterface $tokenStorage,
35
        private AuthorizationCheckerInterface $authorizationChecker,
36
        private readonly UserHelper $userHelper,
37
    ) {}
38
39
    #[Route('/login_json', name: 'login_json', methods: ['POST'])]
40
    public function loginJson(Request $request, EntityManager $entityManager, SettingsManager $settingsManager, TokenStorageInterface $tokenStorage, TranslatorInterface $translator): Response
41
    {
42
        if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
43
            return $this->json(
44
                [
45
                    'error' => 'Invalid login request: check that the Content-Type header is "application/json".',
46
                ],
47
                400
48
            );
49
        }
50
51
        $user = $this->userHelper->getCurrent();
52
53
        if (1 !== $user->getActive()) {
54
            if (0 === $user->getActive()) {
55
                $message = $translator->trans('Account not activated.');
56
            } else {
57
                $message = $translator->trans('Invalid credentials. Please try again or contact support if you continue to experience issues.');
58
            }
59
60
            $tokenStorage->setToken(null);
61
            $request->getSession()->invalidate();
62
63
            return $this->json(['error' => $message], 401);
64
        }
65
66
        if (null !== $user->getExpirationDate() && $user->getExpirationDate() <= new DateTime()) {
67
            $message = $translator->trans('Your account has expired.');
68
69
            $tokenStorage->setToken(null);
70
            $request->getSession()->invalidate();
71
72
            return $this->json(['error' => $message], 401);
73
        }
74
75
        $extraFieldValuesRepository = $this->entityManager->getRepository(ExtraFieldValues::class);
76
        $legalTermsRepo = $this->entityManager->getRepository(Legal::class);
77
        if ($user->hasRole('ROLE_STUDENT')
78
            && 'true' === $this->settingsManager->getSetting('allow_terms_conditions')
79
            && 'login' === $this->settingsManager->getSetting('load_term_conditions_section')
80
        ) {
81
            $termAndConditionStatus = false;
82
            $extraValue = $extraFieldValuesRepository->findLegalAcceptByItemId($user->getId());
83
            if (!empty($extraValue['value'])) {
84
                $result = $extraValue['value'];
85
                $userConditions = explode(':', $result);
86
                $version = $userConditions[0];
87
                $langId = (int) $userConditions[1];
88
                $realVersion = $legalTermsRepo->getLastVersion($langId);
89
                $termAndConditionStatus = ($version >= $realVersion);
90
            }
91
92
            if (false === $termAndConditionStatus) {
93
                $tempTermAndCondition = ['user_id' => $user->getId()];
94
95
                $this->tokenStorage->setToken(null);
96
                $request->getSession()->invalidate();
97
98
                $request->getSession()->start();
99
                $request->getSession()->set('term_and_condition', $tempTermAndCondition);
100
101
                $responseData = [
102
                    'redirect' => '/main/auth/inscription.php',
103
                    'load_terms' => true,
104
                ];
105
106
                return new JsonResponse($responseData, Response::HTTP_OK);
107
            }
108
            $request->getSession()->remove('term_and_condition');
109
        }
110
111
        $data = null;
112
        if ($user) {
113
            $data = $this->serializer->serialize($user, 'jsonld', ['groups' => ['user_json:read']]);
114
        }
115
116
        return new JsonResponse($data, Response::HTTP_OK, [], true);
117
    }
118
119
    #[Route('/check-session', name: 'check_session', methods: ['GET'])]
120
    public function checkSession(): JsonResponse
121
    {
122
        if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
123
            return new JsonResponse(['isAuthenticated' => true]);
124
        }
125
126
        return new JsonResponse(['isAuthenticated' => false]);
127
    }
128
}
129