BackupCodeManager::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/*
3
 * Copyright (C) 2020  Jan Böhmer
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Affero General Public License as published
7
 * by the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Affero General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Affero General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
declare(strict_types=1);
20
21
namespace App\Services\TFA;
22
23
use App\Entity\User;
24
25
/**
26
 * This services offers methods to manage backup codes for two factor authentication.
27
 */
28
class BackupCodeManager
29
{
30
    protected $backupCodeGenerator;
31
32
    public function __construct(BackupCodeGenerator $backupCodeGenerator)
33
    {
34
        $this->backupCodeGenerator = $backupCodeGenerator;
35
    }
36
37
    /**
38
     * Enable backup codes for the given user, by generating a set of backup codes.
39
     * If the backup codes were already enabled before, they a.
40
     */
41
    public function enableBackupCodes(User $user): void
42
    {
43
        if (empty($user->getBackupCodes())) {
44
            $this->regenerateBackupCodes($user);
45
        }
46
    }
47
48
    /**
49
     * Disable (remove) the backup codes when no other 2 factor authentication methods are enabled.
50
     */
51
    public function disableBackupCodesIfUnused(User $user): void
52
    {
53
        if ($user->isGoogleAuthenticatorEnabled()) {
54
            return;
55
        }
56
57
        $user->setBackupCodes([]);
58
    }
59
60
    /**
61
     * Generates a new set of backup codes for the user. If no backup codes were available before, new ones are
62
     * generated.
63
     *
64
     * @param User $user The user for which the backup codes should be regenerated
65
     */
66
    public function regenerateBackupCodes(User $user): void
67
    {
68
        $codes = $this->backupCodeGenerator->generateCodeSet();
69
        $user->setBackupCodes($codes);
70
    }
71
}
72