Completed
Branch v2.0.0 (abe3f2)
by Alexander
01:26
created

UserAuthService::createJsonWebToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 2
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(),
0 ignored issues
show
Bug introduced by
Consider using $user->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
61
                'role' => $user->getRole(),
62
            ],
63
        ], $expiresIn);
64
    }
65
}
66