Passed
Pull Request — master (#7)
by Koen
05:32
created

Dispensary   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 56
ccs 22
cts 22
cp 1
rs 10
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A dispense() 0 7 1
A __construct() 0 6 1
A generateToken() 0 3 1
A getCacheKey() 0 6 1
A verify() 0 9 2
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 10
    public function __construct(Repository $cache, Hasher $hasher, int $ttl = 60, int $chars = 128)
25
    {
26 10
        $this->cache = $cache;
27 10
        $this->hasher = $hasher;
28 10
        $this->ttl = $ttl;
29 10
        $this->chars = $chars;
30 10
    }
31
32 5
    public function dispense(Authenticatable $user): string
33
    {
34 5
        $token = $this->generateToken();
35
36 5
        $this->cache->put($this->getCacheKey($user), $this->hasher->make($token), $this->ttl);
37
38 5
        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 4
    public function verify(Authenticatable $user, string $token): bool
49
    {
50 4
        $hashedToken = $this->cache->get($this->getCacheKey($user));
51
52 4
        if (null === $hashedToken) {
53 1
            throw new TokenExpired();
54
        }
55
56 3
        return $this->hasher->check($token, $hashedToken);
57
    }
58
59 5
    private function generateToken(): string
60
    {
61 5
        return Str::random($this->chars);
62
    }
63
64 5
    private function getCacheKey(Authenticatable $user)
65
    {
66 5
        return implode('_', [
67 5
            class_basename($user),
68 5
            'Token',
69 5
            $user->getAuthIdentifier(),
70
        ]);
71
    }
72
}
73