private function _testEnabled($method = 'GET') { $request = new Request(); $request->env('REQUEST_METHOD', $method); $request->here = '/pages/home'; $response = new Response(); $View = new View($request, $response); $View->loadHelper('ViewMemcached.ViewMemcached', ['cacheConfig' => TEST_CACHE_CONFIG]); $View->viewPath = 'Pages'; $View->set('test', 'value'); $View->render('home', 'default'); return $View->ViewMemcached->enabled(); }
/** * @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()); }
/** * 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); }
/** * 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]); }
/** * Startup event to trace the user on the website. * * @param Event $event The event that was fired. * * @return void */ public function startup(Event $event) { if (empty($this->_session->id())) { $this->_session->start(); return; } $sessions = TableRegistry::get('Sessions'); $prefix = isset($this->_request['prefix']) ? $this->_request['prefix'] . '/' : ''; $controller = $prefix . $this->_request['controller']; $action = $this->_request['action']; $params = serialize($this->_request->pass); $expires = time() + ini_get('session.gc_maxlifetime'); //@codingStandardsIgnoreStart $user_id = $this->_session->read('Auth.User.id'); $user_agent = $this->_request->env('HTTP_USER_AGENT'); $user_ip = $this->_request->clientIp(); $full_url = $this->_request->url; //@codingStandardIgnoreEnd $modified = new Time(); $record = compact('controller', 'action', 'params', 'expires', 'user_id', 'user_agent', 'user_ip', 'full_url', 'modified'); $record[$sessions->primaryKey()] = $this->_session->id(); $sessions->save(new Entity($record)); }
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'); }
/** * 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; }
/** * Sends an asset file to the client * * @param \Cake\Network\Request $request The request object to use. * @param \Cake\Network\Response $response The response object to use. * @param string $assetFile Path to the asset file in the file system * @param string $ext The extension of the file to determine its mime type * @return void */ protected function _deliverAsset(Request $request, Response $response, $assetFile, $ext) { $compressionEnabled = $response->compress(); if ($response->type($ext) === $ext) { $contentType = 'application/octet-stream'; $agent = $request->env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/octetstream'; } $response->type($contentType); } if (!$compressionEnabled) { $response->header('Content-Length', filesize($assetFile)); } // $response->cache(filemtime($assetFile), $this->_cacheTime); $response->sendHeaders(); readfile($assetFile); if ($compressionEnabled) { ob_end_flush(); } }
/** * Determines the content type of the data the client has sent (i.e. in a POST request) * * @param string|array $type Can be null (or no parameter), a string type name, or an array of types * @return mixed If a single type is supplied a boolean will be returned. If no type is provided * The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type * in the request content type will be returned. */ public function requestedWith($type = null) { if (!$this->request->is('post') && !$this->request->is('put')) { return null; } if (is_array($type)) { foreach ($type as $t) { if ($this->requestedWith($t)) { return $t; } } return false; } list($contentType) = explode(';', $this->request->env('CONTENT_TYPE')); if ($contentType === '') { list($contentType) = explode(';', $this->request->header('CONTENT_TYPE')); } if (!$type) { return $this->response->mapType($contentType); } if (is_string($type)) { return $type === $this->response->mapType($contentType); } }
/** * test scope failure. * * @expectedException \Cake\Network\Exception\UnauthorizedException * @expectedExceptionCode 401 * @return void */ public function testAuthenticateFailReChallenge() { $this->auth->config('scope.username', 'nate'); $request = new Request(['url' => 'posts/index', 'environment' => ['REQUEST_METHOD' => 'GET']]); $request->addParams(array('pass' => array())); $digest = <<<DIGEST Digest username="******", realm="localhost", nonce="123", uri="/dir/index.html", qop=auth, nc=1, cnonce="123", response="6629fae49393a05397450978507c4ef1", opaque="123abc" DIGEST; $request->env('PHP_AUTH_DIGEST', $digest); $this->auth->unauthenticated($request, $this->response); }
/** * Sends an asset file to the client * * @param \Cake\Network\Request $request The request object to use. * @param \Cake\Network\Response $response The response object to use. * @param string $assetFile Path to the asset file in the file system * @param string $ext The extension of the file to determine its mime type * @return void */ protected function _deliverCacheFile(Request $request, Response $response, $file, $ext) { $compressionEnabled = $response->compress(); if ($response->type($ext) === $ext) { $contentType = 'application/octet-stream'; $agent = $request->env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/octetstream'; } $response->type($contentType); } if (!$compressionEnabled) { $response->header('Content-Length', filesize($file)); } $content = file_get_contents($file); $cacheInfo = $this->extractCacheInfo($content); $modifiedTime = filemtime($file); $cacheTime = $cacheInfo['time']; if (!$cacheTime) { $cacheTime = $this->_cacheTime; } $response->cache($modifiedTime, $cacheTime); $response->type($cacheInfo['ext']); if (Configure::read('debug') || $this->config('debug')) { if ($cacheInfo['ext'] === 'html') { $content = '<!--created:' . $modifiedTime . '-->' . $content; } } $response->body($content); }
/** * Get a $_SERVER variable value. * * Get the value even if the $_SERVER index name is prefixed by some "REDIRECT_" (due to mod_rewrite) * * @param string $name */ protected function get_server_value(Request $request, $attribute_name) { $repeat = 0; $value = null; while (!isset($value) && $repeat < 5) { $value = $request->env($this->mod_rewrite_prefix . $attribute_name); if (isset($value)) { return $value; } $attribute_name = $this->mod_rewrite_prefix . $attribute_name; $repeat++; } return null; }
/** * Test ssl option when the current request is ssl. * * @return void */ public function testGenerateWithSslInSsl() { Router::connect('/:controller/:action/*'); $request = new Request(); $request->env('HTTP_HOST', 'localhost'); $request->env('HTTPS', 'on'); Router::pushRequest($request->addParams(['plugin' => null, 'controller' => 'images', 'action' => 'index'])->addPaths(['base' => '', 'here' => '/images/index', 'webroot' => '/'])); $result = Router::url(['_ssl' => false]); $this->assertEquals('http://localhost/images/index', $result); $result = Router::url(['_ssl' => true]); $this->assertEquals('https://localhost/images/index', $result); }
/** * test * * @return void */ public function testAuthenticateNoCookie() { $request = new Request('/'); $request->env('HTTP_USER_AGENT', 'user-agent'); $mockCookie = $this->getMockBuilder('Cake\\Controller\\Component\\CookieComponent')->disableOriginalConstructor()->setMethods(['check', 'read'])->getMock(); $mockCookie->expects($this->once())->method('read')->with('remember_me')->will($this->returnValue(null)); $registry = new ComponentRegistry($this->controller); $registry->set('Cookie', $mockCookie); $this->rememberMe = new RememberMeAuthenticate($registry); $result = $this->rememberMe->authenticate($request, new Response()); $this->assertFalse($result); }
/** * Test CORS * * @dataProvider corsData * @param Request $request * @param string $origin * @param string|array $domains * @param string|array $methods * @param string|array $headers * @param string|bool $expectedOrigin * @param string|bool $expectedMethods * @param string|bool $expectedHeaders * @return void */ public function testCors($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false) { $request->env('HTTP_ORIGIN', $origin); $response = $this->getMock('Cake\\Network\\Response', ['header']); $method = $response->expects(!$expectedOrigin ? $this->never() : $this->at(0))->method('header'); $expectedOrigin && $method->with('Access-Control-Allow-Origin', $expectedOrigin ? $expectedOrigin : $this->anything()); $i = 1; if ($expectedMethods) { $response->expects($this->at($i++))->method('header')->with('Access-Control-Allow-Methods', $expectedMethods ? $expectedMethods : $this->anything()); } if ($expectedHeaders) { $response->expects($this->at($i++))->method('header')->with('Access-Control-Allow-Headers', $expectedHeaders ? $expectedHeaders : $this->anything()); } $response->cors($request, $domains, $methods, $headers); unset($_SERVER['HTTP_ORIGIN']); }
/** * Get the request context for an error/exception trace. * * @param \Cake\Network\Request $request The request to read from. * @return string */ protected function _requestContext($request) { $message = "\nRequest URL: " . $request->here(); $referer = $request->env('HTTP_REFERER'); if ($referer) { $message .= "\nReferer URL: " . $referer; } $clientIp = $request->clientIp(); if ($clientIp && $clientIp !== '::1') { $message .= "\nClient IP: " . $clientIp; } return $message; }
/** * Handles unauthenticated access attempt. First the `unauthenticated()` method * of the last authenticator in the chain will be called. The authenticator can * handle sending response or redirection as appropriate and return `true` to * indicate no further action is necessary. If authenticator returns null this * method redirects user to login action. If it's an ajax request and config * `ajaxLogin` is specified that element is rendered else a 403 http status code * is returned. * * @param \Cake\Controller\Controller $controller A reference to the controller object. * @return void|\Cake\Network\Response Null if current action is login action * else response object returned by authenticate object or Controller::redirect(). */ protected function _unauthenticated(Controller $controller) { if (empty($this->_authenticateObjects)) { $this->constructAuthenticate(); } $auth = end($this->_authenticateObjects); $result = $auth->unauthenticated($this->request, $this->response); if ($result !== null) { return $result; } if ($this->_isLoginAction($controller)) { if (empty($controller->request->data) && !$this->session->check('Auth.redirect') && $this->request->env('HTTP_REFERER')) { $this->session->write('Auth.redirect', $controller->referer(null, true)); } return; } if (!$controller->request->is('ajax')) { $this->flash($this->_config['authError']); $this->session->write('Auth.redirect', $controller->request->here(false)); return $controller->redirect($this->_config['loginAction']); } if (!empty($this->_config['ajaxLogin'])) { $controller->viewPath = 'Element'; $response = $controller->render($this->_config['ajaxLogin'], $this->RequestHandler->ajaxLayout); $response->statusCode(403); return $response; } return $controller->redirect(null, 403); }
/** * 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')) { // index of the array returned by the function getallheaders() is case-insensitive. // @see http://php.net/manual/en/function.getallheaders.php#52029 $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; }
/** * TestAllowMethod * * @return void */ public function testAllowMethod() { $request = new Request(['environment' => ['url' => '/posts/edit/1', 'REQUEST_METHOD' => 'PUT']]); $this->assertTrue($request->allowMethod('put')); $request->env('REQUEST_METHOD', 'DELETE'); $this->assertTrue($request->allowMethod(['post', 'delete'])); }
/** * Generate the login headers * * @param \Cake\Network\Request $request Request object. * @return string Headers for logging in. */ public function loginHeaders(Request $request) { $realm = $this->config('realm') ?: $request->env('SERVER_NAME'); return sprintf('WWW-Authenticate: Basic realm="%s"', $realm); }
/** * Default to loginRedirect, if set, on authError. * * @return void * @triggers Controller.startup $Controller */ public function testDefaultToLoginRedirect() { $url = '/party/on'; $this->Auth->request = $request = new Request($url); $request->env('HTTP_REFERER', false); $request->addParams(Router::parse($url)); $request->addPaths(['base' => 'dirname', 'webroot' => '/dirname/']); Router::pushRequest($request); $this->Auth->config('authorize', ['Controller']); $this->Auth->setUser(['username' => 'mariano', 'password' => 'cake']); $this->Auth->config('loginRedirect', ['controller' => 'something', 'action' => 'else']); $response = new Response(); $Controller = $this->getMock('Cake\\Controller\\Controller', ['on', 'redirect'], [$request, $response]); $event = new Event('Controller.startup', $Controller); // Should not contain basedir when redirect is called. $expected = '/something/else'; $Controller->expects($this->once())->method('redirect')->with($this->equalTo($expected)); $this->Auth->startup($event); }
/** * Generate the login headers * * @param \Cake\Network\Request $request Request object. * @return string Headers for logging in. */ public function loginHeaders(Request $request) { $realm = $this->_config['realm'] ?: $request->env('SERVER_NAME'); $options = ['realm' => $realm, 'qop' => $this->_config['qop'], 'nonce' => $this->_config['nonce'], 'opaque' => $this->_config['opaque'] ?: md5($realm)]; $opts = []; foreach ($options as $k => $v) { $opts[] = sprintf('%s="%s"', $k, $v); } return 'WWW-Authenticate: Digest ' . implode(',', $opts); }
/** * Test CORS * * @dataProvider corsData * @param Request $request * @param string $origin * @param string|array $domains * @param string|array $methods * @param string|array $headers * @param string|bool $expectedOrigin * @param string|bool $expectedMethods * @param string|bool $expectedHeaders * @return void */ public function testCors($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false) { $request->env('HTTP_ORIGIN', $origin); $response = new Response(); $result = $response->cors($request, $domains, $methods, $headers); $this->assertInstanceOf('Cake\\Network\\CorsBuilder', $result); $headers = $response->header(); if ($expectedOrigin) { $this->assertArrayHasKey('Access-Control-Allow-Origin', $headers); $this->assertEquals($expectedOrigin, $headers['Access-Control-Allow-Origin']); } if ($expectedMethods) { $this->assertArrayHasKey('Access-Control-Allow-Methods', $headers); $this->assertEquals($expectedMethods, $headers['Access-Control-Allow-Methods']); } if ($expectedHeaders) { $this->assertArrayHasKey('Access-Control-Allow-Headers', $headers); $this->assertEquals($expectedHeaders, $headers['Access-Control-Allow-Headers']); } unset($_SERVER['HTTP_ORIGIN']); }
/** * Default to loginRedirect, if set, on authError. * * @return void */ public function testDefaultToLoginRedirect() { $url = '/party/on'; $this->Auth->request = $Request = new Request($url); $Request->env('HTTP_REFERER', false); $this->Auth->request->addParams(Router::parse($url)); $this->Auth->config('authorize', ['Controller']); $this->Auth->login(array('username' => 'mariano', 'password' => 'cake')); $this->Auth->config('loginRedirect', ['controller' => 'something', 'action' => 'else']); $response = new Response(); $Controller = $this->getMock('Cake\\Controller\\Controller', array('on', 'redirect'), array($Request, $response)); $event = new Event('Controller.startup', $Controller); $expected = Router::url($this->Auth->config('loginRedirect'), true); $Controller->expects($this->once())->method('redirect')->with($this->equalTo($expected)); $this->Auth->startup($event); }