summaryrefslogtreecommitdiff
path: root/core/classes/authentication/Core/PasswordTrait.php
blob: 40a7381e43c52a8eb92067a55ea42c657c8c9a5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
/** Trait PasswordTrait
 * 
 * @package DevCoder\Authentication\Core
 * 
 */
# namespace DevCoder\Authentication\Core;
# 
# use DevCoder\Authentication\UserInterface;

trait PasswordTrait
{
    
    private $cost = 10;     // Cost must be in the range of 4-31
            // a cost value in the range of 8-11
            // is a good balance between performance and security


    public function cryptPassword(string $plainPassword): string
    {
        return password_hash($plainPassword, PASSWORD_BCRYPT, ['cost' => $this->cost]);
    }


    public function isPasswordValid(UserInterface $user, string $plainPassword): bool
    {
        return password_verify($plainPassword, $user->getPassword());
    }


    public function setCost(int $cost): void
    {
        if ($cost < 4 || $cost > 31) {
            throw new \InvalidArgumentException('Cost must be in the range of 4-31.');
        }
        $this->cost = $cost;
    }
}