code
stringlengths 17
296k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
protected function getJoinTable($type)
{
Deprecation::notice('5.1.0', 'Use getGroupJoinTable() instead');
return $this->getGroupJoinTable($type);
} | Get join table for type
Defaults to those provided by {@see InheritedPermissionsExtension)
@deprecated 5.1.0 Use getGroupJoinTable() instead
@param string $type
@return string | getJoinTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getGroupJoinTable($type)
{
switch ($type) {
case InheritedPermissions::DELETE:
// Delete uses edit type - Drop through
case InheritedPermissions::EDIT:
return $this->getEditorGroupsTable();
case InheritedPermissions::VIEW:
return $this->getViewerGroupsTable();
default:
throw new InvalidArgumentException("Invalid argument type $type");
}
} | Get group join table for type
Defaults to those provided by {@see InheritedPermissionsExtension)
@param string $type
@return string | getGroupJoinTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getMemberJoinTable($type)
{
switch ($type) {
case InheritedPermissions::DELETE:
// Delete uses edit type - Drop through
case InheritedPermissions::EDIT:
return $this->getEditorMembersTable();
case InheritedPermissions::VIEW:
return $this->getViewerMembersTable();
default:
throw new InvalidArgumentException("Invalid argument type $type");
}
} | Get member join table for type
Defaults to those provided by {@see InheritedPermissionsExtension)
@param string $type
@return string | getMemberJoinTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function checkDefaultPermissions($type, Member $member = null)
{
$defaultPermissions = $this->getDefaultPermissions();
if (!$defaultPermissions) {
return false;
}
switch ($type) {
case InheritedPermissions::VIEW:
return $defaultPermissions->canView($member);
case InheritedPermissions::EDIT:
return $defaultPermissions->canEdit($member);
case InheritedPermissions::DELETE:
return $defaultPermissions->canDelete($member);
default:
return false;
}
} | Determine default permission for a givion check
@param string $type Method to check
@param Member $member
@return bool | checkDefaultPermissions | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function isVersioned()
{
if (!class_exists(Versioned::class)) {
return false;
}
/** @var Versioned|DataObject $singleton */
$singleton = DataObject::singleton($this->getBaseClass());
return $singleton->hasExtension(Versioned::class) && $singleton->hasStages();
} | Check if this model has versioning
@return bool | isVersioned | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getEditorGroupsTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_EditorGroups";
} | Get table to use for editor groups relation
@return string | getEditorGroupsTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getViewerGroupsTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_ViewerGroups";
} | Get table to use for viewer groups relation
@return string | getViewerGroupsTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getEditorMembersTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_EditorMembers";
} | Get table to use for editor members relation
@return string | getEditorMembersTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getViewerMembersTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_ViewerMembers";
} | Get table to use for viewer members relation
@return string | getViewerMembersTable | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function getCachePermissions($cacheKey)
{
// Check local cache
if (isset($this->cachePermissions[$cacheKey])) {
return $this->cachePermissions[$cacheKey];
}
// Check persistent cache
if ($this->cacheService) {
$result = $this->cacheService->get($cacheKey);
// Warm local cache
if ($result) {
$this->cachePermissions[$cacheKey] = $result;
return $result;
}
}
return null;
} | Gets the permission from cache
@param string $cacheKey
@return mixed | getCachePermissions | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
protected function generateCacheKey($type, $memberID)
{
$classKey = str_replace('\\', '-', $this->baseClass ?? '');
return "{$type}-{$classKey}-{$memberID}";
} | Creates a cache key for a member and type
@param string $type
@param int $memberID
@return string | generateCacheKey | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php | BSD-3-Clause |
public static function flush()
{
singleton(__CLASS__)->flushCache();
} | Flush all MemberCacheFlusher services | flush | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissionFlusher.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissionFlusher.php | BSD-3-Clause |
protected function getMemberIDList()
{
if (!$this->owner || !$this->owner->exists()) {
return null;
}
if ($this->owner instanceof Group) {
return $this->owner->Members()->column('ID');
}
return [$this->owner->ID];
} | Get a list of member IDs that need their permissions flushed
@return array|null | getMemberIDList | php | silverstripe/silverstripe-framework | src/Security/InheritedPermissionFlusher.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissionFlusher.php | BSD-3-Clause |
protected function getAuthenticator($name = 'default')
{
$authenticators = $this->getAuthenticators();
if (isset($authenticators[$name])) {
return $authenticators[$name];
}
throw new LogicException('No valid authenticator found');
} | Get the selected authenticator for this request
@param string $name The identifier of the authenticator in your config
@return Authenticator Class name of Authenticator
@throws LogicException | getAuthenticator | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function getApplicableAuthenticators($service = Authenticator::LOGIN)
{
$authenticators = $this->getAuthenticators();
foreach ($authenticators as $name => $authenticator) {
if (!($authenticator->supportedServices() & $service)) {
unset($authenticators[$name]);
}
}
if (empty($authenticators)) {
throw new LogicException('No applicable authenticators found');
}
return $authenticators;
} | Get all registered authenticators
@param int $service The type of service that is requested
@return Authenticator[] Return an array of Authenticator objects | getApplicableAuthenticators | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function hasAuthenticator($authenticator)
{
$authenticators = $this->getAuthenticators();
return !empty($authenticators[$authenticator]);
} | Check if a given authenticator is registered
@param string $authenticator The configured identifier of the authenticator
@return bool Returns TRUE if the authenticator is registered, FALSE
otherwise. | hasAuthenticator | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function setCurrentUser($currentUser = null)
{
Security::$currentUser = $currentUser;
} | The intended uses of this function is to temporarily change the current user for things such as
canView() checks or unit tests. It is stateless and will not persist between requests. Importantly
it also will not call any logic that may be present in the current IdentityStore logIn() or logout() methods
If you are unit testing and calling FunctionalTest::get() or FunctionalTest::post() and you need to change
the current user, you should instead use SapphireTest::logInAs() / logOut() which itself will call
Injector::inst()->get(IdentityStore::class)->logIn($member) / logout()
@param null|Member $currentUser | setCurrentUser | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function Link($action = null)
{
$link = Controller::join_links(Director::baseURL(), "Security", $action);
$this->extend('updateLink', $link, $action);
return $link;
} | Get a link to a security action
@param string $action Name of the action
@return string Returns the link to the given action | Link | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function ping()
{
HTTPCacheControlMiddleware::singleton()->disableCache();
Requirements::clear();
return 1;
} | This action is available as a keep alive, so user
sessions don't timeout. A common use is in the admin. | ping | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function preLogin()
{
// Event handler for pre-login, with an option to let it break you out of the login form
$eventResults = $this->extend('onBeforeSecurityLogin');
// If there was a redirection, return
if ($this->redirectedTo()) {
return $this->getResponse();
}
// If there was an HTTPResponse object returned, then return that
if ($eventResults) {
foreach ($eventResults as $result) {
if ($result instanceof HTTPResponse) {
return $result;
}
}
}
// If arriving on the login page already logged in, with no security error, and a ReturnURL then redirect
// back. The login message check is necessary to prevent infinite loops where BackURL links to
// an action that triggers Security::permissionFailure.
// This step is necessary in cases such as automatic redirection where a user is authenticated
// upon landing on an SSL secured site and is automatically logged in, or some other case
// where the user has permissions to continue but is not given the option.
if (!$this->getSessionMessage()
&& ($member = static::getCurrentUser())
&& $member->exists()
&& $this->getRequest()->requestVar('BackURL')
) {
return $this->redirectBack();
}
return null;
} | Perform pre-login checking and prepare a response if available prior to login
@return HTTPResponse Substitute response object if the login process should be circumvented.
Returns null if should proceed as normal. | preLogin | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function getResponseController($title)
{
// Use the default setting for which Page to use to render the security page
$pageClass = $this->config()->get('page_class');
if (!$pageClass || !class_exists($pageClass ?? '')) {
return $this;
}
// Create new instance of page holder
/** @var Page $holderPage */
$holderPage = Injector::inst()->create($pageClass);
$holderPage->Title = $title;
$holderPage->URLSegment = 'Security';
// Disable ID-based caching of the log-in page by making it a random number
$holderPage->ID = -1 * random_int(1, 10000000);
$controller = ModelAsController::controller_for($holderPage);
$controller->setRequest($this->getRequest());
$controller->doInit();
return $controller;
} | Prepare the controller for handling the response to this request
@param string $title Title to use
@return Controller | getResponseController | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function generateTabbedFormSet($forms)
{
if (count($forms ?? []) === 1) {
return $forms;
}
$viewData = new ArrayData([
'Forms' => new ArrayList($forms),
]);
return $viewData->renderWith(
$this->getTemplatesFor('MultiAuthenticatorTabbedForms')
);
} | Combine the given forms into a formset with a tabbed interface
@param array|Form[] $forms
@return string | generateTabbedFormSet | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function getSessionMessage(&$messageType = null)
{
$session = $this->getRequest()->getSession();
$message = $session->get('Security.Message.message');
$messageType = null;
if (empty($message)) {
return null;
}
$messageType = $session->get('Security.Message.type');
$messageCast = $session->get('Security.Message.cast');
if ($messageCast !== ValidationResult::CAST_HTML) {
$message = Convert::raw2xml($message);
}
return sprintf('<p class="message %s">%s</p>', Convert::raw2att($messageType), $message);
} | Get the HTML Content for the $Content area during login
@param string $messageType Type of message, if available, passed back to caller (by reference)
@return string Message in HTML format | getSessionMessage | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function setSessionMessage(
$message,
$messageType = ValidationResult::TYPE_WARNING,
$messageCast = ValidationResult::CAST_TEXT
) {
Controller::curr()
->getRequest()
->getSession()
->set("Security.Message.message", $message)
->set("Security.Message.type", $messageType)
->set("Security.Message.cast", $messageCast);
} | Set the next message to display for the security login page. Defaults to warning
@param string $message Message
@param string $messageType Message type. One of ValidationResult::TYPE_*
@param string $messageCast Message cast. One of ValidationResult::CAST_* | setSessionMessage | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function aggregateTabbedForms(array $results)
{
$forms = [];
foreach ($results as $authName => $singleResult) {
// The result *must* be an array with a Form key
if (!is_array($singleResult) || !isset($singleResult['Form'])) {
user_error('Authenticator "' . $authName . '" doesn\'t support tabbed forms', E_USER_WARNING);
continue;
}
$forms[] = $singleResult['Form'];
}
if (!$forms) {
throw new \LogicException('No authenticators found compatible with tabbed forms');
}
return [
'Forms' => ArrayList::create($forms),
'Form' => $this->generateTabbedFormSet($forms)
];
} | Aggregate tabbed forms from each handler to fragments ready to be rendered.
@param array $results
@return array | aggregateTabbedForms | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function aggregateAuthenticatorResponses($results)
{
$error = false;
$result = null;
foreach ($results as $authName => $singleResult) {
if (($singleResult instanceof HTTPResponse) ||
(is_array($singleResult) &&
(isset($singleResult['Content']) || isset($singleResult['Form'])))
) {
// return the first successful response
return $singleResult;
} else {
// Not a valid response
$error = true;
}
}
if ($error) {
throw new \LogicException('No authenticators found compatible with logout operation');
}
return $result;
} | We have three possible scenarios.
We get back Content (e.g. Password Reset)
We get back a Form (no token set for logout)
We get back a HTTPResponse, telling us to redirect.
Return the first one, which is the default response, as that covers all required scenarios
@param array $results
@return array|HTTPResponse | aggregateAuthenticatorResponses | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function delegateToMultipleHandlers(array $handlers, $title, array $templates, callable $aggregator)
{
// Simpler case for a single authenticator
if (count($handlers ?? []) === 1) {
return $this->delegateToHandler(array_values($handlers)[0], $title, $templates);
}
// Process each of the handlers
$results = array_map(
function (RequestHandler $handler) {
return $handler->handleRequest($this->getRequest());
},
$handlers ?? []
);
$response = call_user_func_array($aggregator, [$results]);
// The return could be a HTTPResponse, in which we don't want to call the render
if (is_array($response)) {
return $this->renderWrappedController($title, $response, $templates);
}
return $response;
} | Delegate to a number of handlers and aggregate the results. This is used, for example, to
build the log-in page where there are multiple authenticators active.
If a single handler is passed, delegateToHandler() will be called instead
@param array|RequestHandler[] $handlers
@param string $title The title of the form
@param array $templates
@param callable $aggregator
@return array|HTTPResponse|RequestHandler|DBHTMLText|string | delegateToMultipleHandlers | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function delegateToHandler(RequestHandler $handler, $title, array $templates = [])
{
$result = $handler->handleRequest($this->getRequest());
// Return the customised controller - may be used to render a Form (e.g. login form)
if (is_array($result)) {
$result = $this->renderWrappedController($title, $result, $templates);
}
return $result;
} | Delegate to another RequestHandler, rendering any fragment arrays into an appropriate.
controller.
@param RequestHandler $handler
@param string $title The title of the form
@param array $templates
@return array|HTTPResponse|RequestHandler|DBHTMLText|string | delegateToHandler | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
protected function renderWrappedController($title, array $fragments, array $templates)
{
$controller = $this->getResponseController($title);
// if the controller calls Director::redirect(), this will break early
if (($response = $controller->getResponse()) && $response->isFinished()) {
return $response;
}
// Handle any form messages from validation, etc.
$messageType = '';
$message = $this->getSessionMessage($messageType);
// We've displayed the message in the form output, so reset it for the next run.
static::clearSessionMessage();
// Ensure title is present - in case getResponseController() didn't return a page controller
$fragments = array_merge(['Title' => $title], $fragments);
if ($message) {
$messageResult = [
'Content' => DBField::create_field('HTMLFragment', $message),
'Message' => DBField::create_field('HTMLFragment', $message),
'MessageType' => $messageType
];
$fragments = array_merge($fragments, $messageResult);
}
return $controller->customise($fragments)->renderWith($templates);
} | Render the given fragments into a security page controller with the given title.
@param string $title string The title to give the security page
@param array $fragments A map of objects to render into the page, e.g. "Form"
@param array $templates An array of templates to use for the render
@return HTTPResponse|DBHTMLText | renderWrappedController | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function getPasswordResetLink($member, $autologinToken)
{
$autologinToken = urldecode($autologinToken ?? '');
return static::singleton()->Link('changepassword') . "?m={$member->ID}&t=$autologinToken";
} | Create a link to the password reset form.
GET parameters used:
- m: member ID
- t: plaintext token
@param Member $member Member object associated with this link.
@param string $autologinToken The auto login token.
@return string | getPasswordResetLink | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function getTemplatesFor($action)
{
$templates = SSViewer::get_templates_by_class(static::class, "_{$action}", __CLASS__);
return array_merge(
$templates,
[
"Security_{$action}",
"Security",
$this->config()->get("template_main"),
"BlankPage"
]
);
} | Determine the list of templates to use for rendering the given action.
@param string $action
@return array Template list | getTemplatesFor | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function encrypt_password($password, $salt = null, $algorithm = null, $member = null)
{
// Fall back to the default encryption algorithm
if (!$algorithm) {
$algorithm = static::config()->get('password_encryption_algorithm');
}
$encryptor = PasswordEncryptor::create_for_algorithm($algorithm);
// New salts will only need to be generated if the password is hashed for the first time
$salt = ($salt) ? $salt : $encryptor->salt($password);
return [
'password' => $encryptor->encrypt($password, $salt, $member),
'salt' => $salt,
'algorithm' => $algorithm,
'encryptor' => $encryptor
];
} | Encrypt a password according to the current password encryption settings.
If the settings are so that passwords shouldn't be encrypted, the
result is simple the clear text password with an empty salt except when
a custom algorithm ($algorithm parameter) was passed.
@param string $password The password to encrypt
@param string $salt Optional: The salt to use. If it is not passed, but
needed, the method will automatically create a
random salt that will then be returned as return value.
@param string $algorithm Optional: Use another algorithm to encrypt the
password (so that the encryption algorithm can be changed over the time).
@param Member $member Optional
@return mixed Returns an associative array containing the encrypted
password and the used salt in the form:
<code>
array(
'password' => string,
'salt' => string,
'algorithm' => string,
'encryptor' => PasswordEncryptor instance
)
</code>
If the passed algorithm is invalid, FALSE will be returned.
@throws PasswordEncryptor_NotFoundException
@see encrypt_passwords() | encrypt_password | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function clear_database_is_ready()
{
Security::$database_is_ready = null;
Security::$force_database_is_ready = null;
} | Resets the database_is_ready cache | clear_database_is_ready | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function force_database_is_ready($isReady)
{
Security::$force_database_is_ready = $isReady;
} | For the database_is_ready call to return a certain value - used for testing
@param bool $isReady | force_database_is_ready | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function set_ignore_disallowed_actions($flag)
{
Security::$ignore_disallowed_actions = $flag;
} | Set to true to ignore access to disallowed actions, rather than returning permission failure
Note that this is just a flag that other code needs to check with Security::ignore_disallowed_actions()
@param bool $flag True or false | set_ignore_disallowed_actions | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function login_url()
{
return Controller::join_links(Director::baseURL(), static::config()->get('login_url'));
} | Get the URL of the log-in page.
To update the login url use the "Security.login_url" config setting.
@return string | login_url | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function logout_url()
{
$logoutUrl = Controller::join_links(Director::baseURL(), static::config()->get('logout_url'));
return SecurityToken::inst()->addToUrl($logoutUrl);
} | Get the URL of the logout page.
To update the logout url use the "Security.logout_url" config setting.
@return string | logout_url | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function lost_password_url()
{
return Controller::join_links(Director::baseURL(), static::config()->get('lost_password_url'));
} | Get the URL of the logout page.
To update the logout url use the "Security.logout_url" config setting.
@return string | lost_password_url | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public static function get_template_global_variables()
{
return [
"LoginURL" => "login_url",
"LogoutURL" => "logout_url",
"LostPasswordURL" => "lost_password_url",
"CurrentMember" => "getCurrentUser",
"currentUser" => "getCurrentUser"
];
} | Defines global accessible templates variables.
@return array | get_template_global_variables | php | silverstripe/silverstripe-framework | src/Security/Security.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Security.php | BSD-3-Clause |
public function getIsloggedIn()
{
return !!Security::getCurrentUser();
} | Check if there is a logged in member
@return bool | getIsloggedIn | php | silverstripe/silverstripe-framework | src/Security/CMSSecurity.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/CMSSecurity.php | BSD-3-Clause |
protected function redirectToExternalLogin()
{
$loginURL = Security::create()->Link('login');
$loginURLATT = Convert::raw2att($loginURL);
$loginURLJS = Convert::raw2js($loginURL);
$message = _t(
__CLASS__ . '.INVALIDUSER',
'<p>Invalid user. <a target="_top" href="{link}">Please re-authenticate here</a> to continue.</p>',
'Message displayed to user if their session cannot be restored',
['link' => $loginURLATT]
);
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setBody(<<<PHP
<!DOCTYPE html>
<html><body>
$message
<script type="application/javascript">
setTimeout(function(){top.location.href = "$loginURLJS";}, 0);
</script>
</body></html>
PHP
);
$this->setResponse($response);
return $response;
} | Redirects the user to the external login page
@return HTTPResponse | redirectToExternalLogin | php | silverstripe/silverstripe-framework | src/Security/CMSSecurity.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/CMSSecurity.php | BSD-3-Clause |
public function enabled()
{
// Disable shortcut
if (!static::config()->get('reauth_enabled')) {
return false;
}
return count($this->getApplicableAuthenticators(Authenticator::CMS_LOGIN) ?? []) > 0;
} | Determine if CMSSecurity is enabled
@return bool | enabled | php | silverstripe/silverstripe-framework | src/Security/CMSSecurity.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/CMSSecurity.php | BSD-3-Clause |
public function success()
{
// Ensure member is properly logged in
if (!Security::getCurrentUser() || !class_exists(AdminRootController::class)) {
return $this->redirectToExternalLogin();
}
// Get redirect url
$controller = $this->getResponseController(_t(__CLASS__ . '.SUCCESS', 'Success'));
$backURLs = [
$this->getRequest()->requestVar('BackURL'),
$this->getRequest()->getSession()->get('BackURL'),
Director::absoluteURL(AdminRootController::config()->get('url_base')),
];
$backURL = null;
foreach ($backURLs as $backURL) {
if ($backURL && Director::is_site_url($backURL)) {
break;
}
}
// Show login
$controller = $controller->customise([
'Content' => DBField::create_field(DBHTMLText::class, _t(
__CLASS__ . '.SUCCESSCONTENT',
'<p>Login success. If you are not automatically redirected ' . '<a target="_top" href="{link}">click here</a></p>',
'Login message displayed in the cms popup once a user has re-authenticated themselves',
['link' => Convert::raw2att($backURL)]
))
]);
return $controller->renderWith($this->getTemplatesFor('success'));
} | Given a successful login, tell the parent frame to close the dialog
@return HTTPResponse|DBField | success | php | silverstripe/silverstripe-framework | src/Security/CMSSecurity.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/CMSSecurity.php | BSD-3-Clause |
public function __construct($name, $permissions)
{
$this->name = $name;
$this->permissions = $permissions;
} | Constructor
@param string $name Text that could be used as label used in an
interface
@param array $permissions Associative array of permissions in this
permission group. The array indices are the
permission codes as used in
{@link Permission::check()}. The value is
suitable for using in an interface. | __construct | php | silverstripe/silverstripe-framework | src/Security/Permission_Group.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission_Group.php | BSD-3-Clause |
public function getName()
{
return $this->name;
} | Get the name of the permission group
@return string Name (label) of the permission group | getName | php | silverstripe/silverstripe-framework | src/Security/Permission_Group.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission_Group.php | BSD-3-Clause |
public function getPermissions()
{
return $this->permissions;
} | Get permissions
@return array Associative array of permissions in this permission
group. The array indices are the permission codes as
used in {@link Permission::check()}. The value is
suitable for using in an interface. | getPermissions | php | silverstripe/silverstripe-framework | src/Security/Permission_Group.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission_Group.php | BSD-3-Clause |
public function getForMember()
{
return $this->forMember;
} | Get the member this validator applies to.
@return Member | getForMember | php | silverstripe/silverstripe-framework | src/Security/Member_Validator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member_Validator.php | BSD-3-Clause |
public function setForMember(Member $value)
{
$this->forMember = $value;
return $this;
} | Set the Member this validator applies to.
@param Member $value
@return $this | setForMember | php | silverstripe/silverstripe-framework | src/Security/Member_Validator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member_Validator.php | BSD-3-Clause |
public function php($data)
{
$valid = parent::php($data);
$identifierField = (string)Member::config()->unique_identifier_field;
// Only validate identifier field if it's actually set. This could be the case if
// somebody removes `Email` from the list of required fields.
$id = isset($data['ID']) ? (int)$data['ID'] : 0;
if (isset($data[$identifierField])) {
if (!$id && ($ctrl = $this->form->getController())) {
// get the record when within GridField (Member editing page in CMS)
if ($ctrl instanceof GridFieldDetailForm_ItemRequest && $record = $ctrl->getRecord()) {
$id = $record->ID;
}
}
// If there's no ID passed via controller or form-data, use the assigned member (if available)
if (!$id && ($member = $this->getForMember())) {
$id = $member->exists() ? $member->ID : 0;
}
// set the found ID to the data array, so that extensions can also use it
$data['ID'] = $id;
$members = Member::get()->filter($identifierField, $data[$identifierField]);
if ($id) {
$members = $members->exclude('ID', $id);
}
if ($members->count() > 0) {
$this->validationError(
$identifierField,
_t(
'SilverStripe\\Security\\Member.VALIDATIONMEMBEREXISTS',
'A member already exists with the same {identifier}',
['identifier' => Member::singleton()->fieldLabel($identifierField)]
),
'required'
);
$valid = false;
}
}
$currentUser = Security::getCurrentUser();
if ($currentUser
&& $id
&& $id === (int)$currentUser->ID
&& Permission::checkMember($currentUser, 'ADMIN')
) {
$stillAdmin = true;
if (!isset($data['DirectGroups'])) {
$stillAdmin = false;
} else {
$adminGroups = array_intersect(
$data['DirectGroups'] ?? [],
Permission::get_groups_by_permission('ADMIN')->column()
);
if (count($adminGroups ?? []) === 0) {
$stillAdmin = false;
}
}
if (!$stillAdmin) {
$this->validationError(
'DirectGroups',
_t(
'SilverStripe\\Security\\Member.VALIDATIONADMINLOSTACCESS',
'Cannot remove all admin groups from your profile'
),
'required'
);
}
}
// Execute the validators on the extensions
$results = $this->extend('updatePHP', $data, $this->form);
$results[] = $valid;
return min($results);
} | Check if the submitted member data is valid (server-side)
Check if a member with that email doesn't already exist, or if it does
that it is this member.
@param array $data Submitted data
@return bool Returns TRUE if the submitted data is valid, otherwise
FALSE. | php | php | silverstripe/silverstripe-framework | src/Security/Member_Validator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member_Validator.php | BSD-3-Clause |
public static function get_cost()
{
return PasswordEncryptor_Blowfish::$cost;
} | Gets the cost that is set for the blowfish algorithm
@return int | get_cost | php | silverstripe/silverstripe-framework | src/Security/PasswordEncryptor_Blowfish.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordEncryptor_Blowfish.php | BSD-3-Clause |
public function checkAEncryptionLevel()
{
// Test hashes taken from
// http://cvsweb.openwall.com/cgi/cvsweb.cgi/~checkout~/Owl/packages/glibc
// /crypt_blowfish/wrapper.c?rev=1.9.2.1;content-type=text%2Fplain
$xOrY = crypt("\xff\xa334\xff\xff\xff\xa3345", '$2a$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi')
== '$2a$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi';
$yOrA = crypt("\xa3", '$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq')
== '$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq';
if ($xOrY && $yOrA) {
return 'y';
} elseif ($xOrY) {
return 'x';
} elseif ($yOrA) {
return 'a';
}
return 'unknown';
} | The algorithm returned by using '$2a$' is not consistent -
it might be either the correct (y), incorrect (x) or mostly-correct (a)
version, depending on the version of PHP and the operating system,
so we need to test it. | checkAEncryptionLevel | php | silverstripe/silverstripe-framework | src/Security/PasswordEncryptor_Blowfish.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordEncryptor_Blowfish.php | BSD-3-Clause |
public function salt($password, $member = null)
{
$generator = new RandomGenerator();
return sprintf('%02d', PasswordEncryptor_Blowfish::$cost) . '$' . substr($generator->randomToken('sha1') ?? '', 0, 22);
} | PasswordEncryptor_Blowfish::$cost param is forced to be two digits with leading zeroes for ints 4-9
@param string $password
@param Member $member
@return string | salt | php | silverstripe/silverstripe-framework | src/Security/PasswordEncryptor_Blowfish.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordEncryptor_Blowfish.php | BSD-3-Clause |
public function populateDefaults()
{
parent::populateDefaults();
$this->Locale = i18n::config()->get('default_locale');
} | Ensure the locale is set to something sensible by default. | populateDefaults | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function isDefaultAdmin()
{
return DefaultAdminService::isDefaultAdmin($this->Email);
} | Check if this user is the currently configured default admin
@return bool | isDefaultAdmin | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function validateCanLogin(ValidationResult &$result = null)
{
$result = $result ?: ValidationResult::create();
if ($this->isLockedOut()) {
$result->addError(
_t(
__CLASS__ . '.ERRORLOCKEDOUT2',
'Your account has been temporarily disabled because of too many failed attempts at ' . 'logging in. Please try again in {count} minutes.',
null,
['count' => static::config()->get('lock_out_delay_mins')]
)
);
}
$this->extend('canLogIn', $result);
return $result;
} | Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid
one with error messages to display if the member is locked out.
You can hook into this with a "canLogIn" method on an attached extension.
@param ValidationResult $result Optional result to add errors to
@return ValidationResult | validateCanLogin | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function isLockedOut()
{
/** @var DBDatetime $lockedOutUntilObj */
$lockedOutUntilObj = $this->dbObject('LockedOutUntil');
if ($lockedOutUntilObj->InFuture()) {
return true;
}
$maxAttempts = $this->config()->get('lock_out_after_incorrect_logins');
if ($maxAttempts <= 0) {
return false;
}
$attempts = LoginAttempt::getByEmail($this->Email)
->sort('Created', 'DESC')
->limit($maxAttempts);
if ($attempts->count() < $maxAttempts) {
return false;
}
foreach ($attempts as $attempt) {
if ($attempt->Status === 'Success') {
return false;
}
}
// Calculate effective LockedOutUntil
/** @var DBDatetime $firstFailureDate */
$firstFailureDate = $attempts->first()->dbObject('Created');
$maxAgeSeconds = $this->config()->get('lock_out_delay_mins') * 60;
$lockedOutUntil = $firstFailureDate->getTimestamp() + $maxAgeSeconds;
$now = DBDatetime::now()->getTimestamp();
if ($now < $lockedOutUntil) {
return true;
}
return false;
} | Returns true if this user is locked out
@return bool | isLockedOut | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function beforeMemberLoggedIn()
{
$this->extend('beforeMemberLoggedIn');
} | Called before a member is logged in via session/cookie/etc | beforeMemberLoggedIn | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function afterMemberLoggedIn()
{
// Clear the incorrect log-in count
$this->registerSuccessfulLogin();
$this->LockedOutUntil = null;
$this->regenerateTempID();
$this->write();
// Audit logging hook
$this->extend('afterMemberLoggedIn');
} | Called after a member is logged in via session/cookie/etc | afterMemberLoggedIn | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function regenerateTempID()
{
$generator = new RandomGenerator();
$lifetime = static::config()->get('temp_id_lifetime');
$this->TempIDHash = $generator->randomToken('sha1');
$this->TempIDExpired = $lifetime
? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime)
: null;
$this->write();
} | Trigger regeneration of TempID.
This should be performed any time the user presents their normal identification (normally Email)
and is successfully authenticated. | regenerateTempID | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function beforeMemberLoggedOut(HTTPRequest $request = null)
{
$this->extend('beforeMemberLoggedOut', $request);
} | Audit logging hook, called before a member is logged out
@param HTTPRequest|null $request | beforeMemberLoggedOut | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function afterMemberLoggedOut(HTTPRequest $request = null)
{
$this->extend('afterMemberLoggedOut', $request);
} | Audit logging hook, called after a member is logged out
@param HTTPRequest|null $request | afterMemberLoggedOut | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function encryptWithUserSettings($string)
{
if (!$string) {
return null;
}
// If the algorithm or salt is not available, it means we are operating
// on legacy account with unhashed password. Do not hash the string.
if (!$this->PasswordEncryption || !$this->Salt) {
return $string;
}
$e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption);
return $e->encrypt($string, $this->Salt);
} | Utility for generating secure password hashes for this member.
@param string $string
@return string
@throws PasswordEncryptor_NotFoundException | encryptWithUserSettings | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function generateAutologinTokenAndStoreHash()
{
$lifetime = $this->config()->auto_login_token_lifetime;
do {
$generator = new RandomGenerator();
$token = $generator->randomToken();
$hash = $this->encryptWithUserSettings($token);
} while (DataObject::get_one(Member::class, [
'"Member"."AutoLoginHash"' => $hash
]));
$this->AutoLoginHash = $hash;
$this->AutoLoginExpired = date('Y-m-d H:i:s', time() + $lifetime);
$this->write();
return $token;
} | Generate an auto login token which can be used to reset the password,
at the same time hashing it and storing in the database.
@return string Token that should be passed to the client (but NOT persisted). | generateAutologinTokenAndStoreHash | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function validateAutoLoginToken($autologinToken)
{
$hash = $this->encryptWithUserSettings($autologinToken);
$member = Member::member_from_autologinhash($hash, false);
return (bool)$member;
} | Check the token against the member.
@param string $autologinToken
@returns bool Is token valid? | validateAutoLoginToken | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public static function member_from_autologinhash($hash, $login = false)
{
$member = static::get()->filter([
'AutoLoginHash' => $hash,
'AutoLoginExpired:GreaterThan' => DBDatetime::now()->getValue(),
])->first();
if ($login && $member) {
Injector::inst()->get(IdentityStore::class)->logIn($member);
}
return $member;
} | Return the member for the auto login hash
@param string $hash The hash key
@param bool $login Should the member be logged in?
@return Member|null the matching member, if valid or null | member_from_autologinhash | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public static function member_from_tempid($tempid)
{
$members = static::get()
->filter('TempIDHash', $tempid);
// Exclude expired
if (static::config()->get('temp_id_lifetime')) {
$members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue());
}
return $members->first();
} | Find a member record with the given TempIDHash value
@param string $tempid
@return Member|null the matching member, if valid or null | member_from_tempid | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getMemberFormFields()
{
$fields = parent::getFrontEndFields();
$fields->replaceField('Password', $this->getMemberPasswordField());
$fields->replaceField('Locale', new DropdownField(
'Locale',
$this->fieldLabel('Locale'),
i18n::getSources()->getKnownLocales()
));
$fields->removeByName(static::config()->get('hidden_fields'));
$fields->removeByName('FailedLoginCount');
$this->extend('updateMemberFormFields', $fields);
return $fields;
} | Returns the fields for the member form - used in the registration/profile module.
It should return fields that are editable by the admin and the logged-in user.
@return FieldList Returns a {@link FieldList} containing the fields for
the member form. | getMemberFormFields | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getMemberPasswordField()
{
$editingPassword = $this->isInDB();
$label = $editingPassword
? _t(__CLASS__ . '.EDIT_PASSWORD', 'New Password')
: $this->fieldLabel('Password');
$password = ConfirmedPasswordField::create(
'Password',
$label,
null,
null,
$editingPassword
);
// If editing own password, require confirmation of existing
if ($editingPassword && $this->ID == Security::getCurrentUser()->ID) {
$password->setRequireExistingPassword(true);
}
if (!$editingPassword) {
$password->setCanBeEmpty(true);
$password->setRandomPasswordCallback(Closure::fromCallable([$this, 'generateRandomPassword']));
// explicitly set "require strong password" to false because its regex in ConfirmedPasswordField
// is too restrictive for generateRandomPassword() which will add in non-alphanumeric characters
$password->setRequireStrongPassword(false);
}
$this->extend('updateMemberPasswordField', $password);
return $password;
} | Builds "Change / Create Password" field for this member
@return ConfirmedPasswordField | getMemberPasswordField | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getValidator()
{
$validator = Member_Validator::create();
$validator->setForMember($this);
$this->extend('updateValidator', $validator);
return $validator;
} | Returns the {@link RequiredFields} instance for the Member object. This
Validator is used when saving a {@link CMSProfileController} or added to
any form responsible for saving a users data.
To customize the required fields, add a {@link DataExtension} to member
calling the `updateValidator()` method.
@return Member_Validator | getValidator | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function onChangeGroups($ids)
{
// Ensure none of these match disallowed list
$disallowedGroupIDs = $this->disallowedGroups();
return count(array_intersect($ids ?? [], $disallowedGroupIDs)) == 0;
} | Filter out admin groups to avoid privilege escalation,
If any admin groups are requested, deny the whole save operation.
@param array $ids Database IDs of Group records
@return bool True if the change can be accepted | onChangeGroups | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
protected function disallowedGroups()
{
// unless the current user is an admin already OR the logged in user is an admin
if (Permission::check('ADMIN') || Permission::checkMember($this, 'ADMIN')) {
return [];
}
// Non-admins may not belong to admin groups
return Permission::get_groups_by_permission('ADMIN')->column('ID');
} | List of group IDs this user is disallowed from
@return int[] List of group IDs | disallowedGroups | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function inGroups($groups, $strict = false)
{
if ($groups) {
foreach ($groups as $group) {
if ($this->inGroup($group, $strict)) {
return true;
}
}
}
return false;
} | Check if the member is in one of the given groups.
@param array|SS_List $groups Collection of {@link Group} DataObjects to check
@param boolean $strict Only determine direct group membership if set to true (Default: false)
@return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE. | inGroups | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function addToGroupByCode($groupcode, $title = "")
{
$group = DataObject::get_one(Group::class, [
'"Group"."Code"' => $groupcode
]);
if ($group) {
$this->Groups()->add($group);
} else {
if (!$title) {
$title = $groupcode;
}
$group = new Group();
$group->Code = $groupcode;
$group->Title = $title;
$group->write();
$this->Groups()->add($group);
}
} | Adds the member to a group. This will create the group if the given
group code does not return a valid group object.
@param string $groupcode
@param string $title Title of the group | addToGroupByCode | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function removeFromGroupByCode($groupcode)
{
$group = Group::get()->filter(['Code' => $groupcode])->first();
if ($group) {
$this->Groups()->remove($group);
}
} | Removes a member from a group.
@param string $groupcode | removeFromGroupByCode | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getLastName()
{
return $this->Surname;
} | Simple proxy method to get the Surname property of the member
@return string | getLastName | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getName()
{
$name = ($this->Surname) ? trim($this->FirstName . ' ' . $this->Surname) : $this->FirstName;
$this->extend('updateName', $name);
return $name;
} | Get the complete name of the member
@return string Returns the first- and surname of the member. | getName | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function setName($name)
{
$nameParts = explode(' ', $name ?? '');
$this->Surname = array_pop($nameParts);
$this->FirstName = join(' ', $nameParts);
} | Set first- and surname
This method assumes that the last part of the name is the surname, e.g.
<i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i>
@param string $name The name | setName | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getDateFormat()
{
$formatter = new IntlDateFormatter(
$this->getLocale(),
IntlDateFormatter::MEDIUM,
IntlDateFormatter::NONE
);
$format = $formatter->getPattern();
$this->extend('updateDateFormat', $format);
return $format;
} | Return the date format based on the user's chosen locale,
falling back to the default format defined by the i18n::config()->get('default_locale') config setting.
@return string ISO date format | getDateFormat | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getLocale()
{
$locale = $this->getField('Locale');
if ($locale) {
return $locale;
}
return i18n::config()->get('default_locale');
} | Get user locale, falling back to the configured default locale | getLocale | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getTimeFormat()
{
$formatter = new IntlDateFormatter(
$this->getLocale(),
IntlDateFormatter::NONE,
IntlDateFormatter::MEDIUM
);
$format = $formatter->getPattern();
$this->extend('updateTimeFormat', $format);
return $format;
} | Return the time format based on the user's chosen locale,
falling back to the default format defined by the i18n::config()->get('default_locale') config setting.
@return string ISO date format | getTimeFormat | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function Groups()
{
$groups = Member_GroupSet::create(Group::class, 'Group_Members', 'GroupID', 'MemberID');
$groups = $groups->forForeignID($this->ID);
$this->extend('updateGroups', $groups);
return $groups;
} | Get a "many-to-many" map that holds for all members their group memberships,
including any parent groups where membership is implied.
Use {@link DirectGroups()} to only retrieve the group relations without inheritance.
@return Member_Groupset | Groups | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function memberNotInGroups($groupList, $memberGroups = null)
{
if (!$memberGroups) {
$memberGroups = $this->Groups();
}
foreach ($memberGroups as $group) {
if (in_array($group->Code, $groupList ?? [])) {
$index = array_search($group->Code, $groupList ?? []);
unset($groupList[$index]);
}
}
return $groupList;
} | Get the groups in which the member is NOT in
When passed an array of groups, and a component set of groups, this
function will return the array of groups the member is NOT in.
@param array $groupList An array of group code names.
@param array $memberGroups A component set of groups (if set to NULL,
$this->groups() will be used)
@return array Groups in which the member is NOT in. | memberNotInGroups | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function canView($member = null)
{
//get member
if (!$member) {
$member = Security::getCurrentUser();
}
//check for extensions, we do this first as they can overrule everything
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
//need to be logged in and/or most checks below rely on $member being a Member
if (!$member) {
return false;
}
// members can usually view their own record
if ($this->ID == $member->ID) {
return true;
}
//standard check
return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin');
} | Users can view their own record.
Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions.
This is likely to be customized for social sites etc. with a looser permission model.
@param Member $member
@return bool | canView | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function canEdit($member = null)
{
//get member
if (!$member) {
$member = Security::getCurrentUser();
}
//check for extensions, we do this first as they can overrule everything
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
//need to be logged in and/or most checks below rely on $member being a Member
if (!$member) {
return false;
}
// HACK: we should not allow for an non-Admin to edit an Admin
if (!Permission::checkMember($member, 'ADMIN') && Permission::checkMember($this, 'ADMIN')) {
return false;
}
// members can usually edit their own record
if ($this->ID == $member->ID) {
return true;
}
//standard check
return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin');
} | Users can edit their own record.
Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
@param Member $member
@return bool | canEdit | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function canDelete($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
//check for extensions, we do this first as they can overrule everything
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
//need to be logged in and/or most checks below rely on $member being a Member
if (!$member) {
return false;
}
// Members are not allowed to remove themselves,
// since it would create inconsistencies in the admin UIs.
if ($this->ID && $member->ID == $this->ID) {
return false;
}
// HACK: if you want to delete a member, you have to be a member yourself.
// this is a hack because what this should do is to stop a user
// deleting a member who has more privileges (e.g. a non-Admin deleting an Admin)
if (Permission::checkMember($this, 'ADMIN')) {
if (!Permission::checkMember($member, 'ADMIN')) {
return false;
}
}
//standard check
return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin');
} | Users can edit their own record.
Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
@param Member $member
@return bool | canDelete | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function changePassword($password, $write = true)
{
$this->Password = $password;
$result = $this->validate();
$this->extend('onBeforeChangePassword', $password, $result);
if ($result->isValid()) {
$this->AutoLoginHash = null;
if ($write) {
$this->write();
}
}
$this->extend('onAfterChangePassword', $password, $result);
return $result;
} | Change password. This will cause rehashing according to the `PasswordEncryption` property via the
`onBeforeWrite()` method. This method will allow extensions to perform actions and augment the validation
result if required before the password is written and can check it after the write also.
`onBeforeWrite()` will encrypt the password prior to writing.
@param string $password Cleartext password
@param bool $write Whether to write the member afterwards
@return ValidationResult | changePassword | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
protected function encryptPassword()
{
// reset salt so that it gets regenerated - this will invalidate any persistent login cookies
// or other information encrypted with this Member's settings (see Member::encryptWithUserSettings)
$this->Salt = '';
// Password was changed: encrypt the password according the settings
$encryption_details = Security::encrypt_password(
$this->Password,
$this->Salt,
$this->isChanged('PasswordEncryption') ? $this->PasswordEncryption : null,
$this
);
// Overwrite the Password property with the hashed value
$this->Password = $encryption_details['password'];
$this->Salt = $encryption_details['salt'];
$this->PasswordEncryption = $encryption_details['algorithm'];
// If we haven't manually set a password expiry
if (!$this->isChanged('PasswordExpiry')) {
// then set it for us
if (static::config()->get('password_expiry_days')) {
$this->PasswordExpiry = date('Y-m-d', time() + 86400 * static::config()->get('password_expiry_days'));
} else {
$this->PasswordExpiry = null;
}
}
return $this;
} | Takes a plaintext password (on the Member object) and encrypts it
@return $this | encryptPassword | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function registerFailedLogin()
{
$lockOutAfterCount = static::config()->get('lock_out_after_incorrect_logins');
if ($lockOutAfterCount) {
// Keep a tally of the number of failed log-ins so that we can lock people out
++$this->FailedLoginCount;
if ($this->FailedLoginCount >= $lockOutAfterCount) {
$lockoutMins = static::config()->get('lock_out_delay_mins');
$this->LockedOutUntil = date('Y-m-d H:i:s', DBDatetime::now()->getTimestamp() + $lockoutMins * 60);
$this->FailedLoginCount = 0;
}
}
$this->extend('registerFailedLogin');
$this->write();
} | Tell this member that someone made a failed attempt at logging in as them.
This can be used to lock the user out temporarily if too many failed attempts are made. | registerFailedLogin | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function registerSuccessfulLogin()
{
if (static::config()->get('lock_out_after_incorrect_logins')) {
// Forgive all past login failures
$this->FailedLoginCount = 0;
$this->LockedOutUntil = null;
$this->write();
}
} | Tell this member that a successful login has been made | registerSuccessfulLogin | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function getHtmlEditorConfigForCMS()
{
$currentName = '';
$currentPriority = 0;
// If we don't have a custom config, no need to look in all groups
$editorConfigMap = HTMLEditorConfig::get_available_configs_map();
$editorConfigCount = count($editorConfigMap);
if ($editorConfigCount === 0) {
return 'cms';
}
if ($editorConfigCount === 1) {
return key($editorConfigMap);
}
foreach ($this->Groups() as $group) {
$configName = $group->HtmlEditorConfig;
if ($configName) {
$config = HTMLEditorConfig::get($group->HtmlEditorConfig);
if ($config && $config->getOption('priority') > $currentPriority) {
$currentName = $configName;
$currentPriority = $config->getOption('priority');
}
}
}
// If can't find a suitable editor, just default to cms
return $currentName ? $currentName : 'cms';
} | Get the HtmlEditorConfig for this user to be used in the CMS.
This is set by the group. If multiple configurations are set,
the one with the highest priority wins.
@return string | getHtmlEditorConfigForCMS | php | silverstripe/silverstripe-framework | src/Security/Member.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member.php | BSD-3-Clause |
public function __construct($controller, $name, $fields = null, $actions = null)
{
$backURL = $controller->getBackURL()
?: $controller->getRequest()->getSession()->get('BackURL');
if (!$fields) {
$fields = $this->getFormFields();
}
if (!$actions) {
$actions = $this->getFormActions();
}
if ($backURL) {
$fields->push(HiddenField::create('BackURL', false, $backURL));
}
parent::__construct($controller, $name, $fields, $actions);
} | Constructor
@param RequestHandler $controller The parent controller, necessary to create the appropriate form action tag.
@param string $name The method on the controller that will return this form object.
@param FieldList|FormField $fields All of the fields in the form - a {@link FieldList} of
{@link FormField} objects.
@param FieldList|FormAction $actions All of the action buttons in the form - a {@link FieldList} of | __construct | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/ChangePasswordForm.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/ChangePasswordForm.php | BSD-3-Clause |
public function getFormFields()
{
$uniqueIdentifier = Member::config()->get('unique_identifier_field');
$label = Member::singleton()->fieldLabel($uniqueIdentifier);
if ($uniqueIdentifier === 'Email') {
$emailField = EmailField::create('Email', $label);
} else {
// This field needs to still be called Email, but we can re-label it
$emailField = TextField::create('Email', $label);
}
return FieldList::create($emailField);
} | Create a single EmailField form that has the capability
of using the MemberLoginForm Authenticator
@return FieldList | getFormFields | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordForm.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordForm.php | BSD-3-Clause |
public function getFormActions()
{
return FieldList::create(
FormAction::create(
'forgotPassword',
_t('SilverStripe\\Security\\Security.BUTTONSEND', 'Send me the password reset link')
)
);
} | Give the member a friendly button to push
@return FieldList | getFormActions | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordForm.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordForm.php | BSD-3-Clause |
public function logout()
{
$member = Security::getCurrentUser();
// If the user doesn't have a security token, show them a form where they can get one.
// This protects against nuisance CSRF attacks to log out users.
if ($member && !SecurityToken::inst()->checkRequest($this->getRequest())) {
Security::singleton()->setSessionMessage(
_t(
'SilverStripe\\Security\\Security.CONFIRMLOGOUT',
"Please click the button below to confirm that you wish to log out."
),
ValidationResult::TYPE_WARNING
);
return [
'Form' => $this->logoutForm()
];
}
return $this->doLogOut($member);
} | Log out form handler method
This method is called when the user clicks on "logout" on the form
created when the parameter <i>$checkCurrentUser</i> of the
{@link __construct constructor} was set to TRUE and the user was
currently logged in.
@return array|HTTPResponse | logout | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LogoutHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LogoutHandler.php | BSD-3-Clause |
public function Link($action = null)
{
$link = Controller::join_links($this->link, $action);
$this->extend('updateLink', $link, $action);
return $link;
} | Return a link to this request handler.
The link returned is supplied in the constructor
@param string|null $action
@return string | Link | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php | BSD-3-Clause |
public function lostpassword()
{
$message = _t(
'SilverStripe\\Security\\Security.NOTERESETPASSWORD',
'Enter your e-mail address and we will send you a link with which you can reset your password'
);
return [
'Content' => DBField::create_field('HTMLFragment', "<p>$message</p>"),
'Form' => $this->lostPasswordForm(),
];
} | URL handler for the initial lost-password screen
@return array | lostpassword | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php | BSD-3-Clause |
public function passwordsent()
{
$message = _t(
'SilverStripe\\Security\\Security.PASSWORDRESETSENTTEXT',
"Thank you. A reset link has been sent, provided an account exists for this email address."
);
return [
'Title' => _t(
'SilverStripe\\Security\\Security.PASSWORDRESETSENTHEADER',
"Password reset link sent"
),
'Content' => DBField::create_field('HTMLFragment', "<p>$message</p>"),
];
} | Show the "password sent" page, after a user has requested
to reset their password.
@return array | passwordsent | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php | BSD-3-Clause |
public function lostPasswordForm()
{
return LostPasswordForm::create(
$this,
$this->authenticatorClass,
'lostPasswordForm',
null,
null,
false
);
} | Factory method for the lost password form
@return Form Returns the lost password form | lostPasswordForm | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php | BSD-3-Clause |
public function redirectToLostPassword()
{
$lostPasswordLink = Security::singleton()->Link('lostpassword');
return $this->redirect($this->addBackURLParam($lostPasswordLink));
} | Redirect to password recovery form
@return HTTPResponse | redirectToLostPassword | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php | BSD-3-Clause |
protected function validateForgotPasswordData(array $data, LostPasswordForm $form)
{
if (empty($data['Email'])) {
$form->sessionMessage(
_t(
'SilverStripe\\Security\\Member.ENTEREMAIL',
'Please enter an email address to get a password reset link.'
),
'bad'
);
return $this->redirectToLostPassword();
}
} | Ensure that the user has provided an email address. Note that the "Email" key is specific to this
implementation, but child classes can override this method to use another unique identifier field
for validation.
@param array $data
@param LostPasswordForm $form
@return HTTPResponse|null | validateForgotPasswordData | php | silverstripe/silverstripe-framework | src/Security/MemberAuthenticator/LostPasswordHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.