protected function init()
 {
     parent::init();
     if (!Director::is_cli() && !Permission::check('ADMIN')) {
         return Security::permissionFailure();
     }
 }
 public function testModelAdminOpens()
 {
     $this->autoFollowRedirection = false;
     $this->logInAs('admin');
     $this->assertTrue((bool) Permission::check("ADMIN"));
     $this->assertEquals(200, $this->get('ModelAdminTest_Admin')->getStatusCode());
 }
 public function init()
 {
     parent::init();
     if (!Permission::check('ADMIN')) {
         return Security::permissionFailure($this);
     }
 }
 public function init()
 {
     parent::init();
     $canAccess = Director::isDev() || Director::is_cli() || Permission::check("ADMIN");
     if (!$canAccess) {
         return Security::permissionFailure($this);
     }
 }
 protected function init()
 {
     parent::init();
     // Unless called from the command line, all CliControllers need ADMIN privileges
     if (!Director::is_cli() && !Permission::check("ADMIN")) {
         return Security::permissionFailure();
     }
 }
 protected function init()
 {
     parent::init();
     $isRunningTests = class_exists('SilverStripe\\Dev\\SapphireTest', false) && SapphireTest::is_running_test();
     $canAccess = Director::isDev() || Director::is_cli() && !$isRunningTests || Permission::check("ADMIN");
     if (!$canAccess) {
         Security::permissionFailure($this);
     }
 }
 public function run($request)
 {
     if (!Permission::check('ADMIN') && !Director::is_cli()) {
         $response = Security::permissionFailure();
         if ($response) {
             $response->output();
         }
         die;
     }
     SapphireTest::delete_all_temp_dbs();
 }
 protected function init()
 {
     parent::init();
     // We allow access to this controller regardless of live-status or ADMIN permission only
     // if on CLI or with the database not ready. The latter makes it less errorprone to do an
     // initial schema build without requiring a default-admin login.
     // Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
     $isRunningTests = class_exists('SapphireTest', false) && SapphireTest::is_running_test();
     $canAccess = Director::isDev() || !Security::database_is_ready() || Director::is_cli() && !$isRunningTests || Permission::check("ADMIN");
     if (!$canAccess) {
         return Security::permissionFailure($this, "This page is secured and you need administrator rights to access it. " . "Enter your credentials below and we will send you right along.");
     }
 }
 protected function init()
 {
     parent::init();
     // Special case for dev/build: Defer permission checks to DatabaseAdmin->init() (see #4957)
     $requestedDevBuild = stripos($this->getRequest()->getURL(), 'dev/build') === 0 && stripos($this->getRequest()->getURL(), 'dev/build/defaults') === false;
     // We allow access to this controller regardless of live-status or ADMIN permission only
     // if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
     $canAccess = $requestedDevBuild || Director::isDev() || Director::is_cli() || Permission::check("ADMIN");
     if (!$canAccess) {
         Security::permissionFailure($this);
         return;
     }
     // check for valid url mapping
     // lacking this information can cause really nasty bugs,
     // e.g. when running Director::test() from a FunctionalTest instance
     global $_FILE_TO_URL_MAPPING;
     if (Director::is_cli()) {
         if (isset($_FILE_TO_URL_MAPPING)) {
             $testPath = BASE_PATH;
             $matched = false;
             while ($testPath && $testPath != "/" && !preg_match('/^[A-Z]:\\\\$/', $testPath)) {
                 if (isset($_FILE_TO_URL_MAPPING[$testPath])) {
                     $matched = true;
                     break;
                 }
                 $testPath = dirname($testPath);
             }
             if (!$matched) {
                 echo 'Warning: You probably want to define ' . 'an entry in $_FILE_TO_URL_MAPPING that covers "' . Director::baseFolder() . '"' . "\n";
             }
         } else {
             echo 'Warning: You probably want to define $_FILE_TO_URL_MAPPING in ' . 'your _ss_environment.php as instructed on the "sake" page of the doc.silverstripe.org wiki' . "\n";
         }
     }
     // Backwards compat: Default to "draft" stage, which is important
     // for tasks like dev/build which call DataObject->requireDefaultRecords(),
     // but also for other administrative tasks which have assumptions about the default stage.
     Versioned::set_stage(Versioned::DRAFT);
 }
 /**
  * @param Member $member
  * @param array $context Additional context-specific data which might
  * affect whether (or where) this object could be created.
  * @return boolean
  */
 public function canCreate($member = null, $context = array())
 {
     $extended = $this->extendedCan(__FUNCTION__, $member, $context);
     if ($extended !== null) {
         return $extended;
     }
     return Permission::check('ADMIN', 'any', $member);
 }
示例#11
0
    require_once 'core/Core.php';
    // Connect to database
    global $databaseConfig;
    if ($databaseConfig) {
        DB::connect($databaseConfig);
    }
    // Check if a token is requesting a redirect
    if (!$reloadToken) {
        return;
    }
    // Otherwise, we start up the session if needed
    if (!isset($_SESSION) && Session::request_contains_session_id()) {
        Session::start();
    }
    // Next, check if we're in dev mode, or the database doesn't have any security data, or we are admin
    if (Director::isDev() || !Security::database_is_ready() || Permission::check('ADMIN')) {
        return $reloadToken->reloadWithToken();
    }
    // Fail and redirect the user to the login page
    $loginPage = Director::absoluteURL(Security::config()->login_url);
    $loginPage .= "?BackURL=" . urlencode($_SERVER['REQUEST_URI']);
    header('location: ' . $loginPage, true, 302);
    die;
})->thenIfErrored(function () use($reloadToken) {
    if ($reloadToken) {
        $reloadToken->reloadWithToken();
    }
})->execute();
global $databaseConfig;
// Redirect to the installer if no database is selected
if (!isset($databaseConfig) || !isset($databaseConfig['database']) || !$databaseConfig['database']) {
 public function canDelete($member = null)
 {
     return Permission::check('APPLY_ROLES', 'any', $member);
 }
 public function testCoreGlobalVariableCalls()
 {
     $this->assertEquals(Director::absoluteBaseURL(), $this->render('{$absoluteBaseURL}'), 'Director::absoluteBaseURL can be called from within template');
     $this->assertEquals(Director::absoluteBaseURL(), $this->render('{$AbsoluteBaseURL}'), 'Upper-case %AbsoluteBaseURL can be called from within template');
     $this->assertEquals(Director::is_ajax(), $this->render('{$isAjax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(Director::is_ajax(), $this->render('{$IsAjax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(Director::is_ajax(), $this->render('{$is_ajax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(Director::is_ajax(), $this->render('{$Is_ajax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(i18n::get_locale(), $this->render('{$i18nLocale}'), 'i18n template functions result correct result');
     $this->assertEquals(i18n::get_locale(), $this->render('{$get_locale}'), 'i18n template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$CurrentMember}'), 'Member template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$CurrentUser}'), 'Member template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$currentMember}'), 'Member template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$currentUser}'), 'Member template functions result correct result');
     $this->assertEquals(SecurityToken::getSecurityID(), $this->render('{$getSecurityID}'), 'SecurityToken template functions result correct result');
     $this->assertEquals(SecurityToken::getSecurityID(), $this->render('{$SecurityID}'), 'SecurityToken template functions result correct result');
     $this->assertEquals(Permission::check("ADMIN"), (bool) $this->render('{$HasPerm(\'ADMIN\')}'), 'Permissions template functions result correct result');
     $this->assertEquals(Permission::check("ADMIN"), (bool) $this->render('{$hasPerm(\'ADMIN\')}'), 'Permissions template functions result correct result');
 }
 /**
  * Validate that this DBFile accepts this filename as valid
  *
  * @param string $filename
  * @throws ValidationException
  * @return bool
  */
 protected function isValidFilename($filename)
 {
     $extension = strtolower(File::get_file_extension($filename));
     // Validate true if within the list of allowed extensions
     $allowed = $this->getAllowedExtensions();
     if ($allowed) {
         return in_array($extension, $allowed);
     }
     // If no extensions are configured, fallback to global list
     $globalList = File::config()->allowed_extensions;
     if (in_array($extension, $globalList)) {
         return true;
     }
     // Only admins can bypass global rules
     return !File::config()->apply_restrictions_to_admin && Permission::check('ADMIN');
 }
 /**
  * An internal utility function to set up variables in preparation for including a compiled
  * template, then do the include
  *
  * Effectively this is the common code that both SSViewer#process and SSViewer_FromString#process call
  *
  * @param string $cacheFile The path to the file that contains the template compiled to PHP
  * @param ViewableData $item The item to use as the root scope for the template
  * @param array $overlay Any variables to layer on top of the scope
  * @param array $underlay Any variables to layer underneath the scope
  * @param ViewableData $inheritedScope The current scope of a parent template including a sub-template
  * @return string The result of executing the template
  */
 protected function includeGeneratedTemplate($cacheFile, $item, $overlay, $underlay, $inheritedScope = null)
 {
     if (isset($_GET['showtemplate']) && $_GET['showtemplate'] && Permission::check('ADMIN')) {
         $lines = file($cacheFile);
         echo "<h2>Template: {$cacheFile}</h2>";
         echo "<pre>";
         foreach ($lines as $num => $line) {
             echo str_pad($num + 1, 5) . htmlentities($line, ENT_COMPAT, 'UTF-8');
         }
         echo "</pre>";
     }
     $cache = $this->getPartialCacheStore();
     $scope = new SSViewer_DataPresenter($item, $overlay, $underlay, $inheritedScope);
     $val = '';
     include $cacheFile;
     return $val;
 }
 /**
  * Update the permission set associated with $record DataObject
  *
  * @param DataObjectInterface $record
  */
 public function saveInto(DataObjectInterface $record)
 {
     $fieldname = $this->name;
     $managedClass = $this->managedClass;
     // Remove all "privileged" permissions if the currently logged-in user is not an admin
     $privilegedPermissions = Permission::config()->privileged_permissions;
     if (!Permission::check('ADMIN')) {
         foreach ($this->value as $id => $bool) {
             if (in_array($id, $privilegedPermissions)) {
                 unset($this->value[$id]);
             }
         }
     }
     // remove all permissions and re-add them afterwards
     $permissions = $record->{$fieldname}();
     foreach ($permissions as $permission) {
         $permission->delete();
     }
     $schema = DataObject::getSchema();
     if ($fieldname && $record && ($schema->hasManyComponent(get_class($record), $fieldname) || $schema->manyManyComponent(get_class($record), $fieldname))) {
         if (!$record->ID) {
             $record->write();
         }
         // We need a record ID to write permissions
         if ($this->value) {
             foreach ($this->value as $id => $bool) {
                 if ($bool) {
                     $perm = new $managedClass();
                     $perm->{$this->filterField} = $record->ID;
                     $perm->Code = $id;
                     $perm->write();
                 }
             }
         }
     }
 }
 /**
  * Determine if the user has permission to upload.
  *
  * @return boolean
  */
 public function canUpload()
 {
     if (!$this->isActive()) {
         return false;
     }
     $can = $this->getConfig('canUpload');
     if (is_bool($can)) {
         return $can;
     }
     return Permission::check($can);
 }
 /**
  * Cleanup function to reset all the Filename fields.  Visit File/fixfiles to call.
  *
  * @deprecated 5.0
  */
 public function fixfiles()
 {
     Deprecation::notice('5.0');
     if (!Permission::check('ADMIN')) {
         return Security::permissionFailure($this);
     }
     $files = File::get();
     foreach ($files as $file) {
         $file->updateFilesystem();
         echo "<li>", $file->Filename;
         $file->write();
     }
     echo "<p>Done!";
 }
 /**
  * Get a list of all available permission codes, both defined through the
  * {@link PermissionProvider} interface, and all not explicitly defined codes existing
  * as a {@link Permission} database record. By default, the results are
  * grouped as denoted by {@link Permission_Group}.
  *
  * @param bool $grouped Group results into an array of permission groups.
  * @return array Returns an array of all available permission codes. The
  *  array indicies are the permission codes as used in
  *  {@link Permission::check()}. The value is a description
  *  suitable for using in an interface.
  */
 public static function get_codes($grouped = true)
 {
     $classes = ClassInfo::implementorsOf('SilverStripe\\Security\\PermissionProvider');
     $allCodes = array();
     $adminCategory = _t('Permission.AdminGroup', 'Administrator');
     $allCodes[$adminCategory]['ADMIN'] = array('name' => _t('Permission.FULLADMINRIGHTS', 'Full administrative rights'), 'help' => _t('Permission.FULLADMINRIGHTS_HELP', 'Implies and overrules all other assigned permissions.'), 'sort' => 100000);
     if ($classes) {
         foreach ($classes as $class) {
             $SNG = singleton($class);
             if ($SNG instanceof TestOnly) {
                 continue;
             }
             $someCodes = $SNG->providePermissions();
             if ($someCodes) {
                 foreach ($someCodes as $k => $v) {
                     if (is_array($v)) {
                         // There must be a category and name key.
                         if (!isset($v['category'])) {
                             user_error("The permission {$k} must have a category key", E_USER_WARNING);
                         }
                         if (!isset($v['name'])) {
                             user_error("The permission {$k} must have a name key", E_USER_WARNING);
                         }
                         if (!isset($allCodes[$v['category']])) {
                             $allCodes[$v['category']] = array();
                         }
                         $allCodes[$v['category']][$k] = array('name' => $v['name'], 'help' => isset($v['help']) ? $v['help'] : null, 'sort' => isset($v['sort']) ? $v['sort'] : 0);
                     } else {
                         $allCodes['Other'][$k] = array('name' => $v, 'help' => null, 'sort' => 0);
                     }
                 }
             }
         }
     }
     $flatCodeArray = array();
     foreach ($allCodes as $category) {
         foreach ($category as $code => $permission) {
             $flatCodeArray[] = $code;
         }
     }
     $otherPerms = DB::query("SELECT DISTINCT \"Code\" From \"Permission\" WHERE \"Code\" != ''")->column();
     if ($otherPerms) {
         foreach ($otherPerms as $otherPerm) {
             if (!in_array($otherPerm, $flatCodeArray)) {
                 $allCodes['Other'][$otherPerm] = array('name' => $otherPerm, 'help' => null, 'sort' => 0);
             }
         }
     }
     // Don't let people hijack ADMIN rights
     if (!Permission::check("ADMIN")) {
         unset($allCodes['ADMIN']);
     }
     ksort($allCodes);
     $returnCodes = array();
     foreach ($allCodes as $category => $permissions) {
         if ($grouped) {
             uasort($permissions, array(__CLASS__, 'sort_permissions'));
             $returnCodes[$category] = $permissions;
         } else {
             $returnCodes = array_merge($returnCodes, $permissions);
         }
     }
     return $returnCodes;
 }
 /**
  * Determine if the user has permission to attach existing files
  * By default returns true if the user has the CMS_ACCESS_AssetAdmin permission
  *
  * @return boolean
  */
 public function canAttachExisting()
 {
     if (!$this->isActive()) {
         return false;
     }
     $can = $this->getConfig('canAttachExisting');
     return is_bool($can) ? $can : Permission::check($can);
 }
 /**
  * @see SecurityAdmin_MemberImportForm
  *
  * @return Form
  */
 public function GroupImportForm()
 {
     if (!Permission::check('ADMIN')) {
         return false;
     }
     $form = new GroupImportForm($this, 'GroupImportForm');
     return $form;
 }
 /**
  * Cleanup function to reset all the Filename fields.  Visit File/fixfiles to call.
  */
 public function fixfiles()
 {
     if (!Permission::check('ADMIN')) {
         return Security::permissionFailure($this);
     }
     $files = DataObject::get("File");
     foreach ($files as $file) {
         $file->updateFilesystem();
         echo "<li>", $file->Filename;
         $file->write();
     }
     echo "<p>Done!";
 }
 public function index()
 {
     if (!Permission::check('ADMIN')) {
         return Security::permissionFailure($this);
     }
     return 'Success';
 }
 public function CanOrganiseSitetree()
 {
     return !Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN') ? false : true;
 }
示例#25
0
 /**
  * Return a {@link FieldList} of fields that would appropriate for editing
  * this member.
  *
  * @return FieldList Return a FieldList of fields that would appropriate for
  *                   editing this member.
  */
 public function getCMSFields()
 {
     require_once 'Zend/Date.php';
     $self = $this;
     $this->beforeUpdateCMSFields(function (FieldList $fields) use($self) {
         /** @var FieldList $mainFields */
         $mainFields = $fields->fieldByName("Root")->fieldByName("Main")->getChildren();
         // Build change password field
         $mainFields->replaceField('Password', $self->getMemberPasswordField());
         $mainFields->replaceField('Locale', new DropdownField("Locale", _t('Member.INTERFACELANG', "Interface Language", 'Language of the CMS'), i18n::get_existing_translations()));
         $mainFields->removeByName($self->config()->hidden_fields);
         if (!$self->config()->lock_out_after_incorrect_logins) {
             $mainFields->removeByName('FailedLoginCount');
         }
         // Groups relation will get us into logical conflicts because
         // Members are displayed within  group edit form in SecurityAdmin
         $fields->removeByName('Groups');
         // Members shouldn't be able to directly view/edit logged passwords
         $fields->removeByName('LoggedPasswords');
         $fields->removeByName('RememberLoginHashes');
         if (Permission::check('EDIT_PERMISSIONS')) {
             $groupsMap = array();
             foreach (Group::get() as $group) {
                 // Listboxfield values are escaped, use ASCII char instead of &raquo;
                 $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
             }
             asort($groupsMap);
             $fields->addFieldToTab('Root.Main', ListboxField::create('DirectGroups', singleton('SilverStripe\\Security\\Group')->i18n_plural_name())->setSource($groupsMap)->setAttribute('data-placeholder', _t('Member.ADDGROUP', 'Add group', 'Placeholder text for a dropdown')));
             // Add permission field (readonly to avoid complicated group assignment logic).
             // This should only be available for existing records, as new records start
             // with no permissions until they have a group assignment anyway.
             if ($self->ID) {
                 $permissionsField = new PermissionCheckboxSetField_Readonly('Permissions', false, 'SilverStripe\\Security\\Permission', 'GroupID', $self->getManyManyComponents('Groups'));
                 $fields->findOrMakeTab('Root.Permissions', singleton('SilverStripe\\Security\\Permission')->i18n_plural_name());
                 $fields->addFieldToTab('Root.Permissions', $permissionsField);
             }
         }
         $permissionsTab = $fields->fieldByName("Root")->fieldByName('Permissions');
         if ($permissionsTab) {
             $permissionsTab->addExtraClass('readonly');
         }
         $defaultDateFormat = Zend_Locale_Format::getDateFormat(new Zend_Locale($self->Locale));
         $dateFormatMap = array('MMM d, yyyy' => Zend_Date::now()->toString('MMM d, yyyy'), 'yyyy/MM/dd' => Zend_Date::now()->toString('yyyy/MM/dd'), 'MM/dd/yyyy' => Zend_Date::now()->toString('MM/dd/yyyy'), 'dd/MM/yyyy' => Zend_Date::now()->toString('dd/MM/yyyy'));
         $dateFormatMap[$defaultDateFormat] = Zend_Date::now()->toString($defaultDateFormat) . sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
         $mainFields->push($dateFormatField = new MemberDatetimeOptionsetField('DateFormat', $self->fieldLabel('DateFormat'), $dateFormatMap));
         $dateFormatField->setValue($self->DateFormat);
         $dateFormatField->setDescriptionTemplate('forms/MemberDatetimeOptionsetField_description_date');
         $defaultTimeFormat = Zend_Locale_Format::getTimeFormat(new Zend_Locale($self->Locale));
         $timeFormatMap = array('h:mm a' => Zend_Date::now()->toString('h:mm a'), 'H:mm' => Zend_Date::now()->toString('H:mm'));
         $timeFormatMap[$defaultTimeFormat] = Zend_Date::now()->toString($defaultTimeFormat) . sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
         $mainFields->push($timeFormatField = new MemberDatetimeOptionsetField('TimeFormat', $self->fieldLabel('TimeFormat'), $timeFormatMap));
         $timeFormatField->setValue($self->TimeFormat);
         $timeFormatField->setDescriptionTemplate('forms/MemberDatetimeOptionsetField_description_time');
     });
     return parent::getCMSFields();
 }
 /**
  * Check that the given action is allowed to be called from a URL.
  * It will interrogate {@link self::$allowed_actions} to determine this.
  *
  * @param string $action
  * @return bool
  * @throws Exception
  */
 public function checkAccessAction($action)
 {
     $actionOrigCasing = $action;
     $action = strtolower($action);
     $isAllowed = false;
     $isDefined = false;
     // Get actions for this specific class (without inheritance)
     $definingClass = $this->definingClassForAction($actionOrigCasing);
     $allowedActions = $this->allowedActions($definingClass);
     // check if specific action is set
     if (isset($allowedActions[$action])) {
         $isDefined = true;
         $test = $allowedActions[$action];
         if ($test === true || $test === 1 || $test === '1') {
             // TRUE should always allow access
             $isAllowed = true;
         } elseif (substr($test, 0, 2) == '->') {
             // Determined by custom method with "->" prefix
             list($method, $arguments) = Object::parse_class_spec(substr($test, 2));
             $isAllowed = call_user_func_array(array($this, $method), $arguments);
         } else {
             // Value is a permission code to check the current member against
             $isAllowed = Permission::check($test);
         }
     } elseif (is_array($allowedActions) && ($key = array_search($action, $allowedActions, true)) !== false && is_numeric($key)) {
         // Allow numeric array notation (search for array value as action instead of key)
         $isDefined = true;
         $isAllowed = true;
     } elseif (is_array($allowedActions) && !count($allowedActions)) {
         // If defined as empty array, deny action
         $isAllowed = false;
     } elseif ($allowedActions === null) {
         // If undefined, allow action based on configuration
         $isAllowed = !Config::inst()->get('RequestHandler', 'require_allowed_actions');
     }
     // If we don't have a match in allowed_actions,
     // whitelist the 'index' action as well as undefined actions based on configuration.
     if (!$isDefined && ($action == 'index' || empty($action))) {
         $isAllowed = true;
     }
     return $isAllowed;
 }
 public function validate()
 {
     $result = parent::validate();
     // Check if the new group hierarchy would add certain "privileged permissions",
     // and require an admin to perform this change in case it does.
     // This prevents "sub-admin" users with group editing permissions to increase their privileges.
     if ($this->Parent()->exists() && !Permission::check('ADMIN')) {
         $inheritedCodes = Permission::get()->filter('GroupID', $this->Parent()->collateAncestorIDs())->column('Code');
         $privilegedCodes = Config::inst()->get('SilverStripe\\Security\\Permission', 'privileged_permissions');
         if (array_intersect($inheritedCodes, $privilegedCodes)) {
             $result->error(sprintf(_t('Group.HierarchyPermsError', 'Can\'t assign parent group "%s" with privileged permissions (requires ADMIN access)'), $this->Parent()->Title));
         }
     }
     return $result;
 }