GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 6955d9...26a64e )
by Dmitri
02:07
created

DamaxApiAuthExtension::configureJwt()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 56
rs 8.9599
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Bundle\ApiAuthBundle\DependencyInjection;
6
7
use Damax\Bundle\ApiAuthBundle\Extractor\ChainExtractor;
8
use Damax\Bundle\ApiAuthBundle\Jwt\Claims;
9
use Damax\Bundle\ApiAuthBundle\Jwt\Claims\ClaimsCollector;
10
use Damax\Bundle\ApiAuthBundle\Jwt\Claims\OrganizationClaims;
11
use Damax\Bundle\ApiAuthBundle\Jwt\Claims\SecurityClaims;
12
use Damax\Bundle\ApiAuthBundle\Jwt\Claims\TimestampClaims;
13
use Damax\Bundle\ApiAuthBundle\Jwt\Lcobucci\Builder;
14
use Damax\Bundle\ApiAuthBundle\Jwt\Lcobucci\Parser;
15
use Damax\Bundle\ApiAuthBundle\Jwt\TokenBuilder;
16
use Damax\Bundle\ApiAuthBundle\Key\Generator\Generator;
17
use Damax\Bundle\ApiAuthBundle\Key\Storage\ChainStorage;
18
use Damax\Bundle\ApiAuthBundle\Listener\ExceptionListener;
19
use Damax\Bundle\ApiAuthBundle\Request\RequestMatcher;
20
use Damax\Bundle\ApiAuthBundle\Security\ApiKey\Authenticator as ApiKeyAuthenticator;
21
use Damax\Bundle\ApiAuthBundle\Security\ApiKey\StorageUserProvider;
22
use Damax\Bundle\ApiAuthBundle\Security\Jwt\AuthenticationHandler;
23
use Damax\Bundle\ApiAuthBundle\Security\Jwt\Authenticator as JwtAuthenticator;
24
use Lcobucci\Clock\SystemClock;
25
use Lcobucci\JWT\Configuration as JwtConfiguration;
26
use Lcobucci\JWT\Signer\Key;
27
use Symfony\Component\Config\FileLocator;
28
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
29
use Symfony\Component\DependencyInjection\ContainerBuilder;
30
use Symfony\Component\DependencyInjection\Definition;
31
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
32
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
33
34
class DamaxApiAuthExtension extends ConfigurableExtension
35
{
36
    protected function loadInternal(array $config, ContainerBuilder $container)
37
    {
38
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
39
        $loader->load('services.xml');
40
41
        if ($config['api_key']['enabled']) {
42
            $this->configureApiKey($config['api_key'], $container);
43
        }
44
45
        if ($config['jwt']['enabled']) {
46
            $this->configureJwt($config['jwt'], $container);
47
        }
48
49
        if ($config['format_exceptions']['enabled']) {
50
            $this->configureExceptions($config['format_exceptions'], $container);
51
        }
52
    }
53
54
    private function configureApiKey(array $config, ContainerBuilder $container): self
55
    {
56
        $storage = $this->configureKeyStorage($config['storage']);
57
58
        // User provider.
59
        $container
60
            ->register('damax.api_auth.api_key.user_provider', StorageUserProvider::class)
61
            ->addArgument($storage)
62
        ;
63
64
        $extractors = $this->configureExtractors($config['extractors']);
65
66
        // Authenticator.
67
        $container
68
            ->register('damax.api_auth.api_key.authenticator', ApiKeyAuthenticator::class)
69
            ->addArgument($extractors)
70
        ;
71
72
        // Key generator.
73
        $container
74
            ->register(Generator::class)
75
            ->setClass(sprintf('Damax\\Bundle\\ApiAuthBundle\\Key\\Generator\\%Generator', ucfirst($config['generator'])))
76
        ;
77
78
        return $this;
79
    }
80
81
    private function configureJwt(array $config, ContainerBuilder $container): self
82
    {
83
        $signer = $this->configureJwtSigner($config['signer']);
84
85
        $clock = new Definition(SystemClock::class);
86
87
        $configuration = (new Definition(JwtConfiguration::class))
88
            ->setFactory(JwtConfiguration::class . '::forSymmetricSigner')
89
            ->addArgument($signer)
90
            ->addArgument(new Definition(Key::class, [
91
                $config['signer']['signing_key'],
92
                $config['signer']['passphrase'],
93
            ]))
94
        ;
95
96
        if (Configuration::SIGNER_ASYMMETRIC === $config['signer']['type']) {
97
            $configuration
98
                ->setFactory(JwtConfiguration::class . '::forAsymmetricSigner')
99
                ->addArgument(new Definition(Key::class, [
100
                    $config['signer']['verification_key'],
101
                ]))
102
            ;
103
        }
104
105
        $parser = (new Definition(Parser::class))
106
            ->addArgument($configuration)
107
            ->addArgument($clock)
108
            ->addArgument($config['parser']['issuers'] ?? null)
109
            ->addArgument($config['parser']['audience'] ?? null)
110
        ;
111
112
        $claims = $this->configureJwtClaims($config['builder'], $clock, $container);
113
114
        $container
115
            ->register(TokenBuilder::class, Builder::class)
116
            ->addArgument($configuration)
117
            ->addArgument($claims)
118
        ;
119
120
        $extractors = $this->configureExtractors($config['extractors']);
121
122
        // Authenticator.
123
        $container
124
            ->register('damax.api_auth.jwt.authenticator', JwtAuthenticator::class)
125
            ->addArgument($extractors)
126
            ->addArgument($parser)
127
            ->addArgument($config['identity_claim'] ?? null)
128
        ;
129
130
        // Handler.
131
        $container
132
            ->register('damax.api_auth.jwt.handler', AuthenticationHandler::class)
133
            ->setAutowired(true)
134
        ;
135
136
        return $this;
137
    }
138
139
    private function configureExceptions(array $config, ContainerBuilder $container): self
140
    {
141
        $container
142
            ->register(ExceptionListener::class)
143
            ->setAutowired(true)
144
            ->addTag('kernel.event_listener', ['event' => 'kernel.exception', 'method' => 'onKernelException'])
145
            ->setArgument(1, new Definition(RequestMatcher::class, [$config['base_url']]))
146
        ;
147
148
        return $this;
149
    }
150
151
    private function configureJwtClaims(array $config, Definition $clock, ContainerBuilder $container): Definition
152
    {
153
        // Default claims.
154
        $container
155
            ->register(TimestampClaims::class)
156
            ->addArgument($clock)
157
            ->addArgument($config['ttl'])
158
            ->addTag('damax.api_auth.jwt_claims')
159
        ;
160
        $container
161
            ->register(OrganizationClaims::class)
162
            ->addArgument($config['issuer'] ?? null)
163
            ->addArgument($config['audience'] ?? null)
164
            ->addTag('damax.api_auth.jwt_claims')
165
        ;
166
        $container
167
            ->register(SecurityClaims::class)
168
            ->addTag('damax.api_auth.jwt_claims')
169
        ;
170
171
        $container->setAlias(Claims::class, ClaimsCollector::class);
172
173
        return $container
174
            ->register(ClaimsCollector::class)
175
            ->addArgument(new TaggedIteratorArgument('damax.api_auth.jwt_claims'))
176
        ;
177
    }
178
179
    private function configureJwtSigner(array $config): Definition
180
    {
181
        $dirs = ['HS' => 'Hmac', 'RS' => 'Rsa', 'ES' => 'Ecdsa'];
182
        $algo = $config['algorithm'];
183
184
        return new Definition('Lcobucci\\JWT\\Signer\\' . $dirs[substr($algo, 0, 2)] . '\\Sha' . substr($algo, 2));
185
    }
186
187
    private function configureExtractors(array $config): Definition
188
    {
189
        $extractors = [];
190
191
        foreach ($config as $item) {
192
            $className = sprintf('Damax\\Bundle\\ApiAuthBundle\\Extractor\\%sExtractor', ucfirst($item['type']));
193
194
            $extractors[] = (new Definition($className))
195
                ->setArgument(0, $item['name'])
196
                ->setArgument(1, $item['prefix'] ?? null)
197
            ;
198
        }
199
200
        return new Definition(ChainExtractor::class, [$extractors]);
201
    }
202
203
    private function configureKeyStorage(array $config): Definition
204
    {
205
        $drivers = [];
206
207
        foreach ($config as $item) {
208
            $className = sprintf('Damax\\Bundle\\ApiAuthBundle\\Key\\Storage\\%sStorage', ucfirst($item['type']));
209
210
            $drivers[] = $driver = new Definition($className);
211
212
            if (Configuration::STORAGE_FIXED === $item['type']) {
213
                $driver->addArgument($item['tokens']);
214
            }
215
        }
216
217
        return new Definition(ChainStorage::class, [$drivers]);
218
    }
219
}
220