Creates a basic auth security handler.
@throws Exception
345624
protected SecurityHandler createSecurityHandler() throws Exception {
        HashLoginService l = new HashLoginService();
        // UserStore is now separate store entity and must be added to HashLoginService
        UserStore userStore = new UserStore();
        l.setUserStore(userStore);
        for (User user : Users.getUsers()) {
            userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
        }
        l.setName("apimanrealm");

        ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
        csh.setAuthenticator(new BasicAuthenticator());
        csh.setRealmName("apimanrealm");
        csh.setLoginService(l);

        return csh;
    }
1316046
@Override
    public ProxyHandler createProxyHandler() {
        final HttpProxyHandler handler;

        // For reasons that are not immediately clear, HttpProxyHandler doesn't allow null usernames/passwords if
        // specified. If we want them to be null, we have to use the constructor that doesn't take a username/password
        // at all.
        if (this.username != null && this.password != null) {
            handler = new HttpProxyHandler(this.proxyAddress, this.username, this.password);
        } else {
            handler = new HttpProxyHandler(this.proxyAddress);
        }

        return handler;
    }
366583
final protected function onAuth()
    {
        $authService = $this->getAuthService();

        $this->authManager->setAuthService($authService);

        if ($this->authActive === true) {
            if ($authService->isLoggedIn()) {
                $this->onSuccess();
            } else {
                $this->onFailure();
            }
        }

        // Now handle RBRAC if present
        if ($this->hasRbacRules()) {
            // Check if provided user has enough privileges
            if (!$this->hasRight($authService->getRole())) {
                $this->onNoRights();
            }
        }
    }
640148
protected function prepareSecurityTokenRequest($username, $password, $address)
    {
        $fileName = __DIR__ . '/xml/SAML.xml';
        if (!file_exists($fileName)) {
            throw new \Exception("The file $fileName does not exist");
        }

        $template = file_get_contents($fileName);
        $template = str_replace('{username}', $username, $template);
        $template = str_replace('{password}', $password, $template);
        $template = str_replace('{address}', $address, $template);
        return $template;
    }
731287
public void handle(RequestContext context, AuthenticationException e) throws SecurityProviderException,
            IOException {
        saveRequest(context);

        String loginFormUrl = getLoginFormUrl();

        if (StringUtils.isNotEmpty(loginFormUrl)) {
            RedirectUtils.redirect(context.getRequest(), context.getResponse(), loginFormUrl);
        } else {
            sendError(e, context);
        }
    }
464140
private void init() throws Exception {
        if (sslContext == null) {
            if (keyStoreInputStream == null && sslConfig.getKeyStorePath() == null &&
		trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
                TrustManager[] trust_managers = null;
                if (sslConfig.isTrustAll()) {
                    logger.debug("No keystore or trust store configured.  ACCEPTING UNTRUSTED CERTIFICATES!!!!!");
                    // Create a trust manager that does not validate certificate chains
                    TrustManager trustAllCerts = new X509TrustManager() {
			    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			    }
			    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
			    }

			    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
			    }
			};
                    trust_managers = new TrustManager[] { trustAllCerts };
                }
                
                SecureRandom secureRandom = (sslConfig.getSecureRandomAlgorithm() == null)?null:
		    SecureRandom.getInstance(sslConfig.getSecureRandomAlgorithm());
                sslContext = SSLContext.getInstance(sslConfig.getProtocol());
                sslContext.init(null, trust_managers, secureRandom);
            } else {
                // verify that keystore and truststore
                // parameters are set up correctly               
                checkKeyStore();

                KeyStore keyStore = loadKeyStore();
                KeyStore trustStore = loadTrustStore();

                Collection<? extends CRL> crls = loadCRL(sslConfig.getCrlPath());

                if (sslConfig.isValidateCerts() && keyStore != null) {
                    if (sslConfig.getCertAlias() == null) {
                        List<String> aliases = Collections.list(keyStore.aliases());
			sslConfig.setCertAlias(aliases.size() == 1 ? aliases.get(0) : null);
                    }

                    Certificate cert = sslConfig.getCertAlias() == null?null:
			keyStore.getCertificate(sslConfig.getCertAlias());
                    if (cert == null) {
                        throw new Exception("No certificate found in the keystore" + (sslConfig.getCertAlias() == null ? "":" for alias " + sslConfig.getCertAlias()));
                    }

                    CertificateValidator validator = new CertificateValidator(trustStore, crls);
                    validator.setMaxCertPathLength(sslConfig.getMaxCertPathLength());
                    validator.setEnableCRLDP(sslConfig.isEnableCRLDP());
                    validator.setEnableOCSP(sslConfig.isEnableOCSP());
                    validator.setOcspResponderURL(sslConfig.getOcspResponderURL());
                    validator.validate(keyStore, cert);
                }

                KeyManager[] keyManagers = getKeyManagers(keyStore);
                TrustManager[] trustManagers = getTrustManagers(trustStore, crls);

                SecureRandom secureRandom = (sslConfig.getSecureRandomAlgorithm() == null)?null:
		    SecureRandom.getInstance(sslConfig.getSecureRandomAlgorithm());
                sslContext = (sslConfig.getProvider() == null)?
		    SSLContext.getInstance(sslConfig.getProtocol()):
		    SSLContext.getInstance(sslConfig.getProtocol(), sslConfig.getProvider());
                sslContext.init(keyManagers, trustManagers, secureRandom);

                SSLEngine engine = newSslEngine();
                
                logger.info("Enabled Protocols {} of {}",
			    Arrays.asList(engine.getEnabledProtocols()),
			    Arrays.asList(engine.getSupportedProtocols()));
		logger.debug("Enabled Ciphers {} of {}",
			     Arrays.asList(engine.getEnabledCipherSuites()),
			     Arrays.asList(engine.getSupportedCipherSuites()));
            }
        }
    }
635189
function guard($authorizeOfGuardName)
    {
        if (! $this->guards->has($authorizeOfGuardName) )
            throw new \Exception(sprintf('Guard Authorization (%s) Not Registered.', $authorizeOfGuardName));

        $guard = $this->guards->get($authorizeOfGuardName);
        return $guard;
    }
278217
protected function passwordProtectedRequest()
    {
        $oInput = Factory::service('Input');
        header('WWW-Authenticate: Basic realm="' . APP_NAME . ' - Restricted Area"');
        header($oInput->server('SERVER_PROTOCOL') . ' 401 Unauthorized');
        $oErrorHandler = Factory::service('ErrorHandler');
        $oErrorHandler->renderErrorView(401);
        exit(401);
    }
894532
public function create() {
		$ssoClient = new \Flowpack\SingleSignOn\Client\Domain\Model\SsoClient();
		if ((string)$this->clientServiceBaseUri === '') {
			throw new Exception('Missing Flowpack.SingleSignOn.Client.client.serviceBaseUri setting', 1351075078);
		}
		$ssoClient->setServiceBaseUri($this->clientServiceBaseUri);
		if ((string)$this->clientPublicKeyFingerprint === '') {
			throw new Exception('Missing Flowpack.SingleSignOn.Client.client.publicKeyFingerprint setting', 1351075159);
		}
		$ssoClient->setPublicKeyFingerprint($this->clientPublicKeyFingerprint);
		return $ssoClient;
	}
1121088
protected function _auth()
    {
        if ($this->_helo == false) {
            throw new SMTPException(__('Must call EHLO (or HELO) before calling AUTH'));
        } elseif ($this->_auth !== false) {
            throw new SMTPException(__('Can not call AUTH again.'));
        }

        $this->_send('AUTH LOGIN');
        $this->_expect(334);
        $this->_send(base64_encode($this->_user));
        $this->_expect(334);
        $this->_send(base64_encode($this->_pass));
        $this->_expect(235);
        $this->_auth = true;
    }
813616
private Map<String, String> getHttpHeaderBasic() throws Exception {
        
        return new HashMap<String, String>(){{
            put("Authorization", "Basic " + getHttpHeaderBasicKey());
        }};
    }
118487
public function start(Request $request, AuthenticationException $exception = null)
    {
        if ($exception) {
            $message = $exception->getMessage();
            if (empty($message) && is_callable([$exception, 'getMessageKey'])) {
                $message = $e->getMessageKey();
            }
        } else {
            $message = 'Full authentication is required to access this resource.';
        }

        $content = [
            'errors' => [
                'code' => 401,
                'message' => $this->translator->trans($message, [], 'errors')
            ]
        ];

        return new JsonResponse($content, JsonResponse::HTTP_UNAUTHORIZED);
    }
1056116
private function httpHandler()
    {
        if (config()->loadFile('view') === true) {
            // Instantiate Http UserAgent Service
            $this->services->load(Framework\Http\UserAgent::class, 'userAgent');

            // Instantiate Http View Service
            $this->services->load(Framework\Http\Parser::class);

            // Instantiate Http View Service
            $this->services->load(Framework\Http\View::class);

            // Instantiate Http Presenter Service
            $this->services->load(Framework\Http\Presenter::class);
        }

        // Instantiate Http Router Service
        $this->services->load(Framework\Http\Router::class);

        if (profiler() !== false) {
            profiler()->watch('Parse Router Request');
        }
        router()->parseRequest();

        if (config()->loadFile('session') === true) {

            // Instantiate Session Service
            $session = new Session(config('session', true));
            $session->setLogger($this->services->get('logger'));

            if ( ! $session->isStarted()) {
                $session->start();
            }

            $this->services->add($session, 'session');

            if ($session->has('language') and $this->services->has('language')) {
                language()->setDefault($session->get('language'));
            } else {
                $session->set('language', language()->getDefault());
            }

            if (config('security')->protection[ 'csrf' ] === true) {
                $csrfProtection = new Security\Protections\Csrf();
                $this->services->add($csrfProtection, 'csrfProtection');
            }

            if (config('security')->protection[ 'xss' ] === true) {
                $xssProtection = new Security\Protections\Xss();
                $this->services->add($xssProtection, 'xssProtection');
            }
        }

        // Instantiate Http Middleware Service
        $this->services->load(Framework\Http\Middleware::class);

        if (profiler() !== false) {
            profiler()->watch('Running Middleware Service: Pre Controller');
        }
        middleware()->run();

        if ($this->services->has('controller')) {
            $controller = $this->services->get('controller');

            $controllerParameter = dash($controller->getParameter());
            $controllerRequestMethod = dash($controller->getRequestMethod());

            $modules = $this->modules->getArrayCopy();
            
            // Run Module Autoloader
            foreach ($modules as $module) {
                if (in_array($module->getType(), ['KERNEL', 'FRAMEWORK'])) {
                    continue;
                }

                // Autoload Module Language
                if ($this->services->has('language')) {
                    language()->loadFile($module->getParameter());
                }

                // Autoload Module Model
                $module->loadModel();

                // Add View Resource Directory
                if($this->services->has('view')) {
                    view()->addFilePath($module->getResourcesDir());
                    presenter()->assets->pushFilePath($module->getResourcesDir());
                }
            }
            
            if ($this->services->has('view')) {
                presenter()->initialize();
            }

            // Autoload Language
            if ($this->services->has('language')) {
                language()->loadFile($controller->getParameter());
                language()->loadFile($controller->getRequestMethod());
                language()->loadFile($controller->getParameter() . '/' . $controller->getRequestMethod());
            }

            // Autoload Model
            $modelClassName = str_replace(['Controllers', 'Presenters'], 'Models', $controller->getName());

            if (class_exists($modelClassName)) {
                $this->models->load($modelClassName, 'controller');
            }

            if ($this->services->has('view')) {
                // Autoload Presenter
                $presenterClassName = str_replace('Controllers', 'Presenters', $controller->getName());

                if (class_exists($presenterClassName)) {
                    $presenterClassObject = new $presenterClassName();
                    if ($presenterClassObject instanceof Framework\Http\Presenter) {
                        $this->services->add($presenterClassObject, 'presenter');
                    }
                }
            }

            // Initialize Controller
            if (profiler() !== false) {
                profiler()->watch('Calling Hooks Service: Pre Controller');
            }

            hooks()->callEvent(Framework\Services\Hooks::PRE_CONTROLLER);

            if (profiler() !== false) {
                profiler()->watch('Instantiating Requested Controller: ' . $controller->getClass());
            }
            $requestController = $controller->getInstance();

            if (method_exists($requestController, '__reconstruct')) {
                $requestController->__reconstruct();
            }

            if (profiler() !== false) {
                profiler()->watch('Calling Hooks Service: Post Controller');
            }
            hooks()->callEvent(Framework\Services\Hooks::POST_CONTROLLER);

            if (profiler() !== false) {
                profiler()->watch('Calling Middleware Service: Post Controller');
            }
            middleware()->run();

            $requestMethod = $controller->getRequestMethod();
            $requestMethodArgs = $controller->getRequestMethodArgs();

            // Call the requested controller method
            if (profiler() !== false) {
                profiler()->watch('Execute Requested Controller Method');
            }

            ob_start();
            $requestController->__call($requestMethod, $requestMethodArgs);
            $requestControllerOutput = ob_get_contents();
            ob_end_clean();

            if (is_numeric($requestControllerOutput)) {
                output()->sendError($requestControllerOutput);
            } elseif (is_bool($requestControllerOutput)) {
                if ($requestControllerOutput === true) {
                    output()->sendError(200);
                } elseif ($requestControllerOutput === false) {
                    output()->sendError(204);
                }
            } elseif (is_array($requestControllerOutput) or is_object($requestControllerOutput)) {
                output()->sendPayload($requestControllerOutput);
            } elseif ($requestController instanceof Framework\Http\Controllers\Restful) {
                if (empty($requestControllerOutput)) {
                    $requestController->sendError(204);
                } elseif (is_string($requestControllerOutput)) {
                    if (is_json($requestControllerOutput)) {
                        output()->setContentType('application/json');
                    } else {
                        output()->setContentType('text/plain');
                    }

                    echo $requestControllerOutput;
                }
            } elseif (is_string($requestControllerOutput)) {
                if (is_json($requestControllerOutput)) {
                    output()->setContentType('application/json');
                    echo $requestControllerOutput;
                } elseif ($this->services->has('view')) {
                    if (empty($requestControllerOutput)) {
                        $filenames = [
                            $controllerRequestMethod,
                            $controllerParameter . DIRECTORY_SEPARATOR . $controllerRequestMethod,
                        ];

                        if ($controllerRequestMethod === 'index') {
                            array_unshift($filenames, $controllerParameter);
                        }

                        foreach ($filenames as $filename) {
                            if (false !== ($filePath = view()->getFilePath($filename))) {
                                view()->load($filePath);
                                break;
                            }
                        }
                    } else {
                        presenter()->partials->offsetSet('content', $requestControllerOutput);
                    }

                    if (presenter()->partials->offsetExists('content')) {
                        if(is_ajax()) {
                            echo presenter()->partials->content;
                        } else {
                            $htmlOutput = view()->render();

                            if (empty($htmlOutput)) {
                                output()->sendError(204);
                            } else {
                                output()->setContentType('text/html');
                                output()->send($htmlOutput);
                            }
                        }
                    } else {
                        output()->sendError(204);
                    }
                } elseif (empty($requestControllerOutput) or $requestControllerOutput === '') {
                    output()->sendError(204);
                } else {
                    output()->setContentType('text/plain');
                    output()->send($requestControllerOutput);
                }
            }
        } else {
            // Show Error (404) Page Not Found
            output()->sendError(404);
        }
    }
477369
function () {
                try {
                    authHandler.sign(authInterface, context.item.request, function (err) {
                        // handle all types of errors in one place, see catch block
                        if (err) { throw err; }

                        done();
                    });
                }
                catch (err) {
                    // handles synchronous and asynchronous errors in auth.sign
                    run.triggers.console(context.coords,
                        'warn',
                        'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
                        err
                    );

                    // swallow the error, we've warned the user
                    done();
                }
            }
233920
public function handleResetPassword()
    {
        if ($this->presenter->isAjax())
        {
            $allowedReset = (
                $this->presenter->user->isAllowed(UserAuthorizator::RES_RESET_PASSWORD_HANDLE)
                && $this->presenter->user->getId() !== $this->userEntity->getId()
                && (
                    !$this->userEntity->isInRole(UserAuthorizator::ROLE_ADMIN)
                    || $this->presenter->user->isAllowed(UserAuthorizator::RES_EDIT_ADMINS)
                )
            );

            if (!$allowedReset)
            {
                throw new ForbiddenRequestException;
            }

            try
            {
                $this->userManager->resetPassword($this->userEntity);

                $this->presenter->notificationAjax(
                    'Heslo resetováno',
                    'Heslo bylo úspěšně resetováno a uživateli byl odeslán e-mail.',
                    'success'
                );
            }
            catch (\Exception $exception)
            {
                throw $exception;
            }
        }
    }
929460
function authenticator($authenticatorName = self::AUTHENTICATOR_DEFAULT)
    {
        if (!$this->authenticators->has($authenticatorName))
            throw new \Exception(sprintf('Authenticator (%s) Not Registered.', $authenticatorName));

        $authenticator = $this->authenticators->get($authenticatorName);
        return $authenticator;
    }
531052
public static function generateSigningKeypair() : Keypair
    {
        try {
            $keypair = \sodium_crypto_sign_keypair();
            return new Keypair(
                \sodium_crypto_sign_secretkey($keypair),
                \sodium_crypto_sign_publickey($keypair)
            );
        } catch (SodiumException $e) {
            throw new Exception($e->getMessage());
        }
    }