Passed
Pull Request — master (#22)
by Simon
01:54
created

SiteConfigExtension::updateCMSFields()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 4
nop 1
dl 0
loc 15
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace Firesphere\BootstrapMFA\Extensions;
4
5
use SilverStripe\Forms\CheckboxField;
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\Forms\ReadonlyField;
8
use SilverStripe\ORM\DataExtension;
9
use SilverStripe\ORM\FieldType\DBDatetime;
10
use SilverStripe\SiteConfig\SiteConfig;
11
12
/**
13
 * Class \Firesphere\BootstrapMFA\Extensions\SiteConfigExtension
14
 *
15
 * @property SiteConfig|SiteConfigExtension $owner
16
 * @property string $ForceMFA
17
 */
18
class SiteConfigExtension extends DataExtension
19
{
20
21
    /**
22
     * @var array
23
     */
24
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
25
        'ForceMFA' => 'Date'
26
    ];
27
    /**
28
     * Is MFA Enforced via a comparison in {@link updateCMSFields()}
29
     *
30
     * @var bool
31
     */
32
    protected $EnforceMFA = false;
33
34
    /**
35
     * Add the checkbox and if enabled the date since enforcement
36
     *
37
     * @param FieldList $fields
38
     */
39
    public function updateCMSFields(FieldList $fields)
40
    {
41
        $this->EnforceMFA = !($this->owner->ForceMFA === null || $this->owner->ForceMFA === '0000-00-00');
42
        $fields->addFieldToTab(
43
            'Root.MFA',
44
            CheckboxField::create(
45
                'EnforceMFA',
46
                _t(self::class . '.ENFORCEMFA', 'Enforce MFA on all users'),
47
                $this->EnforceMFA
48
            )
49
        );
50
        if ($this->EnforceMFA) {
51
            $fields->addFieldToTab(
52
                'Root.MFA',
53
                ReadonlyField::create('ForceMFA', _t(self::class . '.ENFORCEDSINCE', 'MFA enforced since'))
54
            );
55
        }
56
    }
57
58
    public function onBeforeWrite()
59
    {
60
        parent::onBeforeWrite();
61
        // Edge case, when building from the previous Boolean, it'll set itself to 0000-00-00
62
        if ($this->owner->ForceMFA === '0000-00-00') {
63
            $this->owner->ForceMFA = null;
64
        }
65
66
        /* Set the MFA enforcement */
67
        if (!$this->owner->ForceMFA && $this->owner->EnforceMFA) {
68
            $this->owner->ForceMFA = DBDatetime::now()->Format('YYYY-MM-dd');
69
        }
70
71
        /* Reset the MFA enforcement if the checkbox is unchecked */
72
        if (!$this->owner->EnforceMFA) {
73
            $this->owner->ForceMFA = null;
74
        }
75
    }
76
}
77