Completed
Pull Request — master (#13)
by
unknown
04:45
created

Recovery::setCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace hiqdev\yii2\mfa\base;
5
6
use Yii;
7
use yii\db\ActiveRecord;
8
9
class Recovery extends ActiveRecord
10
{
11
    public static function tableName()
12
    {
13
        return '{{mfa_recovery_codes}}';
14
    }
15
16
    public function rules(): array
17
    {
18
        return [
19
            ['user_id', 'integer'],
20
            ['user_id', 'required'],
21
            ['code', 'string'],
22
            ['code', 'required'],
23
        ];
24
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function attributeLabels()
30
    {
31
        return [
32
            'code' => Yii::t('mfa', 'Recovery code'),
33
        ];
34
    }
35
36
    public function setUser(int $id): self {
37
        $this->user_id = $id;
38
39
        return $this;
40
    }
41
42
    public function getUser(): int {
43
        return $this->user_id;
44
    }
45
46
    public function setCode(string $code): self {
47
        $this->code = $code;
48
49
        return $this;
50
    }
51
52
    public function getCode(): string {
53
        return $this->code;
54
    }
55
56
    private function setId(int $id): self {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
57
        $this->id = $id;
58
59
        return $this;
60
    }
61
62
    private function getId(): int {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
63
        return $this->id;
64
    }
65
66
    public function save($runValidation = true, $attributeNames = null): bool
67
    {
68
        $this->code = $this->hashCode($this->code);
69
70
        return parent::save($runValidation, $attributeNames);
71
    }
72
73
    public function verifyCode(): bool
74
    {
75
        $recoveryCodes = self::findAll(['user_id' => $this->getUser()]);
76
77
        foreach ($recoveryCodes ?? [] as $recoveryCode){
78
            if (Yii::$app->getSecurity()->validatePassword($this->getCode(), $recoveryCode->getCode())){
79
                $recoveryCode->delete();
80
                return true;
81
            }
82
        }
83
84
        return false;
85
    }
86
87
    private function hashCode(string $code): string
88
    {
89
        return Yii::$app->security->generatePasswordHash($code);
90
    }
91
}