Passed
Pull Request — master (#38)
by Simon
04:06
created

SiteConfigExtension::onBeforeWrite()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 8
nop 0
dl 0
loc 16
rs 9.6111
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
    /**
29
     * Is MFA Enforced via a comparison in {@link updateCMSFields()}
30
     *
31
     * @var bool
32
     */
33
    public $EnforceMFA = false;
34
35
    /**
36
     * Add the checkbox and if enabled the date since enforcement
37
     *
38
     * @param FieldList $fields
39
     */
40
    public function updateCMSFields(FieldList $fields)
41
    {
42
        $this->EnforceMFA = !($this->owner->ForceMFA === null || $this->owner->ForceMFA === '0000-00-00');
43
        $fields->addFieldToTab(
44
            'Root.MFA',
45
            CheckboxField::create(
46
                'EnforceMFA',
47
                _t(self::class . '.ENFORCEMFA', 'Enforce MFA on all users'),
48
                $this->EnforceMFA
49
            )
50
        );
51
        if ($this->EnforceMFA) {
52
            $fields->addFieldToTab(
53
                'Root.MFA',
54
                ReadonlyField::create('ForceMFA', _t(self::class . '.ENFORCEDSINCE', 'MFA enforced since'))
55
            );
56
        }
57
    }
58
59
    public function onBeforeWrite()
60
    {
61
        parent::onBeforeWrite();
62
        // Edge case, when building from the previous Boolean, it'll set itself to 0000-00-00
63
        if ($this->owner->ForceMFA === '0000-00-00') {
64
            $this->owner->ForceMFA = null;
65
        }
66
67
        /* Set the MFA enforcement */
68
        if (!$this->owner->ForceMFA && $this->owner->EnforceMFA) {
69
            $this->owner->ForceMFA = DBDatetime::now()->Format('YYYY-MM-dd');
70
        }
71
72
        /* Reset the MFA enforcement if the checkbox is unchecked */
73
        if (!$this->owner->EnforceMFA) {
74
            $this->owner->ForceMFA = null;
75
        }
76
    }
77
}
78