silverstripe /
silverstripe-security-extensions
| 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
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 |