Passed
Push — main ( 0bfc82...b73123 )
by Garbuz
02:45
created

TokenManager::auth()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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