code
stringlengths
17
247k
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
public static function check($code, $arg = "any", $member = null, $strict = true) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } return Permission::checkMember($member, $code, $arg, $strict); }
Check that the current member has the given permission. @param string|array $code Code of the permission to check (case-sensitive) @param string $arg Optional argument (e.g. a permissions for a specific page) @param int|Member $member Optional member instance or ID. If set to NULL, the permssion will be checked for the current user @param bool $strict Use "strict" checking (which means a permission will be granted if the key does not exist at all)? @return int|bool The ID of the permission record if the permission exists; FALSE otherwise. If "strict" checking is disabled, TRUE will be returned if the permission does not exist at all.
check
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function reset() { Permission::$cache_permissions = []; }
Flush the permission cache, for example if you have edited group membership or a permission record.
reset
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function permissions_for_member($memberID) { $groupList = Permission::groupList($memberID); if ($groupList) { $groupCSV = implode(", ", $groupList); $allowed = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" WHERE \"Type\" = " . Permission::GRANT_PERMISSION . " AND \"GroupID\" IN ($groupCSV) UNION SELECT \"Code\" FROM \"PermissionRoleCode\" PRC INNER JOIN \"PermissionRole\" PR ON PRC.\"RoleID\" = PR.\"ID\" INNER JOIN \"Group_Roles\" GR ON GR.\"PermissionRoleID\" = PR.\"ID\" WHERE \"GroupID\" IN ($groupCSV) ")->column() ?? []); $denied = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" WHERE \"Type\" = " . Permission::DENY_PERMISSION . " AND \"GroupID\" IN ($groupCSV) ")->column() ?? []); return array_diff($allowed ?? [], $denied); } return []; }
Get all the 'any' permission codes available to the given member. @param int $memberID @return array
permissions_for_member
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function groupList($memberID = null) { // Default to current member, with session-caching if (!$memberID) { $member = Security::getCurrentUser(); if ($member && isset($_SESSION['Permission_groupList'][$member->ID])) { return $_SESSION['Permission_groupList'][$member->ID]; } } else { $member = DataObject::get_by_id("SilverStripe\\Security\\Member", $memberID); } if ($member) { // Build a list of the IDs of the groups. Most of the heavy lifting // is done by Member::Groups // NOTE: This isn't efficient; but it's called once per session so // it's a low priority to fix. $groups = $member->Groups(); $groupList = []; if ($groups) { foreach ($groups as $group) { $groupList[] = $group->ID; } } // Session caching if (!$memberID) { $_SESSION['Permission_groupList'][$member->ID] = $groupList; } return isset($groupList) ? $groupList : null; } return null; }
Get the list of groups that the given member belongs to. Call without an argument to get the groups that the current member belongs to. In this case, the results will be session-cached. @param int $memberID The ID of the member. Leave blank for the current member. @return array Returns a list of group IDs to which the member belongs to or NULL.
groupList
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function get_groups_by_permission($codes) { $codeParams = is_array($codes) ? $codes : [$codes]; $codeClause = DB::placeholders($codeParams); // Via Roles are groups that have the permission via a role return Group::get() ->where([ "\"PermissionRoleCode\".\"Code\" IN ($codeClause) OR \"Permission\".\"Code\" IN ($codeClause)" => array_merge($codeParams, $codeParams) ]) ->leftJoin('Permission', "\"Permission\".\"GroupID\" = \"Group\".\"ID\"") ->leftJoin('Group_Roles', "\"Group_Roles\".\"GroupID\" = \"Group\".\"ID\"") ->leftJoin('PermissionRole', "\"Group_Roles\".\"PermissionRoleID\" = \"PermissionRole\".\"ID\"") ->leftJoin('PermissionRoleCode', "\"PermissionRoleCode\".\"RoleID\" = \"PermissionRole\".\"ID\""); }
Return all of the groups that have one of the given permission codes @param array|string $codes Either a single permission code, or an array of permission codes @return SS_List The matching group objects
get_groups_by_permission
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function sort_permissions($a, $b) { if ($a['sort'] == $b['sort']) { // Same sort value, do alpha instead return strcmp($a['name'] ?? '', $b['name'] ?? ''); } else { // Just numeric. return $a['sort'] < $b['sort'] ? -1 : 1; } }
Sort permissions based on their sort value, or name @param array $a @param array $b @return int
sort_permissions
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function protect_entire_site($protect = true, $code = BasicAuth::AUTH_PERMISSION, $message = null) { static::config() ->set('entire_site_protected', $protect) ->set('entire_site_protected_code', $code); if ($message) { static::config()->set('entire_site_protected_message', $message); } }
Enable protection of all requests handed by SilverStripe with basic authentication. This log-in uses the Member database for authentication, but doesn't interfere with the regular log-in form. This can be useful for test sites, where you want to hide the site away from prying eyes, but still be able to test the regular log-in features of the site. You can also enable this feature by adding this line to your .env. Set this to a permission code you wish to require: `SS_USE_BASIC_AUTH=ADMIN` CAUTION: Basic Auth is an oudated security measure which passes credentials without encryption over the network. It is considered insecure unless this connection itself is secured (via HTTPS). It also doesn't prevent access to web requests which aren't handled via SilverStripe (e.g. published assets). Consider using additional authentication and authorisation measures to secure access (e.g. IP whitelists). @param boolean $protect Set this to false to disable protection. @param string $code {@link Permission} code that is required from the user. Defaults to "ADMIN". Set to NULL to just require a valid login, regardless of the permission codes a user has. @param string $message
protect_entire_site
php
silverstripe/silverstripe-framework
src/Security/BasicAuth.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/BasicAuth.php
BSD-3-Clause
public static function setDefaultAdmin($username, $password) { // don't overwrite if already set if (static::hasDefaultAdmin()) { throw new BadMethodCallException( "Default admin already exists. Use clearDefaultAdmin() first." ); } if (empty($username) || empty($password)) { throw new InvalidArgumentException("Default admin username / password cannot be empty"); } static::$default_username = $username; static::$default_password = $password; static::$has_default_admin = true; }
Set the default admin credentials @param string $username @param string $password
setDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function hasDefaultAdmin() { // Check environment if not explicitly set if (!isset(static::$has_default_admin)) { return !empty(Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME')) && !empty(Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD')); } return static::$has_default_admin; }
Check if there is a default admin @return bool
hasDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function clearDefaultAdmin() { static::$has_default_admin = false; static::$default_username = null; static::$default_password = null; }
Flush the default admin credentials.
clearDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public function findOrCreateAdmin($email, $name = null) { $this->extend('beforeFindOrCreateAdmin', $email, $name); // Find member $admin = Member::get() ->filter('Email', $email) ->first(); // Find or create admin group $adminGroup = $this->findOrCreateAdminGroup(); // If no admin is found, create one if ($admin) { $inGroup = $admin->inGroup($adminGroup); } else { // Note: This user won't be able to login until a password is set // Set 'Email' to identify this as the default admin $inGroup = false; $admin = Member::create(); $admin->FirstName = $name ?: $email; $admin->Email = $email; $admin->PasswordEncryption = Security::config()->get('password_encryption_algorithm'); $admin->write(); } // Ensure this user is in an admin group if (!$inGroup) { // Add member to group instead of adding group to member // This bypasses the privilege escallation code in Member_GroupSet $adminGroup ->DirectMembers() ->add($admin); } $this->extend('afterFindOrCreateAdmin', $admin); return $admin; }
Find or create a Member with admin permissions @param string $email @param string $name @return Member
findOrCreateAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
protected function findOrCreateAdminGroup() { // Check pre-existing group $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Check if default records create the group Group::singleton()->requireDefaultRecords(); $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Create new admin group directly $adminGroup = Group::create(); $adminGroup->Code = 'administrators'; $adminGroup->Title = _t('SilverStripe\\Security\\Group.DefaultGroupTitleAdministrators', 'Administrators'); $adminGroup->Sort = 0; $adminGroup->write(); Permission::grant($adminGroup->ID, 'ADMIN'); return $adminGroup; }
Ensure a Group exists with admin permission @return Group
findOrCreateAdminGroup
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function isDefaultAdmin($username) { return static::hasDefaultAdmin() && $username && $username === static::getDefaultAdminUsername(); }
Check if the user is a default admin. Returns false if there is no default admin. @param string $username @return bool
isDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function isDefaultAdminCredentials($username, $password) { return static::isDefaultAdmin($username) && $password && $password === static::getDefaultAdminPassword(); }
Check if the user credentials match the default admin. Returns false if there is no default admin. @param string $username @param string $password @return bool
isDefaultAdminCredentials
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public function process(HTTPRequest $request, callable $delegate) { try { $this ->getAuthenticationHandler() ->authenticateRequest($request); } catch (ValidationException $e) { return new HTTPResponse( "Bad log-in details: " . $e->getMessage(), 400 ); } catch (DatabaseException $e) { // Database isn't ready, carry on. } return $delegate($request); }
Identify the current user from the request @param HTTPRequest $request @param callable $delegate @return HTTPResponse
process
php
silverstripe/silverstripe-framework
src/Security/AuthenticationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/AuthenticationMiddleware.php
BSD-3-Clause
protected function getNewDeviceID() { $generator = new RandomGenerator(); return $generator->randomToken('sha1'); }
Randomly generates a new ID used for the device @return string A device ID
getNewDeviceID
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public function getNewHash(Member $member) { $generator = new RandomGenerator(); $this->setToken($generator->randomToken('sha1')); return $member->encryptWithUserSettings($this->token); }
Creates a new random token and hashes it using the member information @param Member $member The logged in user @return string The hash to be stored in the database
getNewHash
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public static function generate(Member $member) { if (!$member->exists()) { return null; } if (static::config()->force_single_token) { RememberLoginHash::get()->filter('MemberID', $member->ID)->removeAll(); } $rememberLoginHash = RememberLoginHash::create(); do { $deviceID = $rememberLoginHash->getNewDeviceID(); } while (RememberLoginHash::get()->filter('DeviceID', $deviceID)->count()); $rememberLoginHash->DeviceID = $deviceID; $rememberLoginHash->Hash = $rememberLoginHash->getNewHash($member); $rememberLoginHash->MemberID = $member->ID; $now = DBDatetime::now(); $expiryDate = new DateTime($now->Rfc2822()); $tokenExpiryDays = static::config()->token_expiry_days; $expiryDate->add(new DateInterval('P' . $tokenExpiryDays . 'D')); $rememberLoginHash->ExpiryDate = $expiryDate->format('Y-m-d H:i:s'); $rememberLoginHash->extend('onAfterGenerateToken'); $rememberLoginHash->write(); return $rememberLoginHash; }
Generates a new login hash associated with a device The device is assigned a globally unique device ID The returned login hash stores the hashed token in the database, for this device and this member @param Member $member The logged in user @return RememberLoginHash The generated login hash
generate
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public function renew() { // Only regenerate token if configured to do so Deprecation::notice('5.3.0', 'Will be removed without equivalent functionality'); $replaceToken = RememberLoginHash::config()->get('replace_token_during_session_renewal'); if ($replaceToken) { $hash = $this->getNewHash($this->Member()); $this->Hash = $hash; } $this->extend('onAfterRenewToken', $replaceToken); $this->write(); return $this; }
Generates a new hash for this member but keeps the device ID intact @deprecated 5.3.0 Will be removed without equivalent functionality @return RememberLoginHash
renew
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public function __construct($baseClass, CacheInterface $cache = null) { if (!is_a($baseClass, DataObject::class, true)) { throw new InvalidArgumentException('Invalid DataObject class: ' . $baseClass); } $this->baseClass = $baseClass; $this->cacheService = $cache; return $this; }
Construct new permissions object @param string $baseClass Base class @param CacheInterface $cache
__construct
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function flushMemberCache($memberIDs = null) { if (!$this->cacheService) { return; } // Hard flush, e.g. flush=1 if (!$memberIDs) { $this->cacheService->clear(); } if ($memberIDs && is_array($memberIDs)) { foreach ([InheritedPermissions::VIEW, InheritedPermissions::EDIT, InheritedPermissions::DELETE] as $type) { foreach ($memberIDs as $memberID) { $key = $this->generateCacheKey($type, $memberID); $this->cacheService->delete($key); } } } }
Clear the cache for this instance only @param array $memberIDs A list of member IDs
flushMemberCache
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function setGlobalEditPermissions($permissions) { $this->globalEditPermissions = $permissions; return $this; }
Global permissions required to edit @param array $permissions @return $this
setGlobalEditPermissions
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function getDefaultPermissions() { return $this->defaultPermissions; }
Get root permissions handler, or null if no handler @return DefaultPermissionChecker|null
getDefaultPermissions
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function prePopulatePermissionCache($permission = 'edit', $ids = []) { switch ($permission) { case InheritedPermissions::EDIT: $this->canEditMultiple($ids, Security::getCurrentUser(), false); break; case InheritedPermissions::VIEW: $this->canViewMultiple($ids, Security::getCurrentUser(), false); break; case InheritedPermissions::DELETE: $this->canDeleteMultiple($ids, Security::getCurrentUser(), false); break; default: throw new InvalidArgumentException("Invalid permission type $permission"); } }
Force pre-calculation of a list of permissions for optimisation @param string $permission @param array $ids
prePopulatePermissionCache
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 getPermissionField($type) { switch ($type) { case InheritedPermissions::DELETE: // Delete uses edit type - Drop through case InheritedPermissions::EDIT: return 'CanEditType'; case InheritedPermissions::VIEW: return 'CanViewType'; default: throw new InvalidArgumentException("Invalid argument type $type"); } }
Get field to check for permission type for the given check. Defaults to those provided by {@see InheritedPermissionsExtension) @param string $type @return string
getPermissionField
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 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 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 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