1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Domain\User\Services; |
4
|
|
|
|
5
|
|
|
use Core\JsonWebToken\JsonWebTokenService; |
6
|
|
|
use Domain\User\Exceptions\UserException; |
7
|
|
|
use Domain\User\Factories\UserFactory; |
8
|
|
|
use Domain\User\User; |
9
|
|
|
use Domain\User\UserFilter; |
10
|
|
|
use Phalcon\Di\AbstractInjectionAware; |
11
|
|
|
use Phalcon\Di\DiInterface; |
12
|
|
|
use stdClass; |
13
|
|
|
|
14
|
|
|
class UserAuthService extends AbstractInjectionAware |
15
|
|
|
{ |
16
|
|
|
public function __construct(DiInterface $di) |
17
|
|
|
{ |
18
|
|
|
$this->setDi($di); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function authenticate(stdClass $data): string |
22
|
|
|
{ |
23
|
|
|
$userFilter = new UserFilter(); |
24
|
|
|
$params = $userFilter->sanitizeAuthParams($data); |
25
|
|
|
|
26
|
|
|
if ($this->authenticationAllowed($params->email)) { |
27
|
|
|
$user = UserFactory::retrieveByEmail($params->email); |
28
|
|
|
|
29
|
|
|
if ($user->doesPasswordMatch($data->password)) { |
30
|
|
|
return $this->createJsonWebToken($user, $params->rememberMe); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
throw new UserException('Wrong email/password combination. Authentication failed.'); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
private function authenticationAllowed(string $email): bool |
38
|
|
|
{ |
39
|
|
|
if ('' === $email) { |
40
|
|
|
throw new UserException('Email parameter is required.'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// @TODO Add email authorization retries count checking with Redis key |
44
|
|
|
return true; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function createJsonWebToken(User $user, $rememberMe = false): string |
48
|
|
|
{ |
49
|
|
|
$expiresIn = '1 day'; |
50
|
|
|
|
51
|
|
|
if (true === $rememberMe) { |
52
|
|
|
$expiresIn = '14 days'; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return JsonWebTokenService::createToken([ |
56
|
|
|
'sub' => 'AuthToken', |
57
|
|
|
'user' => [ |
58
|
|
|
'id' => $user->getId(), |
59
|
|
|
'email' => $user->getEmail(), |
60
|
|
|
'name' => $user->getName(), |
|
|
|
|
61
|
|
|
'role' => $user->getRole(), |
62
|
|
|
], |
63
|
|
|
], $expiresIn); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|