1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Application\User\Service; |
6
|
|
|
|
7
|
|
|
use App\Application\Exception\BadRequestException; |
8
|
|
|
use App\Application\User\Entity\User; |
9
|
|
|
use App\Queue\LoggingAuthorizationHandler; |
10
|
|
|
use App\Queue\UserLoggedInMessage; |
11
|
|
|
use Yiisoft\Auth\IdentityInterface; |
12
|
|
|
use Yiisoft\Auth\IdentityRepositoryInterface; |
13
|
|
|
use Yiisoft\User\CurrentUser; |
14
|
|
|
use Yiisoft\Yii\Queue\QueueFactoryInterface; |
15
|
|
|
use Yiisoft\Definitions\Exception\InvalidConfigException; |
16
|
|
|
|
17
|
|
|
final class UserService |
18
|
|
|
{ |
19
|
|
|
private IdentityRepositoryInterface $identityRepository; |
20
|
|
|
private CurrentUser $currentUser; |
21
|
|
|
private QueueFactoryInterface $queueFactory; |
22
|
|
|
|
23
|
2 |
|
public function __construct( |
24
|
|
|
CurrentUser $currentUser, |
25
|
|
|
IdentityRepositoryInterface $identityRepository, |
26
|
|
|
QueueFactoryInterface $queueFactory |
27
|
|
|
) { |
28
|
2 |
|
$this->currentUser = $currentUser; |
29
|
2 |
|
$this->identityRepository = $identityRepository; |
30
|
2 |
|
$this->queueFactory = $queueFactory; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param string $login |
35
|
|
|
* @param string $password |
36
|
|
|
* |
37
|
|
|
* @throws InvalidConfigException |
38
|
|
|
* @throws BadRequestException |
39
|
|
|
* |
40
|
|
|
* @return IdentityInterface |
41
|
|
|
*/ |
42
|
1 |
|
public function login(string $login, string $password): IdentityInterface |
43
|
|
|
{ |
44
|
1 |
|
$identity = $this->identityRepository->findByLogin($login); |
45
|
1 |
|
if ($identity === null) { |
46
|
|
|
throw new BadRequestException('No such user.'); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
if (!$identity->validatePassword($password)) { |
50
|
|
|
throw new BadRequestException('Invalid password.'); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
if (!$this->currentUser->login($identity)) { |
54
|
|
|
throw new BadRequestException(); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
$identity->resetToken(); |
58
|
1 |
|
$this->identityRepository->save($identity); |
59
|
|
|
|
60
|
1 |
|
$queueMessage = new UserLoggedInMessage($identity->getId(), time()); |
61
|
1 |
|
$this->queueFactory->get(LoggingAuthorizationHandler::CHANNEL)->push($queueMessage); |
62
|
|
|
|
63
|
1 |
|
return $identity; |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
public function logout(User $user): void |
67
|
|
|
{ |
68
|
1 |
|
$user->resetToken(); |
69
|
1 |
|
$this->identityRepository->save($user); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|