Passed
Pull Request — master (#7302)
by Angel Fernando Quiroz
09:53
created

AbstractScimController   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 51
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A authenticateRequest() 0 21 4
A getAndValidateJson() 0 15 3
A __construct() 0 5 1
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Controller\Scim;
8
9
use Chamilo\CoreBundle\Exception\ScimException;
10
use Chamilo\CoreBundle\Helpers\AccessUrlHelper;
11
use Chamilo\CoreBundle\Helpers\ScimHelper;
12
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
use Symfony\Contracts\Translation\TranslatorInterface;
16
17
use const JSON_ERROR_NONE;
18
19
abstract class AbstractScimController extends AbstractController
20
{
21
    public const SCIM_CONTENT_TYPE = 'application/scim+json';
22
23
    public function __construct(
24
        protected readonly TranslatorInterface $translator,
25
        protected readonly ScimHelper $scimHelper,
26
        protected readonly AccessUrlHelper $accessUrlHelper,
27
    ) {}
28
29
    protected function getAndValidateJson(Request $request): array
30
    {
31
        $content = $request->getContent();
32
33
        if (empty($content)) {
34
            throw new ScimException('No content');
35
        }
36
37
        $data = json_decode($content, true);
38
39
        if (JSON_ERROR_NONE !== json_last_error()) {
40
            throw new ScimException('Invalid JSON: '.json_last_error_msg());
41
        }
42
43
        return $data;
44
    }
45
46
    /**
47
     * @throws ScimException
48
     */
49
    protected function authenticateRequest(Request $request): void
50
    {
51
        $authHeader = $request->headers->get('Authorization');
52
53
        $invalidTokenException = new ScimException(
54
            $this->translator->trans('Invalid Token'),
55
            Response::HTTP_UNAUTHORIZED
56
        );
57
58
        if (!$authHeader) {
59
            throw $invalidTokenException;
60
        }
61
62
        if (!preg_match('/^Bearer\s+(\S+)/i', $authHeader, $matches)) {
63
            throw $invalidTokenException;
64
        }
65
66
        $providedToken = $matches[1];
67
68
        if (!hash_equals($this->getParameter('scim_token'), $providedToken)) {
69
            throw $invalidTokenException;
70
        }
71
    }
72
}
73