Merge pull request #7694 from creative-commoners/pulls/4.0/injection-session

FIX Use Injector to retrieve the current session
This commit is contained in:
Damian Mooyman 2017-12-12 16:47:36 +13:00 committed by GitHub
commit a2fa9f0943
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,11 +2,13 @@
namespace SilverStripe\Security;
use Exception;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HiddenField;
use SilverStripe\View\TemplateGlobalProvider;
@ -56,7 +58,7 @@ class SecurityToken implements TemplateGlobalProvider
protected static $enabled = true;
/**
* @var String $name
* @var string $name
*/
protected $name = null;
@ -110,7 +112,7 @@ class SecurityToken implements TemplateGlobalProvider
}
/**
* @return String
* @return string
*/
public static function get_default_name()
{
@ -146,11 +148,11 @@ class SecurityToken implements TemplateGlobalProvider
}
/**
* @return String
* @return string
*/
public function getValue()
{
$session = Controller::curr()->getRequest()->getSession();
$session = $this->getSession();
$value = $session->get($this->getName());
// only regenerate if the token isn't already set in the session
@ -163,12 +165,30 @@ class SecurityToken implements TemplateGlobalProvider
}
/**
* @param String $val
* @param string $val
* @return $this
*/
public function setValue($val)
{
$session = Controller::curr()->getRequest()->getSession();
$session->set($this->getName(), $val);
$this->getSession()->set($this->getName(), $val);
return $this;
}
/**
* Returns the current session instance from the injector
*
* @return Session
* @throws Exception If the HTTPRequest class hasn't been registered as a service and no controllers exist
*/
protected function getSession()
{
$injector = Injector::inst();
if ($injector->has(HTTPRequest::class)) {
return $injector->get(HTTPRequest::class)->getSession();
} elseif (Controller::has_curr()) {
return Controller::curr()->getRequest()->getSession();
}
throw new Exception('No HTTPRequest object or controller available yet!');
}
/**
@ -188,8 +208,8 @@ class SecurityToken implements TemplateGlobalProvider
*
* Typically you'll want to check {@link Form->securityTokenEnabled()} before calling this method.
*
* @param String $compare
* @return Boolean
* @param string $compare
* @return boolean
*/
public function check($compare)
{
@ -246,8 +266,8 @@ class SecurityToken implements TemplateGlobalProvider
}
/**
* @param String $url
* @return String
* @param string $url
* @return string
*/
public function addToUrl($url)
{
@ -272,7 +292,7 @@ class SecurityToken implements TemplateGlobalProvider
/**
* @uses RandomGenerator
*
* @return String
* @return string
*/
protected function generate()
{