Esempio n. 1
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws Exception
  * @returns null
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!Check::fileToUrlMapping()) {
         die('ERROR: Please set a valid path in $_FILE_TO_URL_MAPPING before running the seeder' . PHP_EOL);
     }
     // Customer overrides delete to check for admin
     // major hack to enable ADMIN permissions
     // login throws cookie warning, this will hide the error message
     error_reporting();
     try {
         if ($admin = \Member::default_admin()) {
             $admin->logIn();
         }
     } catch (\Exception $e) {
     }
     error_reporting(E_ALL);
     $writer = new RecordWriter();
     // TODO batch write is not working with seeder yet
     //        if ($batchSize = $input->getOption('batch')) {
     //            $writer = new BatchedSeedWriter($batchSize);
     //        }
     $seeder = new Seeder($writer, new CliOutputFormatter());
     $key = $input->getOption('key');
     $seeder->unseed($key);
 }
Esempio n. 2
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws Exception
  * @returns null
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!Check::fileToUrlMapping()) {
         die('ERROR: Please set a valid path in $_FILE_TO_URL_MAPPING before running the seeder' . PHP_EOL);
     }
     if (\SiteTree::has_extension('SiteTreeLinkTracking')) {
         \SiteTree::remove_extension('SiteTreeLinkTracking');
     }
     // Customer overrides delete to check for admin
     // major hack to enable ADMIN permissions
     // login throws cookie warning, this will hide the error message
     error_reporting(0);
     try {
         if ($admin = \Member::default_admin()) {
             $admin->logIn();
         }
     } catch (\Exception $e) {
     }
     error_reporting(E_ALL);
     $writer = new RecordWriter();
     if ($input->getOption('batch')) {
         $batchSize = intval($input->getOption('size'));
         $writer = new BatchedSeedWriter($batchSize);
     }
     $seeder = new Seeder($writer, new CliOutputFormatter());
     $className = $input->getOption('class');
     $key = $input->getOption('key');
     if ($input->getOption('force')) {
         $seeder->setIgnoreSeeds(true);
     }
     $seeder->seed($className, $key);
     return;
 }
 /**
  * Attempt to find and authenticate member if possible from the given data.
  *
  * @param array $data
  * @param Form $form
  * @param bool &$success Success flag
  * @return Member Found member, regardless of successful login
  * @see MemberAuthenticator::authenticate_member()
  */
 protected static function authenticate_member($data, $form, &$success)
 {
     // Default success to false
     $success = false;
     // Attempt to identify by temporary ID
     $member = null;
     $email = null;
     if (!empty($data['tempid'])) {
         // Find user by tempid, in case they are re-validating an existing session
         $member = Member::member_from_tempid($data['tempid']);
         if ($member) {
             $email = $member->Email;
         }
     }
     // Otherwise, get email from posted value instead
     if (!$member && !empty($data['Email'])) {
         $email = $data['Email'];
     }
     // Check default login (see Security::setDefaultAdmin()) the standard way and the "extension"-way :-)
     $asDefaultAdmin = $email === Security::default_admin_username();
     if ($asDefaultAdmin || isset($GLOBALS['_DEFAULT_ADMINS']) && array_key_exists($email, $GLOBALS['_DEFAULT_ADMINS'])) {
         // If logging is as default admin, ensure record is setup correctly
         $member = Member::default_admin();
         $success = Security::check_default_admin($email, $data['Password']);
         // If not already true check if one of the extra admins match
         if (!$success) {
             $success = $GLOBALS['_DEFAULT_ADMINS'][$email] == $data['Password'];
         }
         if ($success) {
             return $member;
         }
     }
     // Attempt to identify user by email
     if (!$member && $email) {
         // Find user by email
         $member = Member::get()->filter(Member::config()->unique_identifier_field, $email)->first();
     }
     // Validate against member if possible
     if ($member && !$asDefaultAdmin) {
         $result = $member->checkPassword($data['Password']);
         $success = $result->valid();
     } else {
         $result = new ValidationResult(false, _t('Member.ERRORWRONGCRED'));
     }
     // Emit failure to member and form (if available)
     if (!$success) {
         if ($member) {
             $member->registerFailedLogin();
         }
         if ($form) {
             $form->sessionMessage($result->message(), 'bad');
         }
     } else {
         if ($member) {
             $member->registerSuccessfulLogin();
         }
     }
     return $member;
 }
 public function testDefaultAdmin()
 {
     $adminMembers = Permission::get_members_by_permission('ADMIN');
     $this->assertEquals(0, $adminMembers->count());
     $admin = Member::default_admin();
     $this->assertInstanceOf('Member', $admin);
     $this->assertTrue(Permission::checkMember($admin, 'ADMIN'));
     $this->assertEquals($admin->Email, Security::default_admin_username());
     $this->assertNull($admin->Password);
 }
 /**
  *	The test to ensure the request filter is functioning correctly.
  */
 public function testRequestFilter()
 {
     // Instantiate link mappings to use.
     $mapping = LinkMapping::create(array('LinkType' => 'Simple', 'MappedLink' => 'wrong/page', 'RedirectLink' => 'pending'));
     $mapping->write();
     LinkMapping::create(array('LinkType' => 'Simple', 'MappedLink' => 'pending', 'RedirectLink' => 'correct/page'))->write();
     // The CMS module needs to be present to test page behaviour.
     if (ClassInfo::exists('SiteTree')) {
         // This is required to support multiple sites.
         $this->logInAs(Member::default_admin());
         $parentID = ClassInfo::exists('Multisites') ? Multisites::inst()->getCurrentSiteId() : 0;
         // Instantiate pages to use.
         $first = SiteTree::create(array('URLSegment' => 'wrong', 'ParentID' => $parentID));
         $first->writeToStage('Stage');
         $first->writeToStage('Live');
         $second = SiteTree::create(array('URLSegment' => 'page', 'ParentID' => $first->ID));
         $second->writeToStage('Stage');
         $second->writeToStage('Live');
     }
     // Determine whether the enforce misdirection is functioning correctly.
     $response = $this->get('wrong/page');
     $this->assertEquals($response->getStatusCode(), 303);
     $this->assertEquals($response->getHeader('Location'), '/correct/page');
     // The CMS module needs to be present to test page behaviour.
     if (ClassInfo::exists('SiteTree')) {
         // Update the default enforce misdirection.
         Config::inst()->update('MisdirectionRequestFilter', 'enforce_misdirection', false);
         // Determine whether the page is now matched.
         $response = $this->get('wrong/page');
         $this->assertEquals($response->getStatusCode(), 200);
         $this->assertEquals($response->getHeader('Location'), null);
         // Instantiate a fallback to use.
         $first->Fallback = 'Nearest';
         $first->writeToStage('Stage');
         $first->writeToStage('Live');
         // The database needs to be cleaned up to prevent further testing conflict.
         $second->deleteFromStage('Live');
         $second->deleteFromStage('Stage');
         $mapping->delete();
         // Determine whether the fallback is matched.
         $response = $this->get('wrong/page');
         $this->assertEquals($response->getStatusCode(), 303);
         $this->assertEquals($response->getHeader('Location'), '/wrong/?misdirected=1');
     }
     // Instantiate a director rule to use.
     Config::inst()->update('Director', 'rules', array('wrong/page' => 'Controller'));
     // Determine whether the director rule is matched.
     $response = $this->get('wrong/page');
     $this->assertEquals($response->getStatusCode(), 200);
     $this->assertEquals($response->getHeader('Location'), null);
     // The database needs to be emptied to prevent further testing conflict.
     self::empty_temp_db();
 }
Esempio n. 6
0
 /**
  * Return an existing member with administrator privileges, or create one of necessary.
  *
  * Will create a default 'Administrators' group if no group is found
  * with an ADMIN permission. Will create a new 'Admin' member with administrative permissions
  * if no existing Member with these permissions is found.
  *
  * Important: Any newly created administrator accounts will NOT have valid
  * login credentials (Email/Password properties), which means they can't be used for login
  * purposes outside of any default credentials set through {@link Security::setDefaultAdmin()}.
  *
  * @return Member
  */
 public static function findAnAdministrator()
 {
     // coupling to subsites module
     $origSubsite = null;
     if (is_callable('Subsite::changeSubsite')) {
         $origSubsite = Subsite::currentSubsiteID();
         Subsite::changeSubsite(0);
     }
     $member = null;
     // find a group with ADMIN permission
     $adminGroup = Permission::get_groups_by_permission('ADMIN')->First();
     if (is_callable('Subsite::changeSubsite')) {
         Subsite::changeSubsite($origSubsite);
     }
     if ($adminGroup) {
         $member = $adminGroup->Members()->First();
     }
     if (!$adminGroup) {
         singleton('Group')->requireDefaultRecords();
         $adminGroup = Permission::get_groups_by_permission('ADMIN')->First();
     }
     if (!$member) {
         singleton('Member')->requireDefaultRecords();
         $member = Permission::get_members_by_permission('ADMIN')->First();
     }
     if (!$member) {
         $member = Member::default_admin();
     }
     if (!$member) {
         // Failover to a blank admin
         $member = Member::create();
         $member->FirstName = _t('Member.DefaultAdminFirstname', 'Default Admin');
         $member->write();
         // Add member to group instead of adding group to member
         // This bypasses the privilege escallation code in Member_GroupSet
         $adminGroup->DirectMembers()->add($member);
     }
     return $member;
 }
    public function run($request)
    {
        if (!Director::is_cli() && !isset($_GET['run'])) {
            DB::alteration_message('Must add ?run=1', 'error');
            return false;
        }
        if (!Director::is_cli()) {
            // - Add UTF-8 so characters will render as they should when debugging (so you can visualize inproperly formatted characters easier)
            // - Add base_tag so that printing blocks of HTML works properly with relative links (helps with visualizing errors)
            ?>
			<head>
				<?php 
            echo SSViewer::get_base_tag('');
            ?>
				<meta charset="UTF-8">
			</head>
<?php 
        }
        increase_time_limit_to(300);
        WordpressDatabase::$default_config = $this->config()->default_db;
        $this->db = $this->wordpressImportService->getDatabase();
        // Login as default admin so 'canPublish()' definitely returns true in 'SiteTree::doPublish()'
        if (!Member::currentUser()) {
            $defaultAdmin = Member::default_admin();
            if ($defaultAdmin && $defaultAdmin->exists()) {
                Session::set('loggedInAs', $defaultAdmin->ID);
            }
        }
        // Unsure if the importing functionality can ever hit this, but just incase.
        if (Versioned::current_stage() !== 'Stage') {
            throw new Exception('Versioned::current_stage() must be "Stage".');
        }
        $this->runCustom($request);
    }
 /**
  * Ensures we have permissions to manipulate pages (gets around access issues with global state). Unfortunately, the
  * creation of a default admin account below is necessary because SilverStripe will reference global state via
  * Member::currentUser() and the only surefire way around this is to login as a default admin with full access.
  *
  * CAUTION: Since migrations can only be run from the command line, it's assumed that if you're accessing this, then
  * you're already an admin or you've got an incorrectly configured site!
  *
  * TODO: This should be removed soon.
  *
  * @deprecated  Use ::whileAdmin() instead.
  */
 protected static function loginAsAdmin()
 {
     Deprecation::notice('0', 'Use ::whileAdmin() instead. This method will be removed soon.');
     if (!Member::currentUserID()) {
         // See if a default admin is setup yet.
         if (!Security::has_default_admin()) {
             // Generate a randomized user/pass and use that as the default administrator just for this session.
             $user = substr(str_shuffle(sha1("u" . microtime())), 0, 20);
             $pass = substr(str_shuffle(sha1("p" . microtime())), 0, 20);
             Security::setDefaultAdmin($user, $pass);
         }
         $admin = Member::default_admin();
         if (!$admin) {
             throw new MigrationException("Cannot login: No default administrator found.");
         }
         Session::start();
         Session::set("loggedInAs", $admin->ID);
     }
 }
 public function testDefaultAdminLockOut()
 {
     Config::inst()->update('Member', 'lock_out_after_incorrect_logins', 1);
     Config::inst()->update('Member', 'lock_out_delay_mins', 10);
     SS_Datetime::set_mock_now('2016-04-18 00:00:00');
     $controller = new Security();
     $form = new Form($controller, 'Form', new FieldList(), new FieldList());
     // Test correct login
     MemberAuthenticator::authenticate(array('Email' => 'admin', 'Password' => 'wrongpassword'), $form);
     $this->assertTrue(Member::default_admin()->isLockedOut());
     $this->assertEquals(Member::default_admin()->LockedOutUntil, '2016-04-18 00:10:00');
 }