A middleware to be used in routes that returns a temporary unavailable response if an administrator has disabled the app.

@return \BearFramework\App\Response|null
168506
public function disabledCheck(): ?\BearFramework\App\Response
    {
        $currentUserExists = Config::hasServer() && (Config::hasFeature('USERS') || Config::hasFeature('USERS_LOGIN_*')) ? $this->currentUser->exists() : false;
        $settings = $this->app->bearCMS->data->settings->get();
        $isDisabled = !$currentUserExists && $settings->disabled;
        if ($isDisabled) {
            return new App\Response\TemporaryUnavailable(htmlspecialchars($settings->disabledText));
        }
        return null;
    }
1086395
public function getView() {
		
		try {
			
			if ($this->view) {
				
				$file = $this->modulePath .'/view'. ucfirst($this->view) .'.php';
				
				if (!file_exists($file)) {
					if ($this->app->currentUser->areKeysPopulated()) {
						throw new \Exception('View file '. $file .' has not been found');
					} else {
						die('Access denied');
					}
				}

				include_once($file);

				$viewName = ucfirst($this->name) .'View'. ucfirst($this->view);
				
				if (!class_exists($viewName)) {
					throw new \Exception('Class ' . $viewName . ' was not found in file ' . $file);
				}
				
				return new $viewName();
				
			} else {
				
				throw new \Exception('No view file has been set');
				
			}
		
		} catch (\Exception $e) {
			
			// set the error in the log
			$this->app->logError($e->getMessage());
			
			// get a fall-back referer or default and redirect the user
			$url = !isset($_SERVER['REFERER']) ? $_SERVER['REFERER'] : BASE_HREF;
			$this->redirect($url, TRUE);
			
		}
		
		return NULL;
		
	}
804652
protected function retryMiddleware()
    {
        return Middleware::retry(function (
            $retries,
            RequestInterface $request,
            ResponseInterface $response = null
        ) {
            // Limit the number of retries to 2
            if ($retries < $this->app->config->get('http.max_retries', 1) && $response && $body = $response->getBody()) {
                // Retry on server errors
                $response = json_decode($body, true);

                if (!empty($response['errcode']) && in_array(abs($response['errcode']), [40001, 40014, 42001], true)) {
                    $this->accessToken->refresh();
                    $this->app['logger']->debug('Retrying with refreshed access token.');

                    return true;
                }
            }

            return false;
        }, function () {
            return abs($this->app->config->get('http.retry_delay', 500));
        });
    }
815083
public function inAction()
    {
        $id = $this
            ->request
            ->query
            ->get('id');

        $ids = explode(',', $this
            ->request
            ->query
            ->get('ids'));

        $result = $this
                ->locationProvider
                ->in($id, $ids);

        return $this->createResponseObject(function () use ($result) {
            return ['result' => $result];
        });
    }
1250153
public function getUrl()
    {
        if (\Yii::$app === null || $this->getIsConsoleRequest()) {
            return null;
        }

        return \Yii::$app->getRequest()->getAbsoluteUrl();
    }
27145
public function getInternalResponse()
    {
        if (null === $this->internalResponse) {
            @trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', \get_class($this).'::'.__FUNCTION__), E_USER_DEPRECATED);
            // throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
        }

        return $this->internalResponse;
    }
1045853
public function handler(): Response
    {
        if ($this->redirect) {
            return response(null, 302, ['Location' => $this->redirect]);
        } elseif ($this->request->query->has('error')) {
            return view('error.twig', [
                'error' => $this->request->query->get('error'),
                'message' => $this->request->query->get('message')
            ]);
        } else {
            $this->addAssets();
            return view($this->template, $this->data);
        }
    }
1250647
protected function getAccessToken()
    {
        switch ($this->grant) {
            case 'provided_token':
                return $this->token;

            case 'client_credentials':
                return $this->getFrameworkBridge()->getClientToken();

            case 'authorization_code':
                $user = $this->getFrameworkBridge()->getCurrentUser();

                if (! $user) {
                    return null;
                }

                return $user->getOAuthToken();

            default:
                throw new \Exception('Unsupported grant type. Check $this->grant.');
        }
    }
800159
public function get()
    {
        $wordpressUri = trim(config('app.wp.dir', 'cms'), '\/');
        $route = $this->router->any($wordpressUri.'/wp-admin/{any?}', function () {
            return new Response();
        });

        $route->middleware('admin');
        $route->bind($this->request);

        return $route;
    }
1332534
public function getUserInRequest() {
    if (isset($_COOKIE[$this->cookieName])) {
      $user = $this->validateToken($_COOKIE[$this->cookieName],
          $this->clientId);
      if ($user) {
        $accountInfo = $this->getUserById($user->getUserId());
        $accountInfo->setProviderId($user->getProviderId());
        return $accountInfo;
      }
    }
    return null;
  }
121153
public function getClient() {
		if (!$this->client) {
			// Create custom handler stack with middlewares
			$stack = HandlerStack::create();

			$context = $this;
			$stack->push(Middleware::mapResponse(function (ResponseInterface $response) use ($context) {
   				// If a new version of this accessor is available, store its COID
				if ($response->hasHeader('C-Accessor-Latest-Version'))
      				$context->setLatestAccessorVersionCOID(
						new IRI($response->getHeaderLine('C-Accessor-Latest-Version')));
    			return $response;
			}));

			// Prepare client options
			$options = [
				'base_uri' => str_replace('{aauid}', AAUIDParser::getAAUID($this->getAAUID()), $this->agwBaseUrl),
				'headers' => [
					'Authorization' => 'Bearer '.$this->getAccessToken()
				],
				'handler' => $stack
			];
			if (isset($this->request) && $this->request->hasHeader('X-Forwarded-For')) {
				$options['headers']['X-Forwarded-For'] = $this->request->getHeaderLine('X-Forwarded-For');				
			}

			// Create client
			$this->client = new Client($options);
		}
		return $this->client;
	}
665532
public function resourceAction()
    {
        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        if (!$this->server->verifyResourceRequest($this->getOAuth2Request())) {
            $response   = $this->server->getResponse();
            $parameters = $response->getParameters();
            $errorUri   = isset($parameters['error_uri']) ? $parameters['error_uri'] : null;
            return new ApiProblemResponse(
                new ApiProblem(
                    $response->getStatusCode(),
                    $parameters['error_description'],
                    $errorUri,
                    $parameters['error']
                )
            );
        }
        $httpResponse = $this->getResponse();
        $httpResponse->setStatusCode(200);
        $httpResponse->getHeaders()->addHeaders(array('Content-type' => 'application/json'));
        $httpResponse->setContent(
            json_encode(array('success' => true, 'message' => 'You accessed my APIs!'))
        );
        return $httpResponse;
    }
661683
public function logout()
    {

        $response = $this->requestToken(self::REVOKE_ENDPOINT, array(
            'token' => $this->_auth->accessToken()
        ));

        $this->_auth->reset();

        return $response;

    }
519565
public function handler(): Response
    {
        $this->auth(null);
        $data = $this->validate([
            'username' => [
                new NotBlank()
            ],
            'password' => [
                new NotBlank()
            ]
        ]);
        $member = Member::search($data['username']);
        if (!$member) {
            throw new HttpUnauthorizedException();
        }
        if (password_verify($data['password'], $member->getPassword())) {
            $this->auth($member);
            $this->log('info', 'Login successfully');
            return response();
        } else {
            $this->log('info', 'Login failed');
            throw new HttpUnauthorizedException();
        }
    }
126837
public function tokenAction()
    {
        // Can't do anything if not HTTP request...
        if (!$this->request instanceof HttpRequest) {
            return null;
        }

        // Currently, ZF2 Http Request object is not PSR-7 compliant, therefore we need to create a new one from
        // globals, and then convert the response back to ZF2 format

        $request  = ServerRequestFactory::fromGlobals();
        $response = $this->authorizationServer->handleTokenRequest($request);

        return $this->convertToZfResponse($response);
    }
928728
public function notFound(): Response
    {
        $this->response->setStatus(404);
        $this->response->setBody('<html><title>404 Not found</title>404 Not found</html>');
        return $this->response;
    }
580687
public function requestAccessToken()
    {
        try {
            $this->session->requestAccessToken($_GET['code']);
            return $this;
        } catch (Exception $e) {
            $this->redirectToSpotifyAuthorizeUrl();
        }
    }