SudoModeService::getLifetime()   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
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SilverStripe\SecurityExtensions\Service;
6
7
use SilverStripe\Control\Session;
8
use SilverStripe\Core\Config\Configurable;
9
use SilverStripe\ORM\FieldType\DBDatetime;
10
11
class SudoModeService implements SudoModeServiceInterface
12
{
13
    use Configurable;
14
15
    /**
16
     * The lifetime that sudo mode authorization lasts for, in minutes.
17
     *
18
     * Note that if the PHP session times out before this lifetime is reached, it will automatically be reset.
19
     * @see \SilverStripe\Control\Session::$timeout
20
     *
21
     * @config
22
     * @var int
23
     */
24
    private static $lifetime_minutes = 45;
0 ignored issues
show
introduced by
The private property $lifetime_minutes is not used, and could be removed.
Loading history...
25
26
    /**
27
     * The session key that is used to store the timestamp for when sudo mode was last activated
28
     *
29
     * @var string
30
     */
31
    private const SUDO_MODE_SESSION_KEY = 'sudo-mode-last-activated';
32
33
    public function check(Session $session): bool
34
    {
35
        $lastActivated = $session->get(self::SUDO_MODE_SESSION_KEY);
36
        // Not activated at all
37
        if (!$lastActivated) {
38
            return false;
39
        }
40
41
        // Activated within the last "lifetime" window
42
        $nowTimestamp = DBDatetime::now()->getTimestamp();
43
        return $lastActivated > ($nowTimestamp - $this->getLifetime() * 60);
44
    }
45
46
    public function activate(Session $session): bool
47
    {
48
        $session->set(self::SUDO_MODE_SESSION_KEY, DBDatetime::now()->getTimestamp());
49
        return true;
50
    }
51
52
    public function getLifetime(): int
53
    {
54
        return (int) $this->config()->get('lifetime_minutes');
55
    }
56
}
57