UserPasswordHistoryTrait::onAddPasswordToHistory()   B
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.4444
c 0
b 0
f 0
ccs 0
cts 16
cp 0
cc 8
nc 7
nop 1
crap 72
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\user\security;
14
15
use yii\base\ModelEvent;
16
use yii\base\InvalidParamException;
17
18
/**
19
 * This trait provides password history operation for User model.
20
 *
21
 * @property-read PasswordHistory[] $passwordHistories
22
 *
23
 * @version 1.0
24
 * @author vistart <[email protected]>
25
 */
26
trait UserPasswordHistoryTrait
27
{
28
    /**
29
     * @var string|false Password History class name. If you do not need password
30
     * history model, please set it false.
31
     */
32
    public $passwordHistoryClass = false;
33
    
34
    /**
35
     * @var boolean determine whether to allow the password that has been used to be stored.
36
     */
37
    public $allowUsedPassword = true;
38
    
39
    /**
40
     * Get all password histories sorted by creation time in descending order.
41
     * @return boolean|PasswordHistory[] False if password history class is invalid.
42
     */
43
    public function getPasswordHistories()
44
    {
45
        if (empty($this->passwordHistoryClass) || !class_exists($this->passwordHistoryClass)) {
46
            return false;
47
        }
48
        $class = $this->passwordHistoryClass;
49
        return $class::find()->createdBy($this)->orderByCreatedAt(SORT_DESC)->all();
50
    }
51
    
52
    /**
53
     * This event is ONLY used for adding password to history.
54
     * You SHOULD NOT call this method directly, or you know the consequences of doing so
55
     * @param ModelEvent $event
56
     * @return boolean False if no password was added to history.
57
     */
58
    public function onAddPasswordToHistory($event)
59
    {
60
        $password = $event->data;
61
        $sender = $event->sender;
62
        /* @var $sender static */
63
        if (empty($sender->passwordHistoryClass) ||
64
                !class_exists($sender->passwordHistoryClass) ||
65
                empty($sender->passwordHashAttribute) ||
0 ignored issues
show
Bug introduced by
The property passwordHashAttribute does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
66
                !is_string($sender->passwordHashAttribute)) {
67
            return false;
68
        }
69
        if (empty($password)) {
70
            $password = ['pass_hash' => $sender->{$sender->passwordHashAttribute}];
71
        }
72
        $class = $sender->passwordHistoryClass;
73
        if (array_key_exists('pass_hash', $password)) {
74
            return $class::addHash($password['pass_hash'], $sender);
75
        }
76
        if (array_key_exists('password', $password)) {
77
            return $class::add($password['password'], $sender);
78
        }
79
        return false;
80
    }
81
82
    /**
83
     * Add password to history.
84
     * Note: Please specify password history class before using this method.
85
     *
86
     * @param string $password the password to be added.
87
     * @return boolean whether the password added. False if password history class not specified.
88
     * @throws InvalidParamException throw if password existed.
89
     */
90
    public function addPasswordHistory($password)
91
    {
92
        if (!empty($this->passwordHistoryClass) && class_exists($this->passwordHistoryClass)) {
93
            $class = $this->passwordHistoryClass;
94
            return $class::add($password, $this);
95
        }
96
        return false;
97
    }
98
    
99
    /**
100
     * Add password hash to history.
101
     * Note: Please specify password history class before using this method.
102
     *
103
     * @param string $passHash Password hash to be added.
104
     * @return boolean whether the password hash added. False if password history class not specified.
105
     * @throws InvalidParamException throw if password existed.
106
     */
107
    public function addPasswordHashToHistory($passHash)
108
    {
109
        if (!empty($this->passwordHistoryClass) && class_exists($this->passwordHistoryClass)) {
110
            $class = $this->passwordHistoryClass;
111
            return $class::addHash($passHash, $this);
112
        }
113
        return false;
114
    }
115
    
116
    /**
117
     * @inheritdoc
118
     */
119
    public function getPasswordHashRules()
120
    {
121
        if (empty($this->passwordHashAttribute) || !is_string($this->passwordHashAttribute)) {
122
            return [];
123
        }
124
        $rules = parent::getPasswordHashRules();
125
        $rules[] = [
126
            [$this->passwordHashAttribute], 'checkPasswordNotUsed', 'when' => function () {
127
                return $this->isAttributeChanged($this->passwordHashAttribute)
0 ignored issues
show
Bug introduced by
It seems like isAttributeChanged() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
128
                        && !$this->allowUsedPassword && !$this->getIsNewRecord();
0 ignored issues
show
Bug introduced by
It seems like getIsNewRecord() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
129
            }
130
        ];
131
        return $rules;
132
    }
133
    
134
    /**
135
     * @var string The message for password used error.
136
     */
137
    public $passwordUsedMessage = 'The password has been used.';
138
    
139
    public static $eventPasswordUsed = 'passwordUsed';
140
141
    /**
142
     * This method is only used for password hash attribute validation.
143
     * If password is used, the `eventPasswordUsed` event will be triggered.
144
     *
145
     * @param string $attribute
146
     * @param mixed $params
147
     * @param type $validator
148
     */
149
    public function checkPasswordNotUsed($attribute, $params, $validator)
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $validator is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
150
    {
151
        $class = $this->passwordHistoryClass;
152
        $result = $class::isUsed($this->_password, $this);
0 ignored issues
show
Bug introduced by
The property _password does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
153
        if ($result != false) {
154
            $this->trigger(static::$eventPasswordUsed);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
155
            $this->addError($attribute, $this->passwordUsedMessage);
0 ignored issues
show
Bug introduced by
It seems like addError() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
156
        }
157
    }
158
}
159