示例#1
3
 public function findCursor(Query $query)
 {
     $current = $this->request->query('cursor');
     $limit = $this->request->query('limit') ?: 10;
     if ($current) {
         $query->where(['id >' => $current]);
     }
     $query->limit($limit);
     return $query;
 }
示例#2
0
 /**
  * Enriches all of the passed audit logs to add the request
  * info metadata.
  *
  * @param Event The AuditStash.beforeLog event
  * @param array $logs The audit log event objects
  * @return void
  */
 public function beforeLog(Event $event, array $logs)
 {
     $meta = ['ip' => $this->request->clientIp(), 'url' => $this->request->here(), 'user' => $this->user];
     foreach ($logs as $log) {
         $log->setMetaInfo($log->getMetaInfo() + $meta);
     }
 }
 public function beforeSave(Event $event, EntityInterface $entity)
 {
     if ($entity === null) {
         return true;
     }
     $isNew = $entity->isNew();
     $fields = $this->config('fields');
     $ip = self::$_request->clientIp();
     foreach ($fields as $field => $when) {
         $when = strtolower($when);
         if (!in_array($when, ['always', 'new'])) {
             throw new UnexpectedValueException(sprintf('"When" should be one of "always", "new". The passed value "%s" is invalid', $when));
         }
         switch ($when) {
             case 'always':
                 $entity->set($field, $ip);
                 continue;
                 break;
             case 'new':
                 if ($isNew) {
                     $entity->set($field, $ip);
                     continue;
                 }
                 break;
         }
     }
     return true;
 }
示例#4
0
 /**
  * Get data of the request
  *
  * @param Request $request
  * @return array
  */
 public function getData(Request $request)
 {
     $data = $request->data('attributes');
     if ($request->data('id')) {
         $data['id'] = $request->data('id');
     }
     return $data;
 }
示例#5
0
 /**
  * {@inheritDoc}
  */
 public function val($field, $options = [])
 {
     $options += ['default' => null, 'schemaDefault' => true];
     $val = $this->_request->data($field);
     if ($val !== null) {
         return $val;
     }
     return $options['default'];
 }
示例#6
0
 /**
  * Permission extract constructor.
  *
  * @param $user
  * @param Request $request
  */
 public function __construct($user, Request $request)
 {
     $this->_request = $request;
     $this->_user = (array) $user;
     $this->_requestPref = $request->param('prefix');
     $this->_controller = $request->param('Controller');
     $this->_setAclPlugins();
     $this->_setupAllowed();
 }
示例#7
0
 /**
  * Setup
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Router::connect('/:controller/:action');
     $request = new Request();
     $request->addParams(array('controller' => 'pages', 'action' => 'display'));
     $this->View = new View($request);
     $this->Toolbar = new ToolbarHelper($this->View);
 }
示例#8
0
 /**
  * test check() failing
  *
  * @return void
  */
 public function testAuthorizeCheckFailure()
 {
     $request = new Request('posts/index');
     $request->addParams(['controller' => 'posts', 'action' => 'index']);
     $user = ['Users' => ['username' => 'mark']];
     $this->_mockAcl();
     $this->Acl->expects($this->once())->method('check')->with($user, 'Posts', 'read')->will($this->returnValue(false));
     $this->assertFalse($this->auth->authorize($user['Users'], $request));
 }
示例#9
0
 /**
  * User authorize.
  *
  * @param array $user
  * @param Request $request
  * @return bool
  */
 public function authorize($user, Request $request)
 {
     $user = new Data($user);
     //  Allow all for admin role.
     if (Role::ADMIN_ID == $user->get('role_id', Role::PUBLIC_ID)) {
         return true;
     }
     return (bool) $request->param('allowed');
 }
示例#10
0
 /**
  * Checks the fields to ensure they are supplied.
  *
  * @param \Cake\Network\Request $request The request that contains login information.
  * @param array $fields The fields to be checked.
  * @return bool False if the fields have not been supplied. True if they exist.
  */
 protected function _checkFields(Request $request, array $fields)
 {
     foreach ([$fields['username'], $fields['password']] as $field) {
         $value = $request->data($field);
         if (empty($value) || !is_string($value)) {
             return false;
         }
     }
     return true;
 }
示例#11
0
 /**
  * test setting parameters in beforeDispatch method
  *
  * @return void
  * @triggers __CLASS__ $this, compact(request)
  */
 public function testBeforeDispatchSkipWhenControllerSet()
 {
     $filter = new RoutingFilter();
     $request = new Request("/testcontroller/testaction/params1/params2/params3");
     $request->addParams(['controller' => 'articles']);
     $event = new Event(__CLASS__, $this, compact('request'));
     $filter->beforeDispatch($event);
     $this->assertSame($request->params['controller'], 'articles');
     $this->assertEmpty($request->params['action']);
 }
 /**
  * test authenticate token as request header
  *
  * @return void
  */
 public function testAuthenticateTokenHeader()
 {
     $request = new Request('posts/index');
     $expected = ['id' => 1, 'user_name' => 'mariano', 'email' => '*****@*****.**', 'token' => '12345', 'created' => new Time('2007-03-17 01:16:23'), 'updated' => new Time('2007-03-17 01:18:31')];
     $request->env('HTTP_X_APITOKEN', '12345');
     $result = $this->auth->getUser($request, $this->response);
     $this->assertEquals($expected, $result);
     $request->env('HTTP_X_APITOKEN', '66666');
     $result = $this->auth->getUser($request, $this->response);
     $this->assertFalse($result);
 }
 /**
  * Hands authorization over to the AnnAuthorize class.
  * @param array $user
  *         An array containing information about the user to authorize.
  * @param Request $request
  *         Describes the request to authorize.
  */
 public function authorize($user, Request $request)
 {
     $controller = $this->_registry->getController();
     $action = $request->param('action');
     $pass = $request->param('pass');
     Log::debug(sprintf('Trying to authorize user %s for request %s/%s and parameters %s.', $user['username'], $controller->name, $action, json_encode($pass)));
     $annAuthorization = AnnAuthorization::getInstance();
     $authorized = $annAuthorization->authorizeRequest($user['id'], $controller, $action, $pass, $request);
     Log::debug(sprintf('Authorization %s', $authorized ? 'was successful.' : 'failed.'));
     return $authorized;
 }
 /**
  * setup create a request object to get out of router later.
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Router::reload();
     $request = new Request();
     $request->base = '';
     $request->env('HTTP_REFERER', '/referer');
     Router::setRequestInfo($request);
     Configure::write('debug', true);
     $this->_logger = $this->getMock('Psr\\Log\\LoggerInterface');
     Log::reset();
     Log::config('error_test', ['engine' => $this->_logger]);
 }
 /**
  * Get user's credentials (username and password) from either session or request data
  *
  * @param Request $request Request instance
  * @return array|bool
  */
 protected function _getCredentials(Request $request)
 {
     $credentials = [];
     foreach (['username', 'password'] as $field) {
         if (!($credentials[$field] = $request->data($this->_config['fields'][$field]))) {
             $credentials[$field] = $this->_decrypt($request->session()->read('TwoFactorAuth.credentials.' . $field));
         }
         if (empty($credentials[$field]) || !is_string($credentials[$field])) {
             return false;
         }
     }
     return $credentials;
 }
示例#16
0
文件: Theme.php 项目: UnionCMS/Core
 /**
  * Check and get current theme.
  *
  * @param Request $request
  * @return string|null
  */
 public static function get(Request $request)
 {
     $theme = Configure::read('Theme.site');
     if ($request->param('prefix') == 'admin') {
         $theme = Configure::read('Theme.admin');
     }
     $path = self::_find($theme);
     if ($path !== null) {
         self::loadList([$theme]);
         return $theme;
     }
     return null;
 }
 /**
  * Authenticate callback
  * Reads the stored cookie and auto login the user
  *
  * @param Request $request Cake request object.
  * @param Response $response Cake response object.
  * @return mixed
  */
 public function authenticate(Request $request, Response $response)
 {
     $cookieName = Configure::read('Users.RememberMe.Cookie.name');
     if (!$this->_registry->Cookie->check($cookieName)) {
         return false;
     }
     $cookie = $this->_registry->Cookie->read($cookieName);
     $this->config('fields.username', 'id');
     $user = $this->_findUser($cookie['id']);
     if ($user && !empty($cookie['user_agent']) && $request->header('User-Agent') === $cookie['user_agent']) {
         return $user;
     }
     return false;
 }
示例#18
0
文件: AclHelper.php 项目: Xety/Xeta
 /**
  * Check if the user can access to the given URL.
  *
  * @param array $params The params to check.
  *
  * @return bool
  */
 public function check(array $params = [])
 {
     if (!$this->request->session()->read('Auth.User')) {
         return false;
     }
     $params += ['_base' => false];
     $url = Router::url($params);
     $params = Router::parse($url);
     $user = [$this->Authorize->config('userModel') => $this->request->session()->read('Auth.User')];
     $request = new Request();
     $request->addParams($params);
     $action = $this->Authorize->action($request);
     return $this->Acl->check($user, $action);
 }
 /**
  * {@inheritDoc}
  */
 public function validate(Request $request)
 {
     if ($request->is('post')) {
         // The (User's) Remote Address
         $whatRemoteIP = env('REMOTE_ADDR') ? '&remoteip=' . env('REMOTE_ADDR') : '';
         // The reCAPTCHA data is extracted from Request
         $gRecaptchaResponse = $request->data('g-recaptcha-response');
         // Verify reCAPTCHA data
         $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $this->config('secretKey') . '&response=' . $gRecaptchaResponse . $whatRemoteIP);
         $response = json_decode($response, true);
         // We return the Google server's response 'success' value
         return (bool) $response['success'];
     }
     return false;
 }
 /**
  * testBeforeDispatch
  *
  * @return void
  */
 public function testBeforeDispatch()
 {
     Configure::write('App.namespace', 'TestApp');
     $filter = new ControllerFactoryFilter();
     $request = new Request();
     $response = new Response();
     $request->addParams(['prefix' => 'admin', 'controller' => 'Posts', 'action' => 'index']);
     $event = new Event(__CLASS__, $this, compact('request', 'response'));
     $filter->beforeDispatch($event);
     $this->assertEquals('TestApp\\Controller\\Admin\\PostsController', get_class($event->data['controller']));
     $request->addParams(['prefix' => 'admin/sub', 'controller' => 'Posts', 'action' => 'index']);
     $event = new Event(__CLASS__, $this, compact('request', 'response'));
     $filter->beforeDispatch($event);
     $this->assertEquals('TestApp\\Controller\\Admin\\Sub\\PostsController', get_class($event->data['controller']));
 }
 /**
  * Determines which content-types the client prefers. If no parameters are given,
  * the single content-type that the client most likely prefers is returned. If $type is
  * an array, the first item in the array that the client accepts is returned.
  * Preference is determined primarily by the file extension parsed by the Router
  * if provided, and secondarily by the list of content-types provided in
  * HTTP_ACCEPT.
  *
  * @param string|array $type An optional array of 'friendly' content-type names, i.e.
  *   'html', 'xml', 'js', etc.
  * @return mixed If $type is null or not provided, the first content-type in the
  *    list, based on preference, is returned. If a single type is provided
  *    a boolean will be returned if that type is preferred.
  *    If an array of types are provided then the first preferred type is returned.
  *    If no type is provided the first preferred type is returned.
  * @see RequestHandlerComponent::setContent()
  */
 public function prefers($type = null)
 {
     $acceptRaw = $this->request->parseAccept();
     if (empty($acceptRaw)) {
         return $this->ext;
     }
     $accepts = $this->response->mapType(array_shift($acceptRaw));
     if (!$type) {
         if (empty($this->ext) && !empty($accepts)) {
             return $accepts[0];
         }
         return $this->ext;
     }
     $types = (array) $type;
     if (count($types) === 1) {
         if (!empty($this->ext)) {
             return in_array($this->ext, $types);
         }
         return in_array($types[0], $accepts);
     }
     $intersect = array_values(array_intersect($accepts, $types));
     if (empty($intersect)) {
         return false;
     }
     return $intersect[0];
 }
 public function testParamsRedirect()
 {
     $request = new Request(['url' => 'controller_posts/index', 'action' => 'index', '_method' => 'POST']);
     $request->env('REQUEST_METHOD', 'POST');
     $request->action = 'index';
     $request->data['Filter'] = ['Posts' => ['title' => 'foo', 'body' => 'bar', 'multi' => [1, 2]]];
     $controller = new Controller($request);
     $controller->listFilters = ['index' => ['fields' => ['Posts.title' => ['searchType' => 'wildcard', 'options' => []], 'Posts.body' => ['searchType' => 'wildcard'], 'Posts.multi' => ['searchType' => 'multipleselect', 'options' => [1 => 'one', 2 => 'two']]]]];
     $ListFilter = new ListFilterComponent($controller->components(), []);
     $event = new Event('Controller.startup', $controller);
     $ListFilter->startup($event);
     $this->assertEquals(array_keys($controller->listFilters['index']['fields']), array_keys($ListFilter->getFilters()['fields']));
     // Check if the request is being redirected properly
     $redirectUrl = parse_url($controller->response->header()['Location']);
     $this->assertEquals(urldecode($redirectUrl['query']), 'Filter-Posts-title=foo&Filter-Posts-body=bar&Filter-Posts-multi[0]=1&Filter-Posts-multi[1]=2');
 }
示例#23
0
 protected function filterMustBeCleared($options)
 {
     $current_path = $this->getComparisonPath($this->request->params);
     $referer_path = $this->getComparisonPath(Router::parse($this->request->referer(true)));
     if ($current_path == $referer_path) {
         return false;
     } else {
         $plugin = isset($this->request->params['plugin']) ? $this->request->params['plugin'] : null;
         $prefix = isset($this->request->params['prefix']) ? $this->request->params['prefix'] : null;
         $controller = $this->request->params['controller'];
         $action = $this->request->params['action'];
         $pass = isset($this->request->params['pass']) ? $this->request->params['pass'] : [];
         $query = isset($this->request->params['?']) ? $this->request->params['?'] : [];
         $referer = Router::parse($this->request->referer(true));
         $referer_plugin = isset($referer['plugin']) ? $referer['plugin'] : null;
         $referer_prefix = isset($referer['prefix']) ? $referer['prefix'] : null;
         $referer_controller = $referer['controller'];
         $referer_action = $referer['action'];
         $referer_pass = isset($referer['pass']) ? $referer['pass'] : [];
         $referer_query = isset($referer['?']) ? $referer['?'] : [];
         if ($plugin == $referer_plugin && $prefix == $referer_prefix && $controller == $referer_controller) {
             if (isset($options['keep_filter_actions']) && is_array($options['keep_filter_actions'])) {
                 if (in_array($referer_action, $options['keep_filter_actions'])) {
                     return false;
                 }
             }
         }
     }
     return true;
 }
示例#24
0
 /**
  * Get the value for a given path.
  *
  * Traverses the entity data and finds the value for $path.
  *
  * @param string $field The dot separated path to the value.
  * @param array $options Options:
  *   - `default`: Default value to return if no value found in request
  *     data or entity.
  *   - `schemaDefault`: Boolen indicating whether default value from table
  *     schema should be used if it's not explicitly provided.
  * @return mixed The value of the field or null on a miss.
  */
 public function val($field, $options = [])
 {
     $options += ['default' => null, 'schemaDefault' => true];
     $val = $this->_request->data($field);
     if ($val !== null) {
         return $val;
     }
     if (empty($this->_context['entity'])) {
         return $options['default'];
     }
     $parts = explode('.', $field);
     $entity = $this->entity($parts);
     if (end($parts) === '_ids' && !empty($entity)) {
         return $this->_extractMultiple($entity, $parts);
     }
     if ($entity instanceof EntityInterface) {
         $part = array_pop($parts);
         $val = $entity->get($part);
         if ($val !== null) {
             return $val;
         }
         if ($options['default'] !== null || !$options['schemaDefault'] || !$entity->isNew()) {
             return $options['default'];
         }
         return $this->_schemaDefault($part, $entity);
     }
     if (is_array($entity)) {
         $key = array_pop($parts);
         return isset($entity[$key]) ? $entity[$key] : null;
     }
     return null;
 }
 /**
  * Retrieves or creates a user based on header data
  *
  * @param \Cake\Network\Request $request Request object.
  * @return mixed Either false or an array of user information
  */
 protected function _getUser(Request $request)
 {
     $config = $this->_config;
     $username = $request->header($config['headers']['username']);
     $result = $this->_query($username)->first();
     if (!empty($result)) {
         return $result;
     }
     $data = [$config['fields']['username'] => $username, $config['fields']['password'] => '', $config['fields']['name'] => $request->header($config['headers']['name']), $config['fields']['email'] => $request->header($config['headers']['email'])];
     $table = TableRegistry::get($config['userModel']);
     $result = $table->newEntity($data);
     if (!$table->save($result)) {
         return false;
     }
     return $result;
 }
 /**
  * Handle unauthenticated access attempt. In implementation valid return values
  * can be:
  *
  * - Null - No action taken, AuthComponent should return appropriate response.
  * - Cake\Network\Response - A response object, which will cause AuthComponent to
  *   simply return that response.
  *
  * @param \Cake\Network\Request $request A request object.
  * @param \Cake\Network\Response $response A response object.
  * @return \Cake\Network\Response|bool
  */
 public function unauthenticated(Request $request, Response $response)
 {
     $response->type('json');
     $deviceId = $request->header($this->config('headerDeviceId'));
     $token = $request->header($this->config('headerToken'));
     if ($deviceId == null || $token == null) {
         return $this->unauthorizedResponse($response);
     }
     $generatedToken = $this->generateToken($deviceId);
     //Log::debug("CREATED TOKEN: ".$generatedToken);
     //Log::debug("SENT TOKEN: ".$token);
     if ($token != $generatedToken) {
         return $this->unauthorizedResponse($response);
     }
     return true;
 }
 /**
  * @return void
  */
 public function testAutoPostRedirectRefererNotWhitelisted()
 {
     $this->request->env('HTTP_REFERER', 'http://localhost/my_controller/wrong');
     $is = $this->Controller->Common->autoPostRedirect(['controller' => 'MyController', 'action' => 'foo'], true);
     $is = $this->Controller->response->header();
     $this->assertSame('http://localhost/my_controller/foo', $is['Location']);
     $this->assertSame(302, $this->Controller->response->statusCode());
 }
 /**
  * Authenticate callback
  *
  * @param Request $request Cake request object.
  * @param Response $response Cake response object.
  * @return bool|mixed
  */
 public function authenticate(Request $request, Response $response)
 {
     $data = $request->session()->read(Configure::read('Users.Key.Session.social'));
     if (empty($data)) {
         return false;
     }
     $socialMail = Hash::get((array) $data->info, Configure::read('Users.Key.Data.email'));
     if (!empty($socialMail)) {
         $data->email = $socialMail;
         $data->validated = true;
     } else {
         $data->email = $request->data(Configure::read('Users.Key.Data.email'));
         $data->validated = false;
     }
     $user = $this->_findOrCreateUser($data);
     return $user;
 }
示例#29
0
 /**
  * Get node ref path by request.
  *
  * @return string
  */
 protected function _getNodeRef()
 {
     $ref = ['type' => 'controllers', 'plugin' => null, 'prefix' => Inflector::camelize($this->_request->param('prefix')), 'controller' => $this->_request->param('controller')];
     if ($this->_request->param('plugin') !== false) {
         $ref['plugin'] = FS::clean($this->_request->param('plugin'), '\\');
         return implode('/', $ref);
     }
     return FS::clean(implode('/', $ref), '/');
 }
示例#30
0
 /**
  * Get token from header or query string.
  *
  * @param \Cake\Network\Request $request Request object.
  * @return string|bool Token string if found else false.
  */
 protected function _getToken($request)
 {
     $token = $request->env('HTTP_AUTHORIZATION');
     // @codeCoverageIgnoreStart
     if (!$token && function_exists('getallheaders')) {
         $headers = array_change_key_case(getallheaders());
         if (isset($headers['authorization']) && substr($headers['authorization'], 0, 7) === 'Bearer ') {
             $token = $headers['authorization'];
         }
     }
     // @codeCoverageIgnoreEnd
     if ($token) {
         return substr($token, 7);
     }
     if (!empty($this->_config['parameter']) && isset($request->query[$this->_config['parameter']])) {
         $token = $request->query($this->_config['parameter']);
     }
     return $token ? $token : false;
 }