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

Dispensary::dispense()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

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
ccs 4
cts 4
cp 1
crap 1
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 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