|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\Auth; |
|
6
|
|
|
|
|
7
|
|
|
use App\User\User; |
|
8
|
|
|
use App\User\UserRepository; |
|
9
|
|
|
use InvalidArgumentException; |
|
10
|
|
|
use Throwable; |
|
11
|
|
|
use Yiisoft\User\CurrentUser; |
|
12
|
|
|
|
|
13
|
|
|
final class AuthService |
|
14
|
|
|
{ |
|
15
|
|
|
private CurrentUser $currentUser; |
|
16
|
|
|
private UserRepository $userRepository; |
|
17
|
|
|
private IdentityRepository $identityRepository; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct( |
|
20
|
|
|
CurrentUser $currentUser, |
|
21
|
|
|
UserRepository $userRepository, |
|
22
|
|
|
IdentityRepository $identityRepository, |
|
23
|
|
|
) { |
|
24
|
|
|
$this->currentUser = $currentUser; |
|
25
|
|
|
$this->userRepository = $userRepository; |
|
26
|
|
|
$this->identityRepository = $identityRepository; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function login(string $login, string $password, bool $rememberMe = false): bool |
|
30
|
|
|
{ |
|
31
|
|
|
$user = $this->userRepository->findByLoginWithAuthIdentity($login); |
|
32
|
|
|
|
|
33
|
|
|
if ($user === null || !$user->validatePassword($password)) { |
|
34
|
|
|
throw new InvalidArgumentException('Invalid login or password.'); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$identity = $user->getIdentity(); |
|
38
|
|
|
$identity->setShouldLoginByCookie($rememberMe); |
|
39
|
|
|
|
|
40
|
|
|
return $this->currentUser->login($identity); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @throws Throwable |
|
45
|
|
|
*/ |
|
46
|
|
|
public function logout(): bool |
|
47
|
|
|
{ |
|
48
|
|
|
$identity = $this->currentUser->getIdentity(); |
|
49
|
|
|
|
|
50
|
|
|
if ($identity instanceof Identity) { |
|
51
|
|
|
$identity->regenerateCookieLoginKey(); |
|
52
|
|
|
$this->identityRepository->save($identity); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return $this->currentUser->logout(); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @throws Throwable |
|
60
|
|
|
*/ |
|
61
|
|
|
public function signup(string $login, string $password): void |
|
62
|
|
|
{ |
|
63
|
|
|
$user = $this->userRepository->findByLogin($login); |
|
64
|
|
|
|
|
65
|
|
|
if ($user !== null) { |
|
66
|
|
|
throw new InvalidArgumentException('Unable to register user with such login.'); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
$user = new User($login, $password); |
|
70
|
|
|
$this->userRepository->save($user); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function isGuest(): bool |
|
74
|
|
|
{ |
|
75
|
|
|
return $this->currentUser->isGuest(); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|