Passed
Pull Request — master (#7302)
by Angel Fernando Quiroz
10:36
created

AbstractScimController   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A authenticateRequest() 0 21 4
A getAndValidateJson() 0 15 3
A __construct() 0 7 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\DependencyInjection\Attribute\Autowire;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Contracts\Translation\TranslatorInterface;
17
18
use const JSON_ERROR_NONE;
19
20
abstract class AbstractScimController extends AbstractController
21
{
22
    public const SCIM_CONTENT_TYPE = 'application/scim+json';
23
24
    public function __construct(
25
        #[Autowire(env: 'SCIM_TOKEN')]
26
        private readonly string $scimToken,
27
        protected readonly TranslatorInterface $translator,
28
        protected readonly ScimHelper $scimHelper,
29
        protected readonly AccessUrlHelper $accessUrlHelper,
30
    ) {}
31
32
    protected function getAndValidateJson(Request $request): array
33
    {
34
        $content = $request->getContent();
35
36
        if (empty($content)) {
37
            throw new ScimException('No content');
38
        }
39
40
        $data = json_decode($content, true);
41
42
        if (JSON_ERROR_NONE !== json_last_error()) {
43
            throw new ScimException('Invalid JSON: '.json_last_error_msg());
44
        }
45
46
        return $data;
47
    }
48
49
    /**
50
     * @throws ScimException
51
     */
52
    public function authenticateRequest(Request $request): void
53
    {
54
        $authHeader = $request->headers->get('Authorization');
55
56
        $invalidTokenException = new ScimException(
57
            $this->translator->trans('Invalid Token'),
58
            Response::HTTP_UNAUTHORIZED
59
        );
60
61
        if (!$authHeader) {
62
            throw $invalidTokenException;
63
        }
64
65
        if (!preg_match('/^Bearer\s+(\S+)/i', $authHeader, $matches)) {
66
            throw $invalidTokenException;
67
        }
68
69
        $providedToken = $matches[1];
70
71
        if (!hash_equals($this->scimToken, $providedToken)) {
72
            throw $invalidTokenException;
73
        }
74
    }
75
}
76