Ejemplo n.º 1
0
 /**
  * @param Event                  $event
  * @param MvcDispatcherInterface $dispatcher
  */
 public function afterDispatchLoop(Event $event, MvcDispatcherInterface $dispatcher, $data)
 {
     $data = $dispatcher->getReturnedValue();
     // Force returned value to an array.
     $dispatcher->setReturnedValue(json_decode(json_encode($data), true));
     $this->response->setJsonContent($data, JSON_PRETTY_PRINT);
     $this->response->setContentType("application/json", "UTF-8");
     $this->response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
 }
Ejemplo n.º 2
0
 public function beforeExecuteRoute($event, DispatcherInterface $dispatcher)
 {
     $defaultNamespace = $dispatcher->getDefaultNamespace();
     $namespace = $dispatcher->getNamespaceName();
     if (strpos($namespace, $defaultNamespace) === 0) {
         $namespace = substr($namespace, strlen($defaultNamespace));
     }
     $parts = array_filter(explode('\\', strtolower($namespace)));
     $parts[] = $dispatcher->getControllerName();
     $parts[] = $dispatcher->getActionName();
     $this->view->pick(implode(DIRECTORY_SEPARATOR, $parts));
 }
Ejemplo n.º 3
0
 /**
  * @param \Phalcon\Mvc\Dispatcher|\Phalcon\Mvc\DispatcherInterface $dispatcher
  * @return bool
  */
 public function beforeExecuteRoute($dispatcher)
 {
     $this->operator = new OperatorIdentity();
     $this->operator->cookies = $this->cookies;
     $this->operator->load();
     // 判断登录
     $moduleConfig = $this->di->get('moduleConfig');
     $controllerName = $dispatcher->getControllerName();
     $actionName = $dispatcher->getActionName();
     if ($controllerName == $moduleConfig->operator->login->controller && $actionName == $moduleConfig->operator->login->action) {
         return true;
     }
     if ($this->operator->isLogin()) {
         // 判断权限
         $result = OperatorGroupRight::verify($this->operator->group, $controllerName, $actionName, $dispatcher->getDI());
         // 权限不足,输出错误
         if (!$result) {
             $content = '';
             if ($this->request->isAjax()) {
                 $resp = new ResponseResult();
                 $resp->sendError(ResponseResultStatus::RIGHT_VERIFY_FAIL, '权限不足!');
                 $content = $resp->getContent();
             } else {
                 $content = '访问权限不足!';
             }
             $this->view->disable();
             echo $content;
         }
         return $result;
     }
     if ($this->request->isAjax()) {
         $resp = new ResponseResult();
         $resp->sendError(ResponseResultStatus::USER_TOKEN_EXPIRES, '未登录!');
         echo $resp->getContent();
     } else {
         $this->response->redirect($moduleConfig->operator->login->url);
     }
     $this->view->disable();
     return false;
 }
Ejemplo n.º 4
0
 /**
  * @param \Phalcon\Events\Event            $event
  * @param \Phalcon\Mvc\DispatcherInterface $dispatcher
  *
  * @return boolean
  *
  * @throws \Sid\Phalcon\AuthMiddleware\Exception
  */
 public function beforeExecuteRoute(\Phalcon\Events\Event $event, \Phalcon\Mvc\DispatcherInterface $dispatcher, $data)
 {
     $methodAnnotations = $this->annotations->getMethod($dispatcher->getHandlerClass(), $dispatcher->getActiveMethod());
     if (!$methodAnnotations->has("AuthMiddleware")) {
         return true;
     }
     $methodAnnotations = $this->annotations->getMethod($dispatcher->getHandlerClass(), $dispatcher->getActiveMethod());
     if (!$methodAnnotations->has("AuthMiddleware")) {
         return true;
     }
     foreach ($methodAnnotations->getAll("AuthMiddleware") as $annotation) {
         $class = $annotation->getArgument(0);
         $authMiddleware = new $class();
         if (!$authMiddleware instanceof \Sid\Phalcon\AuthMiddleware\MiddlewareInterface) {
             throw new \Sid\Phalcon\AuthMiddleware\Exception("Not an auth middleware.");
         }
         if ($authMiddleware->authenticate() !== false) {
             return $authMiddleware->authenticate();
         }
     }
     return false;
 }
Ejemplo n.º 5
0
 /**
  * @param DispatcherInterface $dispatcher
  * @return bool true if cache missed(intercepter injected), false if cache hit(intercepter not injected)
  */
 public function injectInterceptor(DispatcherInterface $dispatcher)
 {
     /**
      * @var \Phalcon\DI $di
      */
     $di = $dispatcher->getDI();
     $config = $di->getConfig();
     // cache is disable
     if (!$config->cache->enable) {
         return true;
     }
     $params = $this->getInterceptorParams($dispatcher);
     if (!$params) {
         return true;
     }
     $methodsAllow = $params['methods'];
     /**
      * @var \Phalcon\Http\Request $request
      */
     $request = $di->getRequest();
     $requestMethod = strtolower($request->getMethod());
     if (false === in_array($requestMethod, $methodsAllow)) {
         return true;
     }
     /**
      * @var \Phalcon\Cache\Backend $cache
      */
     $cache = $di->getViewCache();
     $interceptResult = $this->intercept($request, $params, $cache);
     //cache key matched, response already prepared
     if (true === $interceptResult) {
         $di->getResponse()->send();
         return false;
     }
     $self = $this;
     //Cache missed
     /**
      * @var \Phalcon\Events\Manager $eventsManager
      */
     $eventsManager = $di->getEventsManager();
     $eventsManager->attach('application:beforeSendResponse', function ($event, $application) use($self, $params) {
         $bodyKey = $self->getCacheBodyKey();
         $headersKey = $self->getCacheHeadersKey();
         if (!$bodyKey || !$headersKey) {
             return true;
         }
         /**
          * @var \Phalcon\Http\ResponseInterface $response
          */
         $response = $application->getDI()->getResponse();
         $body = $response->getContent();
         $headers = $response->getHeaders()->toArray();
         $headersCache = array();
         if ($headers) {
             //Filter allowed headers
             $headersCache = array_intersect_key($headers, array_flip($self->getCachableHeaderKeys()));
         }
         $headersCache[Dispatch::CACHE_HEADER_FLAG] = date(DATE_ISO8601);
         $cache = $application->getDI()->getViewCache();
         $request = $application->getDI()->getRequest();
         $callbackKey = $params['jsonp_callback_key'];
         //Jsonp change to json
         if ($params['format'] == 'jsonp' && $callbackKey && ($callbackValue = $request->getQuery($callbackKey))) {
             $body = Dispatch::changeJsonpToJson($body, $callbackValue);
         }
         $cache->save($bodyKey, $body, $params['lifetime']);
         //$cache->save($headersKey, serialize($headersCache), $params['lifetime']);
         $cache->save($headersKey, json_encode($headersCache), $params['lifetime']);
         return true;
     });
     return true;
 }
Ejemplo n.º 6
0
 /**
  *
  *
  * @param $event
  * @param DispatcherInterface $dispatcher
  */
 public function beforeExecuteRoute(Event $event, DispatcherInterface $dispatcher)
 {
     /** @var \Phalcon\DI $di */
     $di = $dispatcher->getDI();
     $config = $di->getConfig();
     // cache is disable
     if (!$config->cache->enable) {
         return;
     }
     $dispatch_cache_config = $dispatcher->getParam('_dispatch_cache');
     if (!$dispatch_cache_config) {
         return;
     }
     /** @var \Phalcon\Http\Request $request */
     $request = $di->getRequest();
     $params = $this->parseParams($dispatch_cache_config);
     $lifetime = intval($params['lifetime']);
     $methodsAllow = $params['methods'];
     if ($lifetime <= 0) {
         return;
     }
     if (!$methodsAllow) {
         $methodsAllow = 'get';
     }
     $methodsAllow = explode('|', strtolower($methodsAllow));
     $requestMethod = strtolower($request->getMethod());
     if (!in_array($requestMethod, $methodsAllow)) {
         return;
     }
     $cache_key_prefix = $_SERVER['HTTP_HOST'] . preg_replace('/[&?]_eva_refresh_dispatch_cache\\=1/i', '', $_SERVER['REQUEST_URI']) . file_get_contents('php://input');
     $cache_key_prefix = md5($cache_key_prefix);
     /** @var \Phalcon\Cache\Backend\Memcache $cache */
     $cache = $di->getViewCache();
     $bodyKey = $cache_key_prefix . '_b';
     $headersKey = $cache_key_prefix . '_h';
     $bodyCached = $cache->get($bodyKey);
     $headersCached = $cache->get($headersKey);
     $hasCached = $headersCached && $bodyCached;
     // cache missing
     if ($di->getRequest()->getQuery('_eva_refresh_dispatch_cache') || !$hasCached) {
         /** @var \Phalcon\Events\Manager $eventsManager */
         $eventsManager = $di->get('eventsManager');
         $eventsManager->attach('application:beforeSendResponse', function ($event, $application) use($di, $headersKey, $bodyKey, $lifetime, $cache) {
             /** @var \Phalcon\Http\ResponseInterface $response */
             $response = $di->getResponse();
             $body = $response->getContent();
             $headers = $response->getHeaders()->toArray();
             !$headers && ($headers = array());
             $headersByHeaderFunc = headers_list();
             if ($headersByHeaderFunc) {
                 $headers = array_merge($headers, $headersByHeaderFunc);
             }
             $headers['Eva-Dsp-Cache'] = time();
             $cache->save($bodyKey, $body, $lifetime);
             $cache->save($headersKey, serialize($headers), $lifetime);
         });
         return;
     }
     /** @var \Phalcon\Http\ResponseInterface $response */
     $response = $di->getResponse();
     if ($hasCached) {
         if ($headersCached) {
             $headersCached = unserialize($headersCached);
             isset($headersCached['Eva-Dsp-Cache']) && ($headersCached['Eva-Dsp-Cache'] = date('Y-m-d H:i:s', $headersCached['Eva-Dsp-Cache']));
             foreach ($headersCached as $_k => $_herder) {
                 if (is_int($_k)) {
                     $response->setRawHeader($_herder);
                 } else {
                     $response->setHeader($_k, $_herder);
                 }
             }
         }
         $response->setContent($bodyCached);
         $response->send();
         exit;
     }
 }
 /**
  * Start execute route benchmark
  *
  * @param Event $event
  * @param DispatcherInterface $dispatcher
  */
 public function beforeExecuteRoute(Event $event, DispatcherInterface $dispatcher)
 {
     $name = get_class($event->getSource()) . '::executeRoute';
     $metadata = ['executed' => sprintf('%s::%sAction', get_class($dispatcher->getActiveController()), $dispatcher->getActionName()), 'controller' => $dispatcher->getControllerName(), 'action' => $dispatcher->getActionName(), 'params' => $dispatcher->getParams()];
     $this->benchmarkRoute = $this->getProfiler()->start($name, $metadata, 'Dispatcher');
 }