Completed
Pull Request — master (#13)
by
unknown
24:06 queued 09:01
created

Recovery::attributeLabels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
    public function save($runValidation = true, $attributeNames = null): bool
57
    {
58
        $this->code = $this->hashCode($this->code);
59
60
        return parent::save($runValidation, $attributeNames);
61
    }
62
63
    public function verifyCode(): bool
64
    {
65
        $recoveryCodes = self::findAll(['user_id' => $this->getUser()]);
66
67
        foreach ($recoveryCodes ?? [] as $recoveryCode){
68
            if (Yii::$app->getSecurity()->validatePassword($this->getCode(), $recoveryCode->getCode())){
69
                $recoveryCode->delete();
70
                return true;
71
            }
72
        }
73
74
        return false;
75
    }
76
77
    private function hashCode(string $code): string
78
    {
79
        return Yii::$app->security->generatePasswordHash($code);
80
    }
81
}