public function testCanUploadWithPermissionCode()
 {
     $field = UploadField::create('MyField');
     Session::clear("loggedInAs");
     $field->setCanUpload(true);
     $this->assertTrue($field->canUpload());
     $field->setCanUpload(false);
     $this->assertFalse($field->canUpload());
     $this->loginWithPermission('ADMIN');
     $field->setCanUpload(false);
     $this->assertFalse($field->canUpload());
     $field->setCanUpload('ADMIN');
     $this->assertTrue($field->canUpload());
 }
 public function testCanView()
 {
     // Create changeset containing all items (unpublished)
     $this->logInWithPermission('ADMIN');
     $changeSet = new ChangeSet();
     $changeSet->write();
     $base = $this->objFromFixture(ChangeSetTest_Base::class, 'base');
     $changeSet->addObject($base);
     $changeSet->sync();
     $this->assertEquals(5, $changeSet->Changes()->count());
     // Check canView
     Session::clear("loggedInAs");
     $this->assertFalse($changeSet->canView());
     $this->logInWithPermission('SomeWrongPermission');
     $this->assertFalse($changeSet->canView());
     $this->logInWithPermission('CMS_ACCESS_CampaignAdmin');
     $this->assertTrue($changeSet->canView());
 }
 public function revoke($filename, $hash)
 {
     $fileID = $this->getFileID($filename, $hash);
     $granted = Session::get(self::GRANTS_SESSION) ?: array();
     unset($granted[$fileID]);
     if ($granted) {
         Session::set(self::GRANTS_SESSION, $granted);
     } else {
         Session::clear(self::GRANTS_SESSION);
     }
 }
 /**
  * Change the password
  *
  * @param array $data The user submitted data
  * @return HTTPResponse
  */
 public function doChangePassword(array $data)
 {
     if ($member = Member::currentUser()) {
         // The user was logged in, check the current password
         if (empty($data['OldPassword']) || !$member->checkPassword($data['OldPassword'])->valid()) {
             $this->clearMessage();
             $this->sessionMessage(_t('Member.ERRORPASSWORDNOTMATCH', "Your current password does not match, please try again"), "bad");
             // redirect back to the form, instead of using redirectBack() which could send the user elsewhere.
             return $this->controller->redirect($this->controller->Link('changepassword'));
         }
     }
     if (!$member) {
         if (Session::get('AutoLoginHash')) {
             $member = Member::member_from_autologinhash(Session::get('AutoLoginHash'));
         }
         // The user is not logged in and no valid auto login hash is available
         if (!$member) {
             Session::clear('AutoLoginHash');
             return $this->controller->redirect($this->controller->Link('login'));
         }
     }
     // Check the new password
     if (empty($data['NewPassword1'])) {
         $this->clearMessage();
         $this->sessionMessage(_t('Member.EMPTYNEWPASSWORD', "The new password can't be empty, please try again"), "bad");
         // redirect back to the form, instead of using redirectBack() which could send the user elsewhere.
         return $this->controller->redirect($this->controller->Link('changepassword'));
     } else {
         if ($data['NewPassword1'] == $data['NewPassword2']) {
             $isValid = $member->changePassword($data['NewPassword1']);
             if ($isValid->valid()) {
                 // Clear locked out status
                 $member->LockedOutUntil = null;
                 $member->FailedLoginCount = null;
                 $member->write();
                 if ($member->canLogIn()->valid()) {
                     $member->logIn();
                 }
                 // TODO Add confirmation message to login redirect
                 Session::clear('AutoLoginHash');
                 if (!empty($_REQUEST['BackURL']) && Director::is_site_url($_REQUEST['BackURL'])) {
                     $url = Director::absoluteURL($_REQUEST['BackURL']);
                     return $this->controller->redirect($url);
                 } else {
                     // Redirect to default location - the login form saying "You are logged in as..."
                     $redirectURL = HTTP::setGetVar('BackURL', Director::absoluteBaseURL(), $this->controller->Link('login'));
                     return $this->controller->redirect($redirectURL);
                 }
             } else {
                 $this->clearMessage();
                 $this->sessionMessage(_t('Member.INVALIDNEWPASSWORD', "We couldn't accept that password: {password}", array('password' => nl2br("\n" . Convert::raw2xml($isValid->starredList())))), "bad", false);
                 // redirect back to the form, instead of using redirectBack() which could send the user elsewhere.
                 return $this->controller->redirect($this->controller->Link('changepassword'));
             }
         } else {
             $this->clearMessage();
             $this->sessionMessage(_t('Member.ERRORNEWPASSWORD', "You have entered your new password differently, try again"), "bad");
             // redirect back to the form, instead of using redirectBack() which could send the user elsewhere.
             return $this->controller->redirect($this->controller->Link('changepassword'));
         }
     }
 }
Пример #5
0
 public function resetValidation()
 {
     Session::clear("FormInfo.{$this->FormName()}.errors");
     Session::clear("FormInfo.{$this->FormName()}.data");
 }
 /**
  * Method to authenticate an user
  *
  * @param array $data Raw data to authenticate the user
  * @param Form $form Optional: If passed, better error messages can be
  *                             produced by using
  *                             {@link Form::sessionMessage()}
  * @return bool|Member Returns FALSE if authentication fails, otherwise
  *                     the member object
  * @see Security::setDefaultAdmin()
  */
 public static function authenticate($data, Form $form = null)
 {
     // Find authenticated member
     $member = static::authenticate_member($data, $form, $success);
     // Optionally record every login attempt as a {@link LoginAttempt} object
     static::record_login_attempt($data, $member, $success);
     // Legacy migration to precision-safe password hashes.
     // A login-event with cleartext passwords is the only time
     // when we can rehash passwords to a different hashing algorithm,
     // bulk-migration doesn't work due to the nature of hashing.
     // See PasswordEncryptor_LegacyPHPHash class.
     if ($success && $member && isset(self::$migrate_legacy_hashes[$member->PasswordEncryption])) {
         $member->Password = $data['Password'];
         $member->PasswordEncryption = self::$migrate_legacy_hashes[$member->PasswordEncryption];
         $member->write();
     }
     if ($success) {
         Session::clear('BackURL');
     }
     return $success ? $member : null;
 }
 /**
  * Show the "login" page
  *
  * For multiple authenticators, Security_MultiAuthenticatorLogin is used.
  * See getTemplatesFor and getIncludeTemplate for how to override template logic
  *
  * @return string|HTTPResponse Returns the "login" page as HTML code.
  */
 public function login()
 {
     // Check pre-login process
     if ($response = $this->preLogin()) {
         return $response;
     }
     // Get response handler
     $controller = $this->getResponseController(_t('Security.LOGIN', 'Log in'));
     // if the controller calls Director::redirect(), this will break early
     if (($response = $controller->getResponse()) && $response->isFinished()) {
         return $response;
     }
     $forms = $this->GetLoginForms();
     if (!count($forms)) {
         user_error('No login-forms found, please use Authenticator::register_authenticator() to add one', E_USER_ERROR);
     }
     // Handle any form messages from validation, etc.
     $messageType = '';
     $message = $this->getLoginMessage($messageType);
     // We've displayed the message in the form output, so reset it for the next run.
     Session::clear('Security.Message');
     // only display tabs when more than one authenticator is provided
     // to save bandwidth and reduce the amount of custom styling needed
     if (count($forms) > 1) {
         $content = $this->generateLoginFormSet($forms);
     } else {
         $content = $forms[0]->forTemplate();
     }
     // Finally, customise the controller to add any form messages and the form.
     $customisedController = $controller->customise(array("Content" => DBField::create_field('HTMLFragment', $message), "Message" => DBField::create_field('HTMLFragment', $message), "MessageType" => $messageType, "Form" => $content));
     // Return the customised controller
     return $customisedController->renderWith($this->getTemplatesFor('login'));
 }
Пример #8
0
 /**
  * Logs this member out.
  */
 public function logOut()
 {
     $this->extend('beforeMemberLoggedOut');
     Session::clear("loggedInAs");
     if (Member::config()->login_marker_cookie) {
         Cookie::set(Member::config()->login_marker_cookie, null, 0);
     }
     Session::destroy();
     $this->extend('memberLoggedOut');
     // Clears any potential previous hashes for this member
     RememberLoginHash::clear($this, Cookie::get('alc_device'));
     Cookie::set('alc_enc', null);
     // // Clear the Remember Me cookie
     Cookie::force_expiry('alc_enc');
     Cookie::set('alc_device', null);
     Cookie::force_expiry('alc_device');
     // Switch back to live in order to avoid infinite loops when
     // redirecting to the login screen (if this login screen is versioned)
     Session::clear('readingMode');
     $this->write();
     // Audit logging hook
     $this->extend('memberLoggedOut');
 }
 /**
  * Login in the user and figure out where to redirect the browser.
  *
  * The $data has this format
  * array(
  *   'AuthenticationMethod' => 'MemberAuthenticator',
  *   'Email' => '*****@*****.**',
  *   'Password' => '1nitialPassword',
  *   'BackURL' => 'test/link',
  *   [Optional: 'Remember' => 1 ]
  * )
  *
  * @param array $data
  * @return HTTPResponse
  */
 protected function logInUserAndRedirect($data)
 {
     Session::clear('SessionForms.MemberLoginForm.Email');
     Session::clear('SessionForms.MemberLoginForm.Remember');
     if (Member::currentUser()->isPasswordExpired()) {
         if (isset($_REQUEST['BackURL']) && ($backURL = $_REQUEST['BackURL'])) {
             Session::set('BackURL', $backURL);
         }
         /** @skipUpgrade */
         $cp = ChangePasswordForm::create($this->controller, 'ChangePasswordForm');
         $cp->sessionMessage(_t('Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good');
         return $this->controller->redirect('Security/changepassword');
     }
     // Absolute redirection URLs may cause spoofing
     if (!empty($_REQUEST['BackURL'])) {
         $url = $_REQUEST['BackURL'];
         if (Director::is_site_url($url)) {
             $url = Director::absoluteURL($url);
         } else {
             // Spoofing attack, redirect to homepage instead of spoofing url
             $url = Director::absoluteBaseURL();
         }
         return $this->controller->redirect($url);
     }
     // If a default login dest has been set, redirect to that.
     if ($url = Security::config()->default_login_dest) {
         $url = Controller::join_links(Director::absoluteBaseURL(), $url);
         return $this->controller->redirect($url);
     }
     // Redirect the user to the page where they came from
     $member = Member::currentUser();
     if ($member) {
         $firstname = Convert::raw2xml($member->FirstName);
         if (!empty($data['Remember'])) {
             Session::set('SessionForms.MemberLoginForm.Remember', '1');
             $member->logIn(true);
         } else {
             $member->logIn();
         }
         Session::set('Security.Message.message', _t('Member.WELCOMEBACK', "Welcome Back, {firstname}", array('firstname' => $firstname)));
         Session::set("Security.Message.type", "good");
     }
     return Controller::curr()->redirectBack();
 }
 /**
  * Reset static configuration variables to their default values.
  */
 public static function reset()
 {
     self::$reading_mode = '';
     Session::clear('readingMode');
 }
 public function testClearElement()
 {
     Session::set('Test', 'Test');
     Session::clear('Test');
     $this->assertEquals(Session::get('Test'), '');
 }
 public function testCanViewStage()
 {
     $public = $this->objFromFixture('VersionedTest_PublicStage', 'public1');
     $private = $this->objFromFixture('VersionedTest_DataObject', 'page1');
     Session::clear("loggedInAs");
     Versioned::set_stage(Versioned::DRAFT);
     // Test that all (and only) public pages are viewable in stage mode
     // Unpublished records are not viewable in live regardless of permissions
     $this->assertTrue($public->canViewStage('Stage'));
     $this->assertFalse($private->canViewStage('Stage'));
     $this->assertFalse($public->canViewStage('Live'));
     $this->assertFalse($private->canViewStage('Live'));
     // Writing records to live should make both stage and live modes viewable
     $private->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
     $public->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
     $this->assertTrue($public->canViewStage('Stage'));
     $this->assertTrue($private->canViewStage('Stage'));
     $this->assertTrue($public->canViewStage('Live'));
     $this->assertTrue($private->canViewStage('Live'));
     // If the draft mode changes, the live mode remains public, although the updated
     // draft mode is secured for non-public records.
     $private->Title = 'Secret Title';
     $private->write();
     $public->Title = 'Public Title';
     $public->write();
     $this->assertTrue($public->canViewStage('Stage'));
     $this->assertFalse($private->canViewStage('Stage'));
     $this->assertTrue($public->canViewStage('Live'));
     $this->assertTrue($private->canViewStage('Live'));
 }