Completed
Push — master ( 6a0ab6...96f47f )
by Mārtiņš
02:11
created

Identification::retrieveEmailIdenityByIdentifier()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 16
cp 0
rs 9.3142
c 0
b 0
f 0
cc 2
eloc 11
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Palladium\Service;
4
5
/**
6
 * Retrieval and handling of identities for registered users
7
 */
8
9
use RuntimeException;
10
11
use Palladium\Component\MapperFactory;
12
use Palladium\Mapper\Authentication as Mapper;
13
use Palladium\Entity\Authentication as Entity;
14
15
use Palladium\Exception\IdentityDuplicated;
16
use Palladium\Exception\IdentityNotFound;
17
use Palladium\Exception\EmailNotFound;
18
use Palladium\Exception\PasswordNotMatch;
19
use Palladium\Exception\CompromisedCookie;
20
use Palladium\Exception\DenialOfServiceAttempt;
21
use Palladium\Exception\IdentityExpired;
22
use Palladium\Exception\Community\UserNotFound;
23
24
25
class Identification extends Locator
26
{
27
28
    private $currentCookie;
29
30
31
    public function loginWithPassword($identifier, $password)
32
    {
33
        $identity = $this->retrieveEmailIdenityByIdentifier($identifier);
34
35
        if ($identity->getId() === null) {
36
            // hardening against timeing based side-channel attacks
37
            $identity->setPassword('');
38
39
            $this->logger->warning('acount not found', [
40
                'input' => [
41
                    'identifier' => $identifier,
42
                    'key' => md5($password),
43
                ],
44
                'account' => [
45
                    'user' => null,
46
                    'identity' => null,
47
                ],
48
            ]);
49
50
            throw new EmailNotFound;
51
        }
52
53 View Code Duplication
        if ($identity->matchKey($password) === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
            $this->logger->warning('wrong password', [
55
                'input' => [
56
                    'identifier' => $identifier,
57
                    'key' => md5($password),
58
                ],
59
                'account' => [
60
                    'user' => $identity->getUserId(),
61
                    'identity' => $identity->getId(),
62
                ],
63
            ]);
64
65
            throw new PasswordNotMatch;
66
        }
67
68
        $this->registerUsageOfIdentity($identity);
69
        $cookie = $this->createCookieIdentity($identity);
70
71
        $this->logger->info('login successful', [
72
            'input' => [
73
                'identifier' => $identifier,
74
            ],
75
            'account' => [
76
                'user' => $identity->getUserId(),
77
                'identity' => $identity->getId(),
78
            ],
79
        ]);
80
81
        $this->currentCookie = $cookie;
82
    }
83
84
85
    private function registerUsageOfIdentity(Entity\Identity $identity)
86
    {
87
        $identity->setLastUsed(time());
88
89
        $mapper = $this->mapperFactory->create(Mapper\Identity::class);
90
        $mapper->store($identity);
91
    }
92
93
94
    private function createCookieIdentity(Entity\EmailIdentity $identity)
95
    {
96
        $cookie = new Entity\CookieIdentity;
97
        $mapper = $this->mapperFactory->create(Mapper\CookieIdentity::class);
98
99
        $cookie->setUserId($identity->getUserId());
100
        $cookie->generateNewSeries();
101
102
        while ($mapper->exists($cookie)) {
103
            // just a failsafe, to prevent violation of constraint
104
            $cookie->generateNewSeries();
105
        }
106
107
        $cookie->generateNewKey();
108
        $cookie->setStatus(Entity\Identity::STATUS_ACTIVE);
109
        $cookie->setExpiresOn(time() + Entity\Identity::COOKIE_LIFESPAN);
110
111
        $mapper->store($cookie);
112
113
        return $cookie;
114
    }
115
116
117
    public function authenticateWithCookie($userId, $series, $key)
118
    {
119
        $identity = $this->retrieveIdenityByCookie($userId, $series, Entity\Identity::STATUS_ACTIVE);
120
121 View Code Duplication
        if ($identity->getId() === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
            $this->logger->error('denial of service', [
123
                'input' => [
124
                    'user' => $userId,
125
                    'series' => $series,
126
                    'key' => $key,
127
                ],
128
                'account' => [
129
                    'user' => $identity->getUserId(),
130
                    'identity' => $identity->getId(),
131
                ],
132
            ]);
133
134
            throw new DenialOfServiceAttempt;
135
        }
136
137
        $mapper = $this->mapperFactory->create(Mapper\CookieIdentity::class);
138
139 View Code Duplication
        if ($identity->getExpiresOn() <  time()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
140
            $identity->setStatus(Entity\Identity::STATUS_EXPIRED);
141
            $mapper->store($identity);
142
            $this->logger->info('cookie expired', [
143
                'input' => [
144
                    'user' => $userId,
145
                    'series' => $series,
146
                    'key' => $key,
147
                ],
148
                'account' => [
149
                    'user' => $identity->getUserId(),
150
                    'identity' => $identity->getId(),
151
                ],
152
            ]);
153
154
            throw new IdentityExpired;
155
        }
156
157 View Code Duplication
        if ($identity->matchKey($key) === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
158
            $identity->setStatus(Entity\Identity::STATUS_BLOCKED);
159
            $mapper->store($identity);
160
161
            $this->logger->error('compromised cookie', [
162
                'input' => [
163
                    'user' => $userId,
164
                    'series' => $series,
165
                    'key' => $key,
166
                ],
167
                'account' => [
168
                    'user' => $identity->getUserId(),
169
                    'identity' => $identity->getId(),
170
                ],
171
            ]);
172
173
            throw new CompromisedCookie;
174
        }
175
176
        $identity->generateNewKey();
177
        $identity->setLastUsed(time());
178
        $identity->setExpiresOn(time() + Entity\Identity::COOKIE_LIFESPAN);
179
180
        $mapper->store($identity);
181
182
        $this->logger->info('cookie updated', [
183
            'account' => [
184
                'user' => $identity->getUserId(),
185
                'identity' => $identity->getId(),
186
            ],
187
        ]);
188
189
        $this->currentCookie = $identity;
190
    }
191
192
193
    private function retrieveIdenityByCookie($userId, $series, $status = Entity\Identity::STATUS_ANY)
194
    {
195
        $cookie = new Entity\CookieIdentity;
196
        $mapper = $this->mapperFactory->create(Mapper\CookieIdentity::class);
197
198
        $cookie->setUserId($userId);
199
        $cookie->setSeries($series);
200
        $cookie->setStatus($status);
201
202
        $mapper->fetch($cookie);
203
204
        return $cookie;
205
    }
206
207
208
    public function retrieveEmailIdenityByIdentifier($identifier)
209
    {
210
        $identity = new Entity\EmailIdentity;
211
        $identity->setIdentifier($identifier);
212
213
        $mapper = $this->mapperFactory->create(Mapper\EmailIdentity::class);
214
        $mapper->fetch($identity);
215
216
        if ($identity->getId() === null) {
217
            $this->logger->warning('acount not found', [
218
                'input' => [
219
                    'identifier' => $identifier,
220
                ],
221
            ]);
222
223
            throw new IdentityNotFound;
224
        }
225
226
227
        return $identity;
228
    }
229
230
231
    public function discardCookie($userId, $series, $key)
232
    {
233
        $identity = $this->retrieveIdenityByCookie($userId, $series, Entity\Identity::STATUS_ACTIVE);
234
235 View Code Duplication
        if ($identity->getId() === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
236
            $this->logger->error('denial of service', [
237
                'input' => [
238
                    'user' => $userId,
239
                    'series' => $series,
240
                    'key' => $key,
241
                ],
242
                'account' => [
243
                    'user' => $identity->getUserId(),
244
                    'identity' => $identity->getId(),
245
                ],
246
            ]);
247
248
            throw new DenialOfServiceAttempt;
249
        }
250
251
        $mapper = $this->mapperFactory->create(Mapper\CookieIdentity::class);
252
253 View Code Duplication
        if ($identity->matchKey($key) === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
254
            $identity->setStatus(Entity\Identity::STATUS_BLOCKED);
255
            $mapper->store($identity);
256
257
            $this->logger->error('compromised cookie', [
258
                'input' => [
259
                    'user' => $userId,
260
                    'series' => $series,
261
                    'key' => $key,
262
                ],
263
                'account' => [
264
                    'user' => $identity->getUserId(),
265
                    'identity' => $identity->getId(),
266
                ],
267
            ]);
268
269
            throw new CompromisedCookie;
270
        }
271
272
        $identity->setStatus(Entity\Identity::STATUS_DISCARDED);
273
        $mapper->store($identity);
274
275
        $this->logger->info('logout successful', [
276
            'account' => [
277
                'user' => $identity->getUserId(),
278
                'identity' => $identity->getId(),
279
            ],
280
        ]);
281
282
    }
283
284
285
    public function changeUserPassword($userId, $oldKey, $newKey)
286
    {
287
        $list = $this->retrieveIdenitiesByUserId($userId, Entity\Identity::TYPE_PASSWORD);
288
289
        if (count($list) !== 1) {
290
            $this->logger->warning('acount not found', [
291
                'input' => [
292
                    'user' => $userId,
293
                    'old-key' => md5($oldKey),
294
                    'new-key' => md5($newKey),
295
                ],
296
            ]);
297
298
            throw new IdentityNotFound;
299
        }
300
301
        $identity = $list->getLastEntity();
302
303
        $mapper = $this->mapperFactory->create(Mapper\EmailIdentity::class);
304
305 View Code Duplication
        if ($identity->matchKey($oldKey) === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
306
            $this->logger->warning('wrong password', [
307
                'input' => [
308
                    'user' => $userId,
309
                    'old-key' => md5($oldKey),
310
                    'new-key' => md5($newKey),
311
                ],
312
                'account' => [
313
                    'user' => $identity->getUserId(),
314
                    'identity' => $identity->getId(),
315
                ],
316
            ]);
317
318
            throw new PasswordNotMatch;
319
        }
320
321
        $identity->setKey($newKey);
322
        $mapper->store($identity);
323
324
        $this->discardAllUserCookies($identity->getUserId());
325
326
        $this->logger->info('password changed', [
327
            'account' => [
328
                'user' => $identity->getUserId(),
329
                'identity' => $identity->getId(),
330
            ],
331
        ]);
332
    }
333
334
335
    public function getCurrentCookie()
336
    {
337
        if (null === $this->currentCookie) {
338
            return new Entity\CookieIdentity;
339
        }
340
341
        return $this->currentCookie;
342
    }
343
344
345
    public function discardCurrentCookie()
346
    {
347
        $cookie = new Entity\CookieIdentity;
348
        $cookie->setExpiresOn(time());
349
350
        $this->currentCookie = $cookie;
351
    }
352
}
353