Failed Conditions
Push — issue#838 ( 2929c5 )
by Guilherme
06:57
created

ClientManager::getClientById()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 5
nop 1
dl 0
loc 26
ccs 17
cts 17
cp 1
crap 4
rs 9.7
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\OpenIDBundle\Manager;
12
13
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
14
use Doctrine\ORM\EntityManagerInterface;
15
use LoginCidadao\CoreBundle\Entity\PersonRepository;
16
use LoginCidadao\CoreBundle\Event\GetClientEvent;
17
use LoginCidadao\CoreBundle\Event\LoginCidadaoCoreEvents;
18
use LoginCidadao\CoreBundle\Model\PersonInterface;
19
use LoginCidadao\OAuthBundle\Model\ClientInterface;
20
use LoginCidadao\OpenIDBundle\Entity\ClientMetadata;
21
use LoginCidadao\OpenIDBundle\Model\CreateClientRequest;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
24
class ClientManager
25
{
26
    /** @var EventDispatcherInterface */
27
    private $dispatcher;
28
29
    /** @var EntityManagerInterface */
30
    private $em;
31
32
    /** @var PersonRepository */
33
    private $personRepository;
34
35
    /** @var string */
36
    private $publicScopes;
37
38
    /**
39
     * ClientManager constructor.
40
     * @param EntityManagerInterface $em
41
     * @param EventDispatcherInterface $dispatcher
42
     * @param PersonRepository $personRepository
43
     * @param $publicScopes
44
     */
45 7
    public function __construct(
46
        EntityManagerInterface $em,
47
        EventDispatcherInterface $dispatcher,
48
        PersonRepository $personRepository,
49
        $publicScopes
50
    ) {
51 7
        $this->em = $em;
52 7
        $this->dispatcher = $dispatcher;
53 7
        $this->personRepository = $personRepository;
54 7
        $this->publicScopes = $publicScopes;
55 7
    }
56
57
    /**
58
     * @param mixed $id
59
     * @return ClientInterface|null
60
     */
61 3
    public function getClientById($id)
62
    {
63 3
        if ($id === null) {
64 1
            return null;
65
        }
66 2
        $randomId = null;
67 2
        if (strstr($id, '_') !== false) {
68 1
            $parts = explode('_', $id);
69 1
            $id = $parts[0];
70 1
            $randomId = $parts[1];
71
        }
72
73 2
        $repo = $this->em->getRepository('LoginCidadaoOAuthBundle:Client');
74
75 2
        if ($randomId) {
76 1
            $client = $repo->findOneBy([
77 1
                'id' => $id,
78 1
                'randomId' => $randomId,
79
            ]);
80
        } else {
81 1
            $client = $repo->find($id);
82
        }
83 2
        $event = new GetClientEvent($client);
84 2
        $this->dispatcher->dispatch(LoginCidadaoCoreEvents::GET_CLIENT, $event);
85
86 2
        return $event->getClient();
87
    }
88
89
    /**
90
     * @param ClientMetadata $data
91
     * @return ClientInterface
92
     * @throws UniqueConstraintViolationException
93
     */
94 3
    public function register(ClientMetadata $data)
95
    {
96 3
        $client = $data->getClient();
97
98 3
        $this->em->persist($client);
99
100 3
        $data->setClient($client);
101 3
        $this->em->persist($data);
102
103 3
        $this->em->flush();
104
105 3
        return $client;
106
    }
107
108 3
    private function sanitizeClient(ClientInterface $client)
109
    {
110 3
        if ($client->getName() === null) {
111 3
            $firstUrl = $client->getRedirectUris()
112 1
                ? parse_url($client->getRedirectUris()[0], PHP_URL_HOST)
113 3
                : 'Unamed Client';
114 3
            $client->setName($firstUrl);
115
        }
116 3
        if ($client->getDescription() === null) {
117 3
            $client->setDescription('');
118
        }
119 3
        if ($client->getTermsOfUseUrl() === null) {
120 3
            $client->setTermsOfUseUrl('');
121
        }
122 3
        if ($client->getSiteUrl() === null) {
123 3
            $client->setSiteUrl('');
124
        }
125
126 3
        return $client;
127
    }
128
129 3
    public function populateNewMetadata(ClientMetadata $data)
130
    {
131 3
        $this->initializeRegistrationAccessToken($data);
132
133 3
        if ($data->getClient() === null) {
134 2
            $client = $data->toClient();
135
        } else {
136 1
            $client = $data->getClient();
137
        }
138
139 3
        $client = $this->sanitizeClient($client);
140 3
        if ($data->getClientName() === null) {
141 3
            $data->setClientName($client->getName());
142
        }
143
144 3
        if (count($data->getContacts()) > 0) {
145
            /** @var PersonInterface[] $owners */
146 1
            $owners = $this->personRepository->findBy([
147 1
                'email' => $data->getContacts(),
148
            ]);
149
150 1
            foreach ($owners as $person) {
151 1
                if (!$person->getEmailConfirmedAt() instanceof \DateTime) {
152
                    // Email is not verified. Skipping...
153 1
                    continue;
154
                }
155 1
                $client->getOwners()->add($person);
156
            }
157
        }
158
159 3
        $publicScopes = explode(' ', $this->publicScopes);
160 3
        $client->setAllowedScopes($publicScopes);
161
162 3
        $data->setClient($client);
163
164 3
        return $data;
165
    }
166
167 3
    private function initializeRegistrationAccessToken(ClientMetadata &$data)
168
    {
169 3
        if (null === $data->getRegistrationAccessToken()) {
170 3
            $registrationAccessToken = bin2hex(random_bytes(120));
171 3
            $data->setRegistrationAccessToken($registrationAccessToken);
172
        }
173 3
    }
174
175
    public function createClientMetadata(CreateClientRequest $createClientRequest): ClientMetadata
176
    {
177
        $metadata = (new ClientMetadata())
178
            ->setRedirectUris($createClientRequest->redirect_uris)
179
            ->setResponseTypes($createClientRequest->response_types)
180
            ->setGrantTypes($createClientRequest->grant_types)
181
            ->setApplicationType($createClientRequest->application_type)
182
            ->setContacts($createClientRequest->contacts)
183
            ->setClientName($createClientRequest->client_name)
184
            ->setLogoUri($createClientRequest->logo_uri)
185
            ->setClientUri($createClientRequest->client_uri)
186
            ->setPolicyUri($createClientRequest->policy_uri)
187
            ->setTosUri($createClientRequest->tos_uri)
188
            ->setJwksUri($createClientRequest->jwks_uri)
189
            ->setJwks($createClientRequest->jwks)
190
            ->setSectorIdentifierUri($createClientRequest->sector_identifier_uri)
191
            ->setSubjectType($createClientRequest->subject_type)
192
            ->setIdTokenSignedResponseAlg($createClientRequest->id_token_signed_response_alg)
193
            ->setIdTokenEncryptedResponseAlg($createClientRequest->id_token_encrypted_response_alg)
194
            ->setIdTokenEncryptedResponseEnc($createClientRequest->id_token_encrypted_response_enc)
195
            ->setUserinfoSignedResponseAlg($createClientRequest->userinfo_signed_response_alg)
196
            ->setUserinfoEncryptedResponseAlg($createClientRequest->userinfo_encrypted_response_alg)
197
            ->setUserinfoEncryptedResponseEnc($createClientRequest->userinfo_encrypted_response_enc)
198
            ->setRequestObjectSigningAlg($createClientRequest->request_object_signing_alg)
199
            ->setRequestObjectEncryptionAlg($createClientRequest->request_object_encryption_alg)
200
            ->setRequestObjectEncryptionEnc($createClientRequest->request_object_encryption_enc)
201
            ->setTokenEndpointAuthMethod($createClientRequest->token_endpoint_auth_method)
202
            ->setTokenEndpointAuthSigningAlg($createClientRequest->token_endpoint_auth_signing_alg)
203
            ->setDefaultMaxAge($createClientRequest->default_max_age)
204
            ->setRequireAuthTime($createClientRequest->require_auth_time)
205
            ->setDefaultAcrValues($createClientRequest->default_acr_values)
206
            ->setInitiateLoginUri($createClientRequest->initiate_login_uri)
207
            ->setRequestUris($createClientRequest->request_uris)
208
            ->setRegistrationAccessToken($createClientRequest->registration_access_token)
209
            ->setPostLogoutRedirectUris($createClientRequest->post_logout_redirect_uris);
210
211
        $metadata = $this->populateNewMetadata($metadata);
212
213
        $this->em->persist($metadata);
214
        $this->em->flush();
215
216
        return $metadata;
217
    }
218
}
219