Passed
Push — main ( 12e7e2...8f14aa )
by Garbuz
03:18
created

TokenManager::deactivationAccessToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Garbuzivan\Laraveltokens;
6
7
use Garbuzivan\Laraveltokens\Exceptions\TokenIsNotNalidException;
8
use Garbuzivan\Laraveltokens\Interfaces\AccessTokenRepositoryInterface;
9
use Garbuzivan\Laraveltokens\Interfaces\GlobalTokenRepositoryInterface;
10
use Garbuzivan\Laraveltokens\Models\AccessToken;
11
use Garbuzivan\Laraveltokens\Traits\ManagerAccessTokenTrait;
12
use Garbuzivan\Laraveltokens\Traits\ManagerGlobalTokenTrait;
13
use Illuminate\Support\Str;
14
15
class TokenManager
16
{
17
    use ManagerAccessTokenTrait, ManagerGlobalTokenTrait;
18
19
    /**
20
     * @var Config $config
21
     */
22
    protected Config $config;
23
24
    /**
25
     * @var AccessTokenRepositoryInterface
26
     */
27
    protected AccessTokenRepositoryInterface $accessTokenRepository;
28
29
    /**
30
     * @var GlobalTokenRepositoryInterface
31
     */
32
    protected GlobalTokenRepositoryInterface $globalTokenRepository;
33
34
    /**
35
     * Configuration constructor.
36
     *
37
     * @param Config                         $config
38
     * @param AccessTokenRepositoryInterface $TokenRepository
39
     * @param GlobalTokenRepositoryInterface $globalTokenRepository
40
     */
41
    public function __construct(
42
        Config                         $config,
43
        AccessTokenRepositoryInterface $TokenRepository,
44
        GlobalTokenRepositoryInterface $globalTokenRepository
45
    ) {
46
        $this->config = $config;
47
        $this->accessTokenRepository = $TokenRepository;
48
        $this->globalTokenRepository = $globalTokenRepository;
49
    }
50
51
    /**
52
     * Авторизация по токену
53
     *
54
     * @param string $token
55
     *
56
     * @return AccessToken
57
     * @throws TokenIsNotNalidException
58
     */
59
    public function auth(string $token): AccessToken
60
    {
61
        $token = $this->config->isEncryption() ? $this->getHash($token) : $token;
62
        $tokenDb = $this->accessTokenRepository->getAccessToken($token);
63
        if (is_null($tokenDb) || !$tokenDb->isValid()) {
64
            throw new TokenIsNotNalidException;
65
        }
66
        if ($this->config->isLastUse()) {
67
            $this->accessTokenRepository->setLastUseAccessToken($token);
68
        }
69
        return $tokenDb;
70
    }
71
72
    /**
73
     * Очистить таблицу токенов
74
     *
75
     * @return void
76
     */
77
    public function deleteAllTokens(): void
78
    {
79
        $this->accessTokenRepository->deleteAllAccessToken();
80
        $this->GlobalTokenRepository->deleteAllGlobalToken();
81
    }
82
83
    /**
84
     * Проверить актуальность токена (наличие токена и дата активности)
85
     *
86
     * @param string $token
87
     *
88
     * @return bool
89
     */
90
    public function isValid(string $token): bool
91
    {
92
        $token = $this->config->isEncryption() ? $this->getHash($token) : $token;
93
        $tokenInfo = $this->accessTokenRepository->getAccessToken($token);
94
        if (is_null($tokenInfo) || !$tokenInfo->isValid()) {
95
            return false;
96
        }
97
        return true;
98
    }
99
100
    /**
101
     * Генерация случайного токена на основе даты и случайной строки
102
     *
103
     * @return string
104
     */
105
    public function generateAccessToken(): string
106
    {
107
        return sha1(time() . Str::random());
108
    }
109
110
    /**
111
     * Преобразование токена для БД в зависимости от настройки Encryption
112
     *
113
     * @param string $token
114
     *
115
     * @return string
116
     */
117
    public function getAccessTokenDb(string $token): string
118
    {
119
        return $this->config->isEncryption() ? $this->getHash($token) : $token;
120
    }
121
122
    /**
123
     * Получение хэша
124
     *
125
     * @param string $string
126
     *
127
     * @return string
128
     */
129
    public function getHash(string $string): string
130
    {
131
        return hash('sha256', $string);
132
    }
133
134
    /**
135
     * Сравнение токена
136
     *
137
     * @param string $token
138
     * @param string $hash
139
     *
140
     * @return bool
141
     */
142
    public function isVerify(string $token, string $hash): bool
143
    {
144
        return strcmp($this->getAccessTokenDb($token), $hash) !== 0;
145
    }
146
147
    /**
148
     * Получить deault Morph
149
     *
150
     * @return string
151
     */
152
    public function getDefaultMorph(): string
153
    {
154
        return 'App\Models\User';
155
    }
156
}
157