1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PSR7Auth\IdentityProvider; |
6
|
|
|
|
7
|
|
|
use Assert\Assertion; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use PSR7Auth\Domain\Entity\UserInterface; |
11
|
|
|
use PSR7Auth\Exception\IdentityNotFoundException; |
12
|
|
|
use PSR7Auth\IdentityProvider\Mapper\BasicIdentityMapperInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Class FormIdentityProvider |
16
|
|
|
*/ |
17
|
|
|
final class FormIdentityProvider implements IdentityProviderInterface |
18
|
|
|
{ |
19
|
|
|
/** @var BasicIdentityMapperInterface */ |
20
|
|
|
private $mapper; |
21
|
|
|
|
22
|
|
|
/** @var string */ |
23
|
|
|
private $identityKey; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* FormIdentityProvider constructor. |
27
|
|
|
* |
28
|
|
|
* @param BasicIdentityMapperInterface $mapper |
29
|
|
|
* @param string $identityKey |
30
|
|
|
*/ |
31
|
3 |
|
public function __construct(BasicIdentityMapperInterface $mapper, string $identityKey) |
32
|
|
|
{ |
33
|
3 |
|
$this->mapper = $mapper; |
34
|
3 |
|
$this->identityKey = $identityKey; |
35
|
3 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @inheritDoc |
39
|
|
|
*/ |
40
|
3 |
|
public function __invoke(ServerRequestInterface $request): UserInterface |
41
|
|
|
{ |
42
|
3 |
|
$data = $request->getParsedBody(); |
43
|
3 |
|
Assertion::isArray($data); |
44
|
3 |
|
Assertion::keyExists($data, $this->identityKey); |
45
|
|
|
|
46
|
3 |
|
$identity = $data[$this->identityKey]; |
47
|
3 |
|
$fields = [BasicIdentityMapperInterface::MODE_EMAIL, BasicIdentityMapperInterface::MODE_USERNAME]; |
48
|
3 |
|
$user = null; |
49
|
|
|
|
50
|
3 |
|
while (! $user instanceof UserInterface && count($fields) > 0) { |
51
|
3 |
|
$mode = array_shift($fields); |
52
|
|
|
try { |
53
|
3 |
|
$user = $this->getUserByModeAndIdentity($mode, $identity); |
54
|
2 |
|
} catch (IdentityNotFoundException $exception) { |
55
|
2 |
|
continue; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
3 |
|
if (! $user instanceof UserInterface) { |
60
|
1 |
|
throw new IdentityNotFoundException(); |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
return $user; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string $mode |
68
|
|
|
* @param string $identity |
69
|
|
|
* |
70
|
|
|
* @return UserInterface |
71
|
|
|
*/ |
72
|
3 |
|
private function getUserByModeAndIdentity(string $mode, string $identity): UserInterface |
73
|
|
|
{ |
74
|
|
|
switch ($mode) { |
75
|
3 |
|
case BasicIdentityMapperInterface::MODE_EMAIL: |
76
|
3 |
|
return $this->mapper->getByEmail($identity); |
77
|
2 |
|
case BasicIdentityMapperInterface::MODE_USERNAME: |
78
|
2 |
|
return $this->mapper->getByUsername($identity); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
throw new InvalidArgumentException('Invalid authentication mode'); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|