Passed
Push — master ( ed990d...3173d8 )
by Adrien
02:49
created

HasPassword::setPassword()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 13
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Model\Traits;
6
7
use Cake\Chronos\Chronos;
8
use Doctrine\ORM\Mapping as ORM;
9
use GraphQL\Doctrine\Annotation as API;
10
11
/**
12
 * Trait for a user with a password and password reset capabilities.
13
 */
14
trait HasPassword
15
{
16
    /**
17
     * @API\Exclude
18
     * @ORM\Column(type="string", length=255)
19
     */
20
    private string $password = '';
21
22
    /**
23
     * @API\Exclude
24
     * @ORM\Column(type="string", length=32, nullable=true, unique=true)
25
     */
26
    private ?string $token = null;
27
28
    /**
29
     * The time when user asked to reset password.
30
     *
31
     * @API\Exclude
32
     * @ORM\Column(type="datetime", nullable=true)
33
     */
34
    private ?Chronos $tokenCreationDate = null;
35
36
    /**
37
     * Hash and change the user password.
38
     */
39 2
    public function setPassword(string $password): void
40
    {
41
        // Ignore empty password that could be sent "by mistake" by the client
42
        // when agreeing to terms
43 2
        if ($password === '') {
44 1
            return;
45
        }
46
47 2
        $this->revokeToken();
48
49 2
        $password = password_hash($password, PASSWORD_DEFAULT);
50
51 2
        $this->password = $password;
52
    }
53
54
    /**
55
     * Returns the hashed password.
56
     *
57
     * @API\Exclude
58
     */
59 1
    public function getPassword(): string
60
    {
61 1
        return $this->password;
62
    }
63
64
    /**
65
     * Generate a new random token to reset password.
66
     */
67 1
    public function createToken(): string
68
    {
69 1
        $this->token = bin2hex(random_bytes(16));
70 1
        $this->tokenCreationDate = new Chronos();
71
72 1
        return $this->token;
73
    }
74
75
    /**
76
     * Destroy existing token.
77
     */
78 2
    public function revokeToken(): void
79
    {
80 2
        $this->token = null;
81 2
        $this->tokenCreationDate = null;
82
    }
83
84
    /**
85
     * Check if token is valid.
86
     *
87
     * @API\Exclude
88
     */
89 1
    public function isTokenValid(): bool
90
    {
91 1
        if (!$this->tokenCreationDate) {
92 1
            return false;
93
        }
94
95 1
        $timeLimit = $this->tokenCreationDate->addMinutes(30);
96
97 1
        return $timeLimit->isFuture();
98
    }
99
}
100