示例#1
0
 protected function setCommonVariable()
 {
     // Achieve that segment
     $this->accessUrl = config('cmsharenjoy.access_url');
     // Get the action name
     $routeArray = Str::parseCallback(Route::currentRouteAction(), null);
     if (last($routeArray) != null) {
         // Remove 'controller' from the controller name.
         $controller = str_replace('Controller', '', class_basename(head($routeArray)));
         // Take out the method from the action.
         $action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', last($routeArray));
         // post, report
         $this->onController = strtolower($controller);
         session()->put('onController', $this->onController);
         view()->share('onController', $this->onController);
         // get-create, post-create
         $this->onMethod = Str::slug(Request::method() . '-' . $action);
         session()->put('onMethod', $this->onMethod);
         view()->share('onMethod', $this->onMethod);
         // create, update
         $this->onAction = strtolower($action);
         session()->put('onAction', $this->onAction);
         view()->share('onAction', $this->onAction);
     }
     // Brand name from setting
     $this->brandName = Setting::get('brand_name');
     // Share some variables to views
     view()->share('brandName', $this->brandName);
     view()->share('langLocales', config('cmsharenjoy.locales'));
     view()->share('activeLanguage', session('sharenjoy.backEndLanguage'));
     // Set the theme
     // $this->theme = Theme::uses('front');
     // Message
     view()->share('messages', Message::getMessageBag());
 }
示例#2
0
 protected function getController()
 {
     $controller = \Illuminate\Support\Str::parseCallback(\Route::currentRouteAction(), null)[0];
     if (!preg_match('/^App\\\\Http\\\\Controllers\\\\([a-zA-Z\\\\]+)Controller$/', $controller, $controller_matches)) {
         throw new \Exception('Could not parse controller.');
     }
     return strtolower(str_replace('\\', '/', Str::camelCaseToHyphen($controller_matches[1])));
 }
示例#3
0
 /**
  * Get the current controller action name.
  *
  * @param  bool  $removeHttpMethod
  * @return string|null
  */
 public function action($removeHttpMethod = true)
 {
     if ($action = $this->router->currentRouteAction()) {
         $action = last(Str::parseCallback($action, null));
         if ($removeHttpMethod) {
             $action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', $action);
         }
         return Str::snake($action, '-');
     }
     return null;
 }
 /**
  * Resolves a string or callable to a valid callable.
  * @param string|callable $transformer
  * @param $defaultMethodName
  * @return callable
  */
 private function resolveCallable($transformer, $defaultMethodName)
 {
     if (is_string($transformer)) {
         return function () use($transformer, $defaultMethodName) {
             list($class, $method) = Str::parseCallback($transformer, $defaultMethodName);
             return call_user_func_array([app($class), $method], func_get_args());
         };
     } elseif (is_callable($transformer)) {
         return $transformer;
     }
     return function () {
     };
 }
示例#5
0
 /**
  * Update the route and request instances
  *
  * @param Route   $route
  * @param Request $request
  */
 public function updateInstances($route, $request)
 {
     $this->request = $request;
     if ($request) {
         $this->uri = urldecode($request->path());
     }
     $this->route = $route;
     if ($route) {
         $this->action = $route->getActionName();
         $actionSegments = Str::parseCallback($this->action, null);
         $this->controller = head($actionSegments);
         $this->method = last($actionSegments);
     }
 }
示例#6
0
 public function all()
 {
     $routes = [];
     foreach ($this->route->getRoutes() as $route) {
         list($controller, $action) = Str::parseCallback($route->getActionName(), [null, null]);
         if ($controller and $action and $controller !== 'Closure') {
             if (!array_key_exists($controller, $routes)) {
                 $routes[$controller] = [];
             }
             $routes[$controller][] = $action;
         }
     }
     return $this->clean($routes);
 }
 public function testBoot()
 {
     $translator = Mockery::mock('Symfony\\Component\\Translation\\TranslatorInterface');
     $translator->shouldReceive('get');
     $presence = Mockery::mock('Illuminate\\Validation\\PresenceVerifierInterface');
     $factory = new Factory($translator);
     $factory->setPresenceVerifier($presence);
     $container = Mockery::mock('Illuminate\\Container\\Container');
     $container->shouldReceive('bind');
     $container->shouldReceive('offsetGet')->with('translator')->andReturn($translator);
     $container->shouldReceive('offsetGet')->with('validator')->andReturn($factory);
     $sp = Mockery::mock('Cviebrock\\ImageValidator\\ImageValidatorServiceProvider[package]', array($container));
     $sp->shouldReceive('package');
     $sp->boot();
     $validator = $factory->make(array(), array());
     foreach ($validator->getExtensions() as $rule => $class_and_method) {
         $this->assertTrue(in_array($rule, $sp->getRules()));
         $this->assertEquals('Cviebrock\\ImageValidator\\ImageValidator@' . 'validate' . studly_case($rule), $class_and_method);
         list($class, $method) = Str::parseCallback($class_and_method, null);
         $this->assertTrue(method_exists($class, $method));
     }
 }
示例#8
0
 /**
  * Get callback from given shortcode name.
  *
  * @param string $name
  *
  * @return mixed
  */
 protected function getCallback($name)
 {
     $callback = $this->shortcodes[$name];
     if (is_string($callback)) {
         if (Str::contains($callback, '@')) {
             $parsedCallback = Str::parseCallback($callback, 'register');
             $instance = $this->container->make($parsedCallback[0]);
             return [$instance, $parsedCallback[1]];
         } elseif (class_exists($callback)) {
             $instance = $this->container->make($callback);
             return [$instance, 'register'];
         } else {
             return $callback;
         }
     }
     return $callback;
 }
 public function __construct()
 {
     $this->beforeFilter(function () {
         // Let's instantiate the response class first
         $this->manager = new Manager();
         $this->manager->parseIncludes(Input::get(Config::get('apiguard.includeKeyword', 'include'), 'include'));
         $this->response = new Response($this->manager);
         // apiguard might not be the only before filter on the controller
         // loop through any before filters and pull out $apiMethods in the controller
         $beforeFilters = $this->getBeforeFilters();
         foreach ($beforeFilters as $filter) {
             if (!empty($filter['options']['apiMethods'])) {
                 $apiMethods = $filter['options']['apiMethods'];
             }
         }
         // This is the actual request object used
         $request = Route::getCurrentRequest();
         // Let's get the method
         Str::parseCallback(Route::currentRouteAction(), null);
         $routeArray = Str::parseCallback(Route::currentRouteAction(), null);
         if (last($routeArray) == null) {
             // There is no method?
             return $this->response->errorMethodNotAllowed();
         }
         $method = last($routeArray);
         // We should check if key authentication is enabled for this method
         $keyAuthentication = true;
         if (isset($apiMethods[$method]['keyAuthentication']) && $apiMethods[$method]['keyAuthentication'] === false) {
             $keyAuthentication = false;
         }
         if ($keyAuthentication === true) {
             $key = $request->header(Config::get('apiguard.keyName', 'X-Authorization'));
             if (empty($key)) {
                 // Try getting the key from elsewhere
                 $key = Input::get(Config::get('apiguard.keyName', 'X-Authorization'));
             }
             if (empty($key)) {
                 // It's still empty!
                 return $this->response->errorUnauthorized();
             }
             $apiKeyModel = App::make(Config::get('apiguard.model', 'Chrisbjr\\ApiGuard\\Models\\ApiKey'));
             $apiRepository = Config::get('apiguard.repository', 'ApiKeyRepository');
             if (!$apiKeyModel instanceof $apiRepository) {
                 Log::error('[Chrisbjr/ApiGuard] You ApiKey model should be an instance of ApiKeyRepository.');
                 $exception = new Exception("You ApiKey model should be an instance of ApiKeyRepository.");
                 throw $exception;
             }
             $this->apiKey = $apiKeyModel->getByKey($key);
             if (empty($this->apiKey)) {
                 return $this->response->errorUnauthorized();
             }
             // API key exists
             // Check level of API
             if (!empty($apiMethods[$method]['level'])) {
                 if ($this->apiKey->level < $apiMethods[$method]['level']) {
                     return $this->response->errorForbidden();
                 }
             }
         }
         $apiLog = App::make(Config::get('apiguard.apiLogModel', 'Chrisbjr\\ApiGuard\\Models\\ApiLog'));
         // Then check the limits of this method
         if (!empty($apiMethods[$method]['limits'])) {
             if (Config::get('apiguard.logging', true) === false) {
                 Log::warning("[Chrisbjr/ApiGuard] You specified a limit in the {$method} method but API logging needs to be enabled in the configuration for this to work.");
             }
             $limits = $apiMethods[$method]['limits'];
             // We get key level limits first
             if ($this->apiKey != null && !empty($limits['key'])) {
                 $keyLimit = !empty($limits['key']['limit']) ? $limits['key']['limit'] : 0;
                 if ($keyLimit == 0 || is_integer($keyLimit) == false) {
                     Log::warning("[Chrisbjr/ApiGuard] You defined a key limit to the " . Route::currentRouteAction() . " route but you did not set a valid number for the limit variable.");
                 } else {
                     if (!$this->apiKey->ignore_limits) {
                         // This means the apikey is not ignoring the limits
                         $keyIncrement = !empty($limits['key']['increment']) ? $limits['key']['increment'] : Config::get('apiguard.keyLimitIncrement', '1 hour');
                         $keyIncrementTime = strtotime('-' . $keyIncrement);
                         if ($keyIncrementTime == false) {
                             Log::warning("[Chrisbjr/ApiGuard] You have specified an invalid key increment time. This value can be any value accepted by PHP's strtotime() method");
                         } else {
                             // Count the number of requests for this method using this api key
                             $apiLogCount = $apiLog->countApiKeyRequests($this->apiKey->id, Route::currentRouteAction(), $request->getMethod(), $keyIncrementTime);
                             if ($apiLogCount >= $keyLimit) {
                                 Log::warning("[Chrisbjr/ApiGuard] The API key ID#{$this->apiKey->id} has reached the limit of {$keyLimit} in the following route: " . Route::currentRouteAction());
                                 return $this->response->setStatusCode(429)->withError('You have reached the limit for using this API.', 'GEN-TOO-MANY-REQUESTS');
                             }
                         }
                     }
                 }
             }
             // Then the overall method limits
             if (!empty($limits['method'])) {
                 $methodLimit = !empty($limits['method']['limit']) ? $limits['method']['limit'] : 0;
                 if ($methodLimit == 0 || is_integer($methodLimit) == false) {
                     Log::warning("[Chrisbjr/ApiGuard] You defined a method limit to the " . Route::currentRouteAction() . " route but you did not set a valid number for the limit variable.");
                 } else {
                     if ($this->apiKey != null && $this->apiKey->ignore_limits == true) {
                         // then we skip this
                     } else {
                         $methodIncrement = !empty($limits['method']['increment']) ? $limits['method']['increment'] : Config::get('apiguard.keyLimitIncrement', '1 hour');
                         $methodIncrementTime = strtotime('-' . $methodIncrement);
                         if ($methodIncrementTime == false) {
                             Log::warning("[Chrisbjr/ApiGuard] You have specified an invalid method increment time. This value can be any value accepted by PHP's strtotime() method");
                         } else {
                             // Count the number of requests for this method
                             $apiLogCount = $apiLog->countMethodRequests(Route::currentRouteAction(), $request->getMethod(), $methodIncrementTime);
                             if ($apiLogCount >= $methodLimit) {
                                 Log::warning("[Chrisbjr/ApiGuard] The API has reached the method limit of {$methodLimit} in the following route: " . Route::currentRouteAction());
                                 return $this->response->setStatusCode(429)->withError('The limit for using this API method has been reached', 'GEN-TOO-MANY-REQUESTS');
                             }
                         }
                     }
                 }
             }
         }
         // End of cheking limits
         if (Config::get('apiguard.logging', true)) {
             // Default to log requests from this action
             $logged = true;
             if (isset($apiMethods[$method]['logged']) && $apiMethods[$method]['logged'] === false) {
                 $logged = false;
             }
             if ($logged) {
                 // Log this API request
                 $this->apiLog = App::make(Config::get('apiguard.apiLogModel', 'Chrisbjr\\ApiGuard\\Models\\ApiLog'));
                 if (isset($this->apiKey)) {
                     $this->apiLog->api_key_id = $this->apiKey->id;
                 }
                 $this->apiLog->route = Route::currentRouteAction();
                 $this->apiLog->method = $request->getMethod();
                 $this->apiLog->params = http_build_query(Input::all());
                 $this->apiLog->ip_address = $request->getClientIp();
                 $this->apiLog->save();
             }
         }
         $this->initialize();
     }, ['apiMethods' => $this->apiMethods]);
 }
示例#10
0
 /**
  * Get the current method name with the prefix 'get', 'post', 'put', 'delete', 'show' trimmed
  *
  * @return string|null
  */
 public function getMethod()
 {
     $action = $this->_router->currentRouteAction();
     if ($action) {
         $extractedController = last(Str::parseCallback($action, null));
         // Trim the "show", "post", "put", "delete", "get" if this is the
         // prefix of the method name
         return $extractedController ? preg_replace('/^(show|get|put|delete|post)(.+)$/', '${2}', $extractedController) : null;
     }
     return null;
 }
示例#11
0
 public function __construct()
 {
     $this->beforeFilter(function () {
         // Let's instantiate the response class first
         $this->manager = new Manager();
         $this->manager->parseIncludes(Input::get(Config::get('api-guard::includeKeyword', 'include'), array()));
         $this->response = new Response($this->manager);
         // api-guard might not be the only before filter on the controller
         // loop through any before filters and pull out $apiMethods in the controller
         $beforeFilters = $this->getBeforeFilters();
         foreach ($beforeFilters as $filter) {
             if (!empty($filter['options']['apiMethods'])) {
                 $apiMethods = $filter['options']['apiMethods'];
             }
         }
         // This is the actual request object used
         $request = Route::getCurrentRequest();
         // Let's get the method
         Str::parseCallback(Route::currentRouteAction(), null);
         $routeArray = Str::parseCallback(Route::currentRouteAction(), null);
         if (last($routeArray) == null) {
             // There is no method?
             return $this->response->errorMethodNotAllowed();
         }
         $method = last($routeArray);
         // We should check if key authentication is enabled for this method
         $keyAuthentication = true;
         if (isset($apiMethods[$method]['keyAuthentication']) && $apiMethods[$method]['keyAuthentication'] === false) {
             $keyAuthentication = false;
         }
         if ($keyAuthentication === true) {
             $key = $request->header(Config::get('api-guard::keyName'));
             if (empty($key)) {
                 // Try getting the key from elsewhere
                 $key = Input::get(Config::get('api-guard::keyName'));
             }
             if (empty($key)) {
                 // It's still empty!
                 return $this->response->errorUnauthorized();
             }
             $this->apiKey = ApiKey::where('key', '=', $key)->first();
             if (!isset($this->apiKey->id)) {
                 // ApiKey not found
                 return $this->response->errorUnauthorized();
             }
             // API key exists
             // Check level of API
             if (!empty($apiMethods[$method]['level'])) {
                 if ($this->apiKey->level < $apiMethods[$method]['level']) {
                     return $this->response->errorForbidden();
                 }
             }
         }
         // Then check the limits of this method
         if (!empty($apiMethods[$method]['limits'])) {
             if (Config::get('api-guard::logging') === false) {
                 Log::warning("[Awalko/ApiGuard] You specified a limit in the {$method} method but API logging needs to be enabled in the configuration for this to work.");
             }
             $limits = $apiMethods[$method]['limits'];
             // We get key level limits first
             if ($this->apiKey != null && !empty($limits['key'])) {
                 Log::info("key limits found");
                 $keyLimit = !empty($limits['key']['limit']) ? $limits['key']['limit'] : 0;
                 if ($keyLimit == 0 || is_integer($keyLimit) == false) {
                     Log::warning("[Awalko/ApiGuard] You defined a key limit to the " . Route::currentRouteAction() . " route but you did not set a valid number for the limit variable.");
                 } else {
                     if (!$this->apiKey->ignore_limits) {
                         // This means the apikey is not ignoring the limits
                         $keyIncrement = !empty($limits['key']['increment']) ? $limits['key']['increment'] : Config::get('api-guard::keyLimitIncrement');
                         $keyIncrementTime = strtotime('-' . $keyIncrement);
                         if ($keyIncrementTime == false) {
                             Log::warning("[Awalko/ApiGuard] You have specified an invalid key increment time. This value can be any value accepted by PHP's strtotime() method");
                         } else {
                             // Count the number of requests for this method using this api key
                             $apiLogCount = ApiLog::where('api_key_id', '=', $this->apiKey->id)->where('route', '=', Route::currentRouteAction())->where('method', '=', $request->getMethod())->where('created_at', '>=', date('Y-m-d H:i:s', $keyIncrementTime))->where('created_at', '<=', date('Y-m-d H:i:s'))->count();
                             if ($apiLogCount >= $keyLimit) {
                                 Log::warning("[Awalko/ApiGuard] The API key ID#{$this->apiKey->id} has reached the limit of {$keyLimit} in the following route: " . Route::currentRouteAction());
                                 return $this->response->errorUnwillingToProcess('You have reached the limit for using this API.');
                             }
                         }
                     }
                 }
             }
             // Then the overall method limits
             if (!empty($limits['method'])) {
                 $methodLimit = !empty($limits['method']['limit']) ? $limits['method']['limit'] : 0;
                 if ($methodLimit == 0 || is_integer($methodLimit) == false) {
                     Log::warning("[Awalko/ApiGuard] You defined a method limit to the " . Route::currentRouteAction() . " route but you did not set a valid number for the limit variable.");
                 } else {
                     if ($this->apiKey != null && $this->apiKey->ignore_limits == true) {
                         // then we skip this
                     } else {
                         $methodIncrement = !empty($limits['method']['increment']) ? $limits['method']['increment'] : Config::get('api-guard::keyLimitIncrement');
                         $methodIncrementTime = strtotime('-' . $methodIncrement);
                         if ($methodIncrementTime == false) {
                             Log::warning("[Awalko/ApiGuard] You have specified an invalid method increment time. This value can be any value accepted by PHP's strtotime() method");
                         } else {
                             // Count the number of requests for this method
                             $apiLogCount = ApiLog::where('route', '=', Route::currentRouteAction())->where('method', '=', $request->getMethod())->where('created_at', '>=', date('Y-m-d H:i:s', $methodIncrementTime))->where('created_at', '<=', date('Y-m-d H:i:s'))->count();
                             if ($apiLogCount >= $methodLimit) {
                                 Log::warning("[Awalko/ApiGuard] The API has reached the method limit of {$methodLimit} in the following route: " . Route::currentRouteAction());
                                 return $this->response->errorUnwillingToProcess('The limit for using this API method has been reached');
                             }
                         }
                     }
                 }
             }
         }
         // End of cheking limits
         if (Config::get('api-guard::logging') && $keyAuthentication == true) {
             // Log this API request
             $apiLog = new ApiLog();
             $apiLog->api_key_id = $this->apiKey->id;
             $apiLog->route = Route::currentRouteAction();
             $apiLog->method = $request->getMethod();
             $apiLog->params = http_build_query(Input::all());
             $apiLog->ip_address = $request->getClientIp();
             $apiLog->save();
         }
     }, ['apiMethods' => $this->apiMethods]);
 }
示例#12
0
 private function getRouteMethod()
 {
     $routeArray = Str::parseCallback(Route::currentRouteAction(), null);
     return last($routeArray);
 }
示例#13
0
 /**
  * Get a result from a class callback.
  *
  * @param   callable  $callback
  * @param   array     $parameters
  * @return  mixed
  */
 protected function createClassCallback($callback, array $parameters)
 {
     list($className, $method) = Str::parseCallback($callback, 'run');
     $instance = $this->container->make($className);
     $callable = array($instance, $method);
     return $this->createCallableCallback($callable, $parameters);
 }
 /**
  * Get the callback for the current shortcode (class or callback)
  *
  * @param  string $name
  *
  * @return callable|array
  */
 public function getCallback($name)
 {
     // Get the callback from the laravel-shortcodes array
     $callback = $this->registered[$name];
     // if is a string
     if (is_string($callback)) {
         // Parse the callback
         list($class, $method) = Str::parseCallback($callback, 'register');
         // If the class exist
         if (class_exists($class)) {
             // return class and method
             return [app($class), $method];
         }
     }
     return $callback;
 }
示例#15
0
 /**
  * Get callback from given shortcode name.
  *
  * @param  string  $name
  * @return mixed
  */
 protected function getCallback($name)
 {
     $callback = $this->shortcodes[$name];
     if (is_string($callback)) {
         if (str_contains($name, '@')) {
             $_callback = Str::parseCallback($callback, 'register');
             return [new $_callback[0](), $_callback[1]];
         } elseif (class_exists($name)) {
             return [new $name(), 'register'];
         } else {
             return $callback;
         }
     }
     return $callback;
 }
示例#16
0
 /**
  * Invoke route dispatcher callback.
  *
  * @param mixed $callable
  * @param array $params
  *
  * @return array|mixed
  */
 protected function invokeCallback($callable, array $params)
 {
     if (is_string($callable)) {
         list($controller, $method) = Str::parseCallback($callable, 'index');
         $callable = [$this->make($controller), $method];
     }
     return call_user_func_array($callable, $params);
 }