x Sorry, these patches are not available anymore due to data migration. Please run a fresh inspection.
Test Failed
Pull Request — master (#7)
by Koen
03:55
created

Dispensary::dispense()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Auth\Dispensary;
6
7
use App\Auth\Dispensary\Exceptions\TokenExpired;
8
use Illuminate\Contracts\Auth\Authenticatable;
9
use Illuminate\Contracts\Cache\Repository;
10
use Illuminate\Contracts\Hashing\Hasher;
11
use Illuminate\Support\Str;
12
use function class_basename;
13
14
final class Dispensary
15
{
16
    private Repository $cache;
17
18
    private Hasher $hasher;
19
20
    private int $ttl;
21
22
    private int $chars;
23
24
    public function __construct(Repository $cache, Hasher $hasher, int $ttl = 60, int $chars = 128)
25
    {
26
        $this->cache = $cache;
27
        $this->hasher = $hasher;
28
        $this->ttl = $ttl;
29
        $this->chars = $chars;
30
    }
31
32
    public function dispense(Authenticatable $user): string
33
    {
34
        $token = $this->generateToken();
35
36
        $this->cache->put($this->getCacheKey($user), $this->hasher->make($token), $this->ttl);
37
38
        return $token;
39
    }
40
41
    /**
42
     * @param  \Illuminate\Contracts\Auth\Authenticatable $user
43
     * @param  string                                     $token
44
     * @return bool
45
     * @throws \App\Auth\Dispensary\Exceptions\TokenExpired
46
     * @throws \Psr\SimpleCache\InvalidArgumentException
47
     */
48
    public function verify(Authenticatable $user, string $token): bool
49
    {
50
        $hashedToken = $this->cache->get($this->getCacheKey($user));
51
52
        if (null === $hashedToken) {
53
            throw new TokenExpired();
54
        }
55
56
        return $this->hasher->check($token, $hashedToken);
57
    }
58
59
    private function generateToken(): string
60
    {
61
        return Str::random($this->chars);
62
    }
63
64
    private function getCacheKey(Authenticatable $user)
65
    {
66
        return implode('_', [
67
            class_basename($user),
68
            'Token',
69
            $user->getAuthIdentifier(),
70
        ]);
71
    }
72
}
73