Passed
Pull Request — master (#6100)
by Angel Fernando Quiroz
11:43
created

AuthenticationConfigHelper::getEnabledProviders()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
nc 3
nop 1
dl 0
loc 17
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\ServiceHelper;
8
9
use Chamilo\CoreBundle\Entity\AccessUrl;
10
use Chamilo\CoreBundle\Entity\UserAuthSource;
11
use InvalidArgumentException;
12
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
13
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
14
15
use function Symfony\Component\String\u;
0 ignored issues
show
introduced by
The function Symfony\Component\String\u was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
16
17
readonly class AuthenticationConfigHelper
18
{
19
    public function __construct(
20
        private ParameterBagInterface $parameterBag,
21
        private AccessUrlHelper $urlHelper,
22
        private UrlGeneratorInterface $urlGenerator,
23
    ) {}
24
25
    public function getProviderConfig(string $providerName, ?AccessUrl $url = null): array
26
    {
27
        $providers = $this->getOAuthProvidersForUrl($url);
28
29
        if ([] === $providers) {
30
            return [];
31
        }
32
33
        if (!isset($providers[$providerName])) {
34
            throw new InvalidArgumentException('Invalid authentication provider for access URL');
35
        }
36
37
        return $providers[$providerName];
38
    }
39
40
    public function isOAuth2ProviderEnabled(string $methodName, ?AccessUrl $url = null): bool
41
    {
42
        $configParams = $this->getProviderConfig($methodName, $url);
43
44
        return $configParams['enabled'] ?? false;
45
    }
46
47
    public function getEnabledOAuthProviders(?AccessUrl $url = null): array
48
    {
49
        $urlProviders = $this->getOAuthProvidersForUrl($url);
50
51
        $enabledProviders = [];
52
53
        foreach ($urlProviders as $providerName => $providerParams) {
54
            if ($providerParams['enabled'] ?? false) {
55
                $enabledProviders[] = [
56
                    'name' => $providerName,
57
                    'title' => $providerParams['title'] ?? u($providerName)->title(),
0 ignored issues
show
Bug introduced by
The function u was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
                    'title' => $providerParams['title'] ?? /** @scrutinizer ignore-call */ u($providerName)->title(),
Loading history...
58
                    'url' => $this->urlGenerator->generate(\sprintf('chamilo.oauth2_%s_start', $providerName)),
59
                ];
60
            }
61
        }
62
63
        return $enabledProviders;
64
    }
65
66
    public function getAuthSources(?AccessUrl $url)
67
    {
68
        $urlId = $url ?: $this->urlHelper->getCurrent();
69
70
        $authentication = $this->parameterBag->has('authentication')
71
            ? $this->parameterBag->get('authentication')
72
            : [];
73
74
        if (isset($authentication[$urlId->getId()])) {
0 ignored issues
show
Bug introduced by
The method getId() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

74
        if (isset($authentication[$urlId->/** @scrutinizer ignore-call */ getId()])) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
75
            return $authentication[$urlId->getId()];
76
        }
77
78
        if (isset($authentication['default'])) {
79
            return $authentication['default'];
80
        }
81
82
        return [];
83
    }
84
85
    /**
86
     * @return array<string, array<string, mixed>>
87
     */
88
    private function getOAuthProvidersForUrl(?AccessUrl $url): array
89
    {
90
        $authentication = $this->getAuthSources($url);
91
92
        if (isset($authentication['oauth2'])) {
93
            return $authentication['oauth2'];
94
        }
95
96
        return [];
97
    }
98
99
    /**
100
     * @return array<int, string>
101
     */
102
    public function getAuthSourceAuthentications(?AccessUrl $url): array
103
    {
104
        $authSources = $this->getAuthSources($url);
105
106
        return [UserAuthSource::PLATFORM, ...array_keys($authSources)];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array(Chamilo\Cor...ray_keys($authSources)) returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
107
    }
108
109
    public function getOAuthProviderOptions(string $providerType, array $config): array
110
    {
111
        $defaults = match ($providerType) {
112
            'generic' => [
113
                'clientId' => $config['client_id'],
114
                'clientSecret' => $config['client_secret'],
115
                'urlAuthorize' => $config['urlAuthorize'],
116
                'urlAccessToken' => $config['urlAccessToken'],
117
                'urlResourceOwnerDetails' => $config['urlResourceOwnerDetails'],
118
                'accessTokenMethod' => $config['accessTokenMethod'] ?? null,
119
                'accessTokenResourceOwnerId' => $config['accessTokenResourceOwnerId'] ?? null,
120
                'scopeSeparator' => $config['scopeSeparator'] ?? null,
121
                'responseError' => $config['responseError'] ?? null,
122
                'responseCode' => $config['responseCode'] ?? null,
123
                'responseResourceOwnerId' => $config['responseResourceOwnerId'] ?? null,
124
                'scopes' => $config['scopes'] ?? null,
125
                'pkceMethod' => $config['pkceMethod'] ?? null,
126
            ],
127
            'facebook' => [
128
                'clientId' => $config['client_id'],
129
                'clientSecret' => $config['client_secret'],
130
                'graphApiVersion' => $config['graph_api_version'] ?? null,
131
            ],
132
            'keycloak' => [
133
                'clientId' => $config['client_id'],
134
                'clientSecret' => $config['client_secret'],
135
                'authServerUrl' => $config['auth_server_url'],
136
                'realm' => $config['realm'],
137
                'version' => $config['version'] ?? null,
138
                'encryptionAlgorithm' => $config['encryption_algorithm'] ?? null,
139
                'encryptionKeyPath' => $config['encryption_key_path'] ?? null,
140
                'encryptionKey' => $config['encryption_key'] ?? null,
141
            ],
142
            'azure' => [
143
                'clientId' => $config['client_id'],
144
                'clientSecret' => $config['client_secret'],
145
                'clientCertificatePrivateKey' => $config['client_certificate_private_key'] ?? null,
146
                'clientCertificateThumbprint' => $config['client_certificate_thumbprint'] ?? null,
147
                'urlLogin' => $config['url_login'] ?? null,
148
                'pathAuthorize' => $config['path_authorize'] ?? null,
149
                'pathToken' => $config['path_token'] ?? null,
150
                'scope' => $config['scope'] ?? null,
151
                'tenant' => $config['tenant'] ?? null,
152
                'urlAPI' => $config['url_api'] ?? null,
153
                'resource' => $config['resource'] ?? null,
154
                'API_VERSION' => $config['api_version'] ?? null,
155
                'authWithResource' => $config['auth_with_resource'] ?? null,
156
                'defaultEndPointVersion' => $config['default_end_point_version'] ?? null,
157
            ],
158
        };
159
160
        return array_filter($defaults, fn ($value) => null !== $value);
161
    }
162
}
163