Redirects the user to the plugin manager or security configuration
357750
@RequirePOST
    public HttpResponse doForward(@QueryParameter String fix, @QueryParameter String configure) {
        if (fix != null) {
            return HttpResponses.redirectViaContextPath("pluginManager");
        }
        if (configure != null) {
            return HttpResponses.redirectViaContextPath("configureSecurity");
        }

        // shouldn't happen
        return HttpResponses.redirectViaContextPath("/");
    }
760569
protected function redirectToInstaller()
    {
        // Error if installer not available
        if (!file_exists(Director::publicFolder() . '/install.php')) {
            throw new HTTPResponse_Exception(
                'SilverStripe Framework requires database configuration defined via .env',
                500
            );
        }

        // Redirect to installer
        $response = new HTTPResponse();
        $response->redirect(Director::absoluteURL('install.php'));
        throw new HTTPResponse_Exception($response);
    }
587725
def configure(username, password, domain):
    
    art = r'''
Welcome!                                __        ___.   .__
_____    ____  ____  ____  __ __  _____/  |______ \_ |__ |  |   ____
\__  \ _/ ___\/ ___\/  _ \|  |  \/    \   __\__  \ | __ \|  | _/ __ \
 / __ \\  \__\  \__(  <_> )  |  /   |  \  |  / __ \| \_\ \  |_\  ___/
(____  /\___  >___  >____/|____/|___|  /__| (____  /___  /____/\___  >
     \/     \/    \/                 \/          \/    \/          \/
     '''
    click.secho(art, fg='blue')
    Config(username=username, password=password, domain=domain)
696254
def handle_existing_user(self, provider, user, access, info):
        ""
        login(self.request, user)
        return redirect(self.get_login_redirect(provider, user, access))
14391
public function loginAction()
    {
        $authPlugin = $this->cmsAuthentication();

        $redirectKey = $this->options->getRedirectKey();
        $redirect = $this->options->getUseRedirectParameter()
            ? $this->params()->fromQuery($redirectKey, false)
            : false;

        $url = $this->url()->fromRoute(
            null,
            [],
            $redirect ? ['query' => [$redirectKey => $redirect]] : []
        );

        $prg = $this->prg($url, true);
        // Return early if prg plugin returned a response
        if ($prg instanceof Response) {
            return $prg;
        }

        $post = $prg;

        $form = $this->loginForm;
        $fm   = $this->flashMessenger();

        if ($this->forwardingController && $fm->hasCurrentErrorMessages()) {
            foreach($fm->getCurrentErrorMessages() as $messages) {
                $form->setMessages($messages);
            }
            $fm->clearCurrentMessages($fm::NAMESPACE_ERROR);
        } elseif ($fm->hasErrorMessages()) {
            foreach($fm->getErrorMessages() as $messages) {
                $form->setMessages($messages);
            }
        }

        $form->setAttribute('action', $this->url()->fromRoute());
        if ($redirect) {
            $form->get($redirectKey)->setValue($redirect);
        }

        if ($post && $form->setData($post)->isValid()) {

            // clear adapters
            $this->cmsAuthentication()->getAuthenticationAdapter()->resetAdapters();
            $this->cmsAuthentication()->getAuthenticationService()->clearIdentity();

            $routeMatch = $this->getEvent()->getRouteMatch();
            $this->getRequest()->setPost(new Parameters($post));
            $this->options->setLoginRoute($routeMatch->getMatchedRouteName());
            $this->forwardingController = $routeMatch->getParam('controller');

            return $this->forward()->dispatch(
                $this->forwardingController,
                ['action' => 'authenticate']
            );
        }

        $this->forwardingController = null;

        $registrationRoute    = $this->options->getRegistrationRoute();
        $resetCredentialRoute = $this->options->getResetCredentialRoute();

        return new ViewModel(compact('form', 'registrationRoute', 'resetCredentialRoute'));
    }
324743
protected function redirectToChangePassword()
    {
        // Since this form is loaded via an iframe, this redirect must be performed via javascript
        $changePasswordForm = ChangePasswordForm::create($this, 'ChangePasswordForm');
        $changePasswordForm->sessionMessage(
            _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'),
            'good'
        );

        // Get redirect url
        $changePasswordURL = $this->addBackURLParam(Security::singleton()->Link('changepassword'));
        $changePasswordURLATT = Convert::raw2att($changePasswordURL);
        $changePasswordURLJS = Convert::raw2js($changePasswordURL);
        $message = _t(
            'SilverStripe\\Security\\CMSMemberLoginForm.PASSWORDEXPIRED',
            '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>',
            'Message displayed to user if their session cannot be restored',
            array('link' => $changePasswordURLATT)
        );

        // Redirect to change password page
        $response = HTTPResponse::create()
            ->setBody(<<<PHP
<!DOCTYPE html>
<html><body>
$message
<script type="application/javascript">
setTimeout(function(){top.location.href = "$changePasswordURLJS";}, 0);
</script>
</body></html>
PHP
        );
        return $response;
    }
879592
public function redirectOnSuccess() {
		$params = [];
		if (!empty($this->options['bypass_hidden_from_input'])) {
			foreach ($this->options['bypass_hidden_from_input'] as $v) {
				$params[$v] = $this->options['input'][$v] ?? '';
			}
		}
		if (!empty($this->options['collection_current_tab_id'])) {
			$params[$this->options['collection_current_tab_id']] = $this->form_link;
		}
		$url = \Application::get('mvc.full') . '?' . http_build_query2($params) . '#' . ($this->options['input']['__anchor'] ?? '');
		$this->redirect($url);
	}
42457
def AuthenticatedOrRedirect(invocation):
    
    class AuthenticatedOrRedirect(GiottoInputMiddleware):
        def http(self, request):
            if request.user:
                return request
            return Redirection(invocation)

        def cmd(self, request):
            if request.user:
                return request
            return Redirection(invocation)

    return AuthenticatedOrRedirect
687906
def default_redirect(request, fallback_url, **kwargs):
    
    redirect_field_name = kwargs.get("redirect_field_name", "next")
    next = request.POST.get(redirect_field_name,
                            request.GET.get(redirect_field_name, ''))
    if not next:
        # try the session if available
        if hasattr(request, "session"):
            session_key_value = kwargs.get("session_key_value", "redirect_to")
            next = request.session.get(session_key_value)
    is_safe = functools.partial(
        ensure_safe_url,
        allowed_protocols=kwargs.get("allowed_protocols"),
        allowed_host=request.get_host()
    )
    redirect_to = next if next and is_safe(next) else fallback_url
    # perform one last check to ensure the URL is safe to redirect to. if it
    # is not then we should bail here as it is likely developer error and
    # they should be notified
    is_safe(redirect_to, raise_on_fail=True)
    return redirect_to
446891
def dispatch(self, request, *args, **kwargs):
        
        def wrapper(request, *args, **kwargs):
            if not self.has_permission(request, *args, **kwargs):
                path = urlquote(request.get_full_path())
                login_url = kwargs.pop('login_url', settings.LOGIN_URL)
                redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME)
                return HttpResponseRedirect("%s?%s=%s" % (login_url, redirect_field_name, path))
            else:
                response = self.pre_process(request, *args, **kwargs)
                if not response:
                    return super(SmartView, self).dispatch(request, *args, **kwargs)
                else:
                    return response

        return wrapper(request, *args, **kwargs)
269469
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
    
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                if request.is_json:
                    abort(HTTPStatus.FORBIDDEN)
                else:
                    if msg:
                        flash(msg, category)
                    return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
                                    override=redirect_url)
            return fn(*args, **kwargs)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapper(decorator_args[0])
    return wrapper
323671
private function Configure($RedirectUrl = '') {
      // Create a model to save configuration settings
      $Validation = new Gdn_Validation();
      $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
      $ConfigurationModel->SetField(array('Garden.Locale', 'Garden.Title', 'Garden.RewriteUrls', 'Garden.WebRoot', 'Garden.Cookie.Salt', 'Garden.Cookie.Domain', 'Database.Name', 'Database.Host', 'Database.User', 'Database.Password', 'Garden.Registration.ConfirmEmail', 'Garden.Email.SupportName'));
      
      // Set the models on the forms.
      $this->Form->SetModel($ConfigurationModel);
      
      // Load the locales for the locale dropdown
      // $Locale = Gdn::Locale();
      // $AvailableLocales = $Locale->GetAvailableLocaleSources();
      // $this->LocaleData = array_combine($AvailableLocales, $AvailableLocales);
      
      // If seeing the form for the first time...
      if (!$this->Form->IsPostback()) {
         // Force the webroot using our best guesstimates
         $ConfigurationModel->Data['Database.Host'] = 'localhost';
         $this->Form->SetData($ConfigurationModel->Data);
      } else {         
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->ApplyRule('Database.Name', 'Required', 'You must specify the name of the database in which you want to set up Vanilla.');
			
         // Let's make some user-friendly custom errors for database problems
         $DatabaseHost = $this->Form->GetFormValue('Database.Host', '~~Invalid~~');
         $DatabaseName = $this->Form->GetFormValue('Database.Name', '~~Invalid~~');
         $DatabaseUser = $this->Form->GetFormValue('Database.User', '~~Invalid~~');
         $DatabasePassword = $this->Form->GetFormValue('Database.Password', '~~Invalid~~');
         $ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost);
         try {
            $Connection = new PDO(
               $ConnectionString,
               $DatabaseUser,
               $DatabasePassword
            );
         } catch (PDOException $Exception) {
            switch ($Exception->getCode()) {
               case 1044:
                  $this->Form->AddError(T('The database user you specified does not have permission to access the database. Have you created the database yet? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
                  break;
               case 1045:
                  $this->Form->AddError(T('Failed to connect to the database with the username and password you entered. Did you mistype them? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
                  break;
               case 1049:
                  $this->Form->AddError(T('It appears as though the database you specified does not exist yet. Have you created it yet? Did you mistype the name? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
                  break;
               case 2005:
                  $this->Form->AddError(T("Are you sure you've entered the correct database host name? Maybe you mistyped it? The database reported: <code>%s</code>"), strip_tags($Exception->getMessage()));
                  break;
               default:
                  $this->Form->AddError(sprintf(T('ValidateConnection'), strip_tags($Exception->getMessage())));
               break;
            }
         }
			
         $ConfigurationModel->Validation->ApplyRule('Garden.Title', 'Required');
         
         $ConfigurationFormValues = $this->Form->FormValues();
         if ($ConfigurationModel->Validate($ConfigurationFormValues) !== TRUE || $this->Form->ErrorCount() > 0) {
            // Apply the validation results to the form(s)
            $this->Form->SetValidationResults($ConfigurationModel->ValidationResults());
         } else {
            $Host = array_shift(explode(':',Gdn::Request()->RequestHost()));
            $Domain = Gdn::Request()->Domain();

            // Set up cookies now so that the user can be signed in.
            $ExistingSalt = C('Garden.Cookie.Salt', FALSE);
            $ConfigurationFormValues['Garden.Cookie.Salt'] = ($ExistingSalt) ? $ExistingSalt : RandomString(10);
            $ConfigurationFormValues['Garden.Cookie.Domain'] = ''; // Don't set this to anything by default. # Tim - 2010-06-23
            // Additional default setup values.
            $ConfigurationFormValues['Garden.Registration.ConfirmEmail'] = TRUE;
            $ConfigurationFormValues['Garden.Email.SupportName'] = $ConfigurationFormValues['Garden.Title'];

            $ConfigurationModel->Save($ConfigurationFormValues, TRUE);
                    
            // If changing locale, redefine locale sources:
            $NewLocale = 'en-CA'; // $this->Form->GetFormValue('Garden.Locale', FALSE);
            if ($NewLocale !== FALSE && Gdn::Config('Garden.Locale') != $NewLocale) {
               $ApplicationManager = new Gdn_ApplicationManager();
               $Locale = Gdn::Locale();
               $Locale->Set($NewLocale, $ApplicationManager->EnabledApplicationFolders(), Gdn::PluginManager()->EnabledPluginFolders(), TRUE);
            }

            // Install db structure & basic data.
            $Database = Gdn::Database();
            $Database->Init();
            $Drop = FALSE; // Gdn::Config('Garden.Version') === FALSE ? TRUE : FALSE;
            $Explicit = FALSE;
            try {
               include(PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'structure.php');
            } catch (Exception $ex) {
               $this->Form->AddError($ex);
            }
         
            if ($this->Form->ErrorCount() > 0)
               return FALSE;

            // Create the administrative user
            $UserModel = Gdn::UserModel();
            $UserModel->DefineSchema();
            $UsernameError = T('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.');
            $UserModel->Validation->ApplyRule('Name', 'Username', $UsernameError);
            $UserModel->Validation->ApplyRule('Name', 'Required', T('You must specify an admin username.'));
            $UserModel->Validation->ApplyRule('Password', 'Required', T('You must specify an admin password.'));
            $UserModel->Validation->ApplyRule('Password', 'Match');
            $UserModel->Validation->ApplyRule('Email', 'Email');
            
            if (!($AdminUserID = $UserModel->SaveAdminUser($ConfigurationFormValues))) {
               $this->Form->SetValidationResults($UserModel->ValidationResults());
            } else {
               // The user has been created successfully, so sign in now.
               SaveToConfig('Garden.Installed', TRUE, array('Save' => FALSE));
               Gdn::Session()->Start($AdminUserID, TRUE);
               SaveToConfig('Garden.Installed', FALSE, array('Save' => FALSE));
            }
            
            if ($this->Form->ErrorCount() > 0)
               return FALSE;
            
            // Assign some extra settings to the configuration file if everything succeeded.
            $ApplicationInfo = array();
            include(CombinePaths(array(PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php')));
            
            // Detect rewrite abilities
            $CanRewrite = (bool)$this->Form->GetFormValue('RewriteUrls');
      
            SaveToConfig(array(
               'Garden.Version' => ArrayValue('Version', GetValue('Dashboard', $ApplicationInfo, array()), 'Undefined'),
               'Garden.RewriteUrls' => $CanRewrite,
               'Garden.CanProcessImages' => function_exists('gd_info'),
               'EnabledPlugins.GettingStarted' => 'GettingStarted', // Make sure the getting started plugin is enabled
               'EnabledPlugins.HtmLawed' => 'HtmLawed' // Make sure html purifier is enabled so html has a default way of being safely parsed.
            ));
         }
      }
      return $this->Form->ErrorCount() == 0 ? TRUE : FALSE;
   }
1059066
def resolve_redirection(self, request, context):
        """"""
        current_page = context['current_page']
        lang = context['lang']
        if current_page.redirect_to_url:
            return HttpResponsePermanentRedirect(current_page.redirect_to_url)

        if current_page.redirect_to:
            return HttpResponsePermanentRedirect(
                current_page.redirect_to.get_url_path(lang))
90302
function _login (directoryUrl, publicUrl) {
  return (req, res) => {
    res.redirect(directoryUrl + '/login?redirect=' + encodeURIComponent(req.query.redirect || publicUrl))
  }
}
1215194
public void reloadPlugin() {
        sendConsoleMessage(Level.INFO, "Starting up!");
        sendConsoleMessage(Level.INFO, "Loading the Configuration");
        config = new ConfigurationManager(serverCaller);
        mainConfig = config.loadFile(serverCaller.getDataFolder(), "config.yml");
        if (!mainConfig.has("System.Setup")) {
            initializeConfig();
        }
        if (!getMainConfig().has("System.Database.Prefix")) {
            getMainConfig().setValue("System.Database.Prefix", "cc3_");
        }

        languageManager = new LanguageManager(serverCaller, serverCaller.getDataFolder(), "lang.yml");
        loadLanguage();
        serverCaller.setCommandPrefix(languageManager.getString("command_prefix"));
        commandManager.setCurrentLevel(1);
        initialiseDatabase();
        updateDatabase();
        initializeCurrency();
        sendConsoleMessage(Level.INFO, getLanguageManager().getString("loading_default_settings"));
        loadDefaultSettings();
        sendConsoleMessage(Level.INFO, getLanguageManager().getString("default_settings_loaded"));
        startUp();
        sendConsoleMessage(Level.INFO, getLanguageManager().getString("ready"));

    }
1008712
public function getHome()
    {
        // Vars
        $config = config('decoy.site.post_login_redirect');
        $auth = app('decoy.user');

        // Make the config optional
        if ($config) {

            // Support the config being a colsure
            if (is_callable($config)) {
                $config = call_user_func($config);
            }

            // Make sure the user has permission before redirecting
            if ($auth->can('read', $config)) {
                return $config;
            }
        }

        // If the user doesn't have permission, iterate through the navigation
        // options until one is permissible
        foreach ($this->getNavUrls() as $url) {
            if ($auth->can('read', $url)) {
                return $url;
            }
        }

        // Default to their account page, which all can access
        return $auth->getUserUrl();
    }
428536
protected function initialRedirectUrl() {

        $defaultUrl = '/'. $this->controller->id . '/' . $this->controller->defaultAction;

        if (isset($this->controller->module->id) && !$this->controller->module instanceof Application) {
            $defaultUrl = '/' . $this->controller->module->id . $defaultUrl;
        }

        if ( empty( $this->successUrl ) ) {
            $this->successUrl = $defaultUrl;
        }

        if ( empty( $this->failedUrl ) ) {
            $this->failedUrl = $defaultUrl;
        }

    }