/** * Get the current user. * * Will prefer the static user cache over sessions. The static user * cache is primarily used for stateless authentication. For stateful authentication, * cookies + sessions will be used. * * @param string $key field to retrieve. Leave null to get entire User record * @return array|null User record. or null if no user is logged in. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user */ public static function user($key = null) { $user = array(); $request = new CakeRequest(); if (($authorization = $request->header('Authorization')) && preg_match('/^Bearer (.*?)$/', $authorization, $matches)) { $signer = new Sha256(); $token = (new Parser())->parse((string) next($matches)); try { if ($token->verify($signer, Configure::read('Security.salt'))) { $data = new ValidationData(Configure::read('Security.timeout') > 0 ? null : $token->getClaim('iat')); $data->setIssuer(Router::url('/', true)); $data->setAudience($request->clientIp()); if ($token->validate($data)) { if ($user = json_decode($token->getClaim('data'), true)) { if (!empty($user['id'])) { if (!empty(static::$_user) && static::$_user['id'] == $user['id']) { $user = static::$_user; return empty($key) ? $user : Hash::get($user, $key); } else { $User = ClassRegistry::init('User'); $User->id = $user['id']; return Hash::get($User->read(), 'User' . (empty($key) ? '' : '.' . $key)); } } } } } } catch (Exception $ex) { } } return false; }
public function testIs() { $result = Reveal::is('App.online'); $expected = !in_array(gethostbyname('google.com'), array('google.com', false)); $this->assertEqual($result, $expected); $result = Reveal::is('DebugKit.loaded'); $expected = CakePlugin::loaded('DebugKit'); $this->assertEqual($result, $expected); $result = Reveal::is(array('OR' => array('DebugKit.enabled', 'DebugKit.automated'))); $expected = Configure::read('debug') || Configure::read('DebugKit.forceEnable') || Configure::read('DebugKit.autoRun'); $this->assertEqual($result, $expected); $_GET['debug'] = 'true'; $this->assertTrue(Reveal::is('DebugKit.requested')); $result = Reveal::is('DebugKit.loaded', array('OR' => array('DebugKit.enabled', array('AND' => array('DebugKit.automated', 'DebugKit.requested'))))); $expected = CakePlugin::loaded('DebugKit') || Configure::read('debug') || Configure::read('DebugKit.forceEnable') || Configure::read('DebugKit.autoRun') && isset($_GET['debug']) && 'true' == $_GET['debug']; $this->assertEqual($result, $expected); $this->assertEqual(Reveal::is('DebugKit.running'), $expected); $request = new CakeRequest(); Router::setRequestInfo($request->addParams(array('controller' => 'pages', 'action' => 'display', 'pass' => array('home')))); $result = Reveal::is('Page.front'); $this->assertTrue($result); Router::reload(); $request = new CakeRequest(); Router::setRequestInfo($request->addParams(array('prefix' => 'admin', 'admin' => true))); $result = Reveal::is('Page.prefixed'); $this->assertTrue($result); Router::reload(); $request = new CakeRequest(); Router::setRequestInfo($request->addParams(array('controller' => 'users', 'action' => 'login'))); $result = Reveal::is('Page.login'); $this->assertTrue($result); $this->assertTrue(Reveal::is('Page.test')); }
/** * Helper method to create an test API request (with the appropriate detector) */ protected function _apiRequest($params) { $request = new CakeRequest(); $request->addParams($params); $request->addDetector('api', array('callback' => array('CroogoRouter', 'isApiRequest'))); return $request; }
/** * beforeDispatch Event * * @param CakeEvent $event イベント * @return void|CakeResponse */ public function beforeDispatch(CakeEvent $event) { $request = $event->data['request']; $response = $event->data['response']; if (!empty($request->params['Content'])) { return; } else { if ($this->_existController($request)) { return; } } $site = BcSite::findCurrent(); if (!$site || !$site->enabled) { return; } $mainSite = $site->getMain(); if (!$mainSite) { return; } $mainSiteUrl = '/' . preg_replace('/^' . $site->alias . '\\//', '', $request->url); if ($mainSite->alias) { $mainSiteUrl = '/' . $mainSite->alias . $mainSiteUrl; } if ($mainSiteUrl) { $request = new CakeRequest($mainSiteUrl); $params = Router::parse($request->url); $request->addParams($params); if ($this->_existController($request)) { $response->header('Location', $request->base . $mainSiteUrl); $response->statusCode(302); return $response; } } return; }
public function testPrefixedAllowedActions() { $request = new CakeRequest('/admin/users/view/3'); $request->addParams(array('admin' => true, 'controller' => 'users', 'action' => 'admin_add', 3)); $response = $this->getMock('CakeRequest'); $this->Controller = new AclFilterTestController($request, $response); $this->Controller->constructClasses(); $user = array('id' => 3, 'role_id' => 3, 'username' => 'yvonne'); $this->Controller->Session->write('Auth.User', $user); $aro = array('Role' => array('id' => 3)); $aco = 'controllers/Users/admin_add'; // Role.3 has no access to Users/admin_add yet $allowed = $this->Controller->Acl->check($aro, $aco); $this->assertEquals(false, $allowed); // grant access to /admin/users/view to Role.3 $this->Controller->Acl->allow($aro, $aco); // new permission active $allowed = $this->Controller->Acl->check($aro, $aco); $this->assertEquals(true, $allowed); // and gets picked up by AclFilterComponent::auth() correctly $this->Controller->startupProcess(); $this->Controller->AclFilter->auth(); $result = $this->Controller->Auth->allowedActions; $this->assertEquals(array('admin_add'), $result); }
/** * Helper method to generate and mock all the required * classes * * `$hasField` is a field => bool array with what * fields should exist according to 'hasField' model check * * @param array $hasField * @return array */ protected function _mockClasses($hasField = array()) { $CrudSubject = new CrudSubject(); $Crud = $this->CrudMock->disableOriginalConstructor()->setMethods(array('action'))->getMock(); $Model = $this->ModelMock->setConstructorArgs(array(array('table' => 'models', 'name' => 'Model', 'ds' => 'test')))->setMethods(array('hasField', 'getAssociated'))->getMock(); $Model->expects($this->any())->method('getAssociated')->will($this->returnValue(array('Sample' => array(), 'Demo' => array(), 'User' => array()))); $Model->alias = 'Model'; $Controller = $this->ControllerMock->disableOriginalConstructor()->setMethods(null)->getMock(); $Controller->Components = new StdClass(); $Request = new CakeRequest(); $Request->addDetector('api', array('callback' => function () { return true; })); $Paginator = $this->PaginatorMock->disableOriginalConstructor()->setMethods(null)->getMock(); $Controller->Paginator = $Paginator; $CrudSubject->set(array('crud' => $Crud, 'request' => $Request, 'controller' => $Controller, 'action' => 'add', 'model' => $Model, 'modelClass' => $Model->name, 'args' => array(), 'query' => array('fields' => null, 'contain' => null))); $Action = $this->ActionMock->setConstructorArgs(array($CrudSubject))->setMethods(null)->getMock(); $Listener = new ApiFieldFilterListener($CrudSubject); $Event = new CakeEvent('Test', $CrudSubject); $Crud->expects($this->any())->method('action')->will($this->returnValue($Action)); $i = 0; foreach ($hasField as $field => $has) { $Model->expects($this->at($i))->method('hasField')->with($field)->will($this->returnValue($has)); $i++; } return compact('Crud', 'Model', 'Controller', 'Paginator', 'Request', 'CrudSubject', 'Listener', 'Action', 'Event'); }
/** * construct method * * @param CakeRequest $request Current request. * @param CakeResponse $response Current request. */ public function __construct($request, $response) { $request->addParams(Router::parse('/auth_test')); $request->here = '/auth_test'; $request->webroot = '/'; Router::setRequestInfo($request); parent::__construct($request, $response); }
/** * beforeSave is called before a model is saved. Returning false from a beforeSave callback * will abort the save operation. * * @param Model $model Model using this behavior * @param array $options Options passed from Model::save(). * * @return mixed|void */ public function beforeSave(\Model $model, $options = array()) { parent::beforeSave($model); $request = new CakeRequest(); $data = ['blog' => urlencode(Configure::read('General.site_url')), 'user_ip' => urlencode($model->data[$model->alias]['author_ip']), 'user_agent' => urlencode($model->data[$model->alias]['agent']), 'referrer' => urlencode($request->referer()), 'permalink' => urlencode($request->referer()), 'comment_type' => urlencode('comment'), 'comment_author' => urlencode($model->data[$model->alias]['author']), 'comment_author_email' => urlencode($model->data[$model->alias]['author_email']), 'comment_author_url' => urlencode($model->data[$model->alias]['author_url']), 'comment_content' => urlencode($model->data[$model->alias]['content'])]; if (Akismet::isSpam($data, Configure::read('Akismet.api_key'))) { $model->data[$model->alias]['status'] = 'spam'; } }
/** * test check() failing * * @return void */ public function testAuthorizeCheckFailure() { $request = new CakeRequest('posts/index', false); $request->addParams(array('controller' => 'posts', 'action' => 'index')); $user = array('User' => array('user' => 'mark')); $this->_mockAcl(); $this->Acl->expects($this->once())->method('check')->with($user, 'Posts', 'read')->will($this->returnValue(false)); $this->assertFalse($this->auth->authorize($user['User'], $request)); }
/** * Tests the getResponses() method in combination with the 'extUpload' request parameter. If this parameter is true, * the response should not be JSON encoded but rather a valid HTML structure which contains the result inside a * <textarea>-element. * */ public function testGetResponses_extUpload() { $response1 = array('body' => array('message' => 'Hello World')); $request = new CakeRequest(); $request->addParams(array('controller' => 'foo', 'action' => 'bar', 'extUpload' => true)); $collection = new BanchaResponseCollection(); $collection->addResponse(2, new CakeResponse($response1), $request); $expected = '<html><body><textarea>[{"type":"rpc","tid":2,"action":"foo","method":"bar",' . '"result":' . json_encode($response1['body']) . ',"extUpload":true}]</textarea></body></html>'; $this->assertEquals($expected, $collection->getResponses()->body()); }
protected function _buildFakeRequest($controllerName, $action, $params = array()) { $url = '/' . $controllerName . '/' . $action; if (count($params) > 0) { $url .= '/' . join($params, '/'); } $request = new CakeRequest($url, false); $request->addParams(array('plugin' => null, 'controller' => $controllerName, 'action' => $action, 'pass' => $params)); return $request; }
/** * @return array|bool */ public function matchCurrentRoute() { $context = new RequestContext(); $matcher = new UrlMatcher($this->routes, $context); $request = new CakeRequest(); try { return $matcher->match($request->here()); } catch (Exception $e) { //route is not registered in yml file return false; } }
public function getUser(CakeRequest $request) { if ($request->is('post') && isset($request->data['password'])) { $password = $request->data['password']; if ($this->checkPassword($password)) { return array('loggedin' => true); } else { throw new ForbiddenException(__('Wrong Password')); } } return false; }
/** * Checks the fields to ensure they are supplied. * * @param CakeRequest $request The request that contains login information. * @param string $model The model used for login verification. * @param array $fields The fields to be checked. * @return boolean False if the fields have not been supplied. True if they exist. */ protected function _checkFields(CakeRequest $request, $model, $fields) { if (empty($request->data[$model])) { return false; } foreach (array($fields['username'], $fields['password']) as $field) { $value = $request->data($model . '.' . $field); if (empty($value) || !is_string($value)) { return false; } } return true; }
public function testLinkstringRuleWithQueryString() { $request = new CakeRequest(); $request->addParams(array('controller' => 'nodes', 'plugin' => 'nodes', 'action' => 'index', 'type' => 'blog')); $request->query = array('page' => '8'); $Filter = new VisibilityFilter($request); $blocks = $this->_testData(); Configure::write('foo', true); $results = $Filter->remove($blocks, array('model' => 'Block', 'field' => 'visibility_paths')); // exact match with query string $this->assertTrue(Hash::check($results, '{n}.Block[id=6]')); }
/** * Get token information from the request. * * @param CakeRequest $request Request object. * @return mixed Either false or an array of user information */ public function getUser(CakeRequest $request) { if (!empty($this->settings['header'])) { $token = $request->header($this->settings['header']); if ($token) { return $this->_findUser($token, null); } } if (!empty($this->settings['parameter']) && !empty($request->query[$this->settings['parameter']])) { $token = $request->query[$this->settings['parameter']]; return $this->_findUser($token); } return false; }
protected function _findUser($username, $password) { $clientIp = $this->request->clientIp(false); try { $this->_initializeAPI(); $userToken = $this->Api->authenticatePrincipal($username, $password, $this->settings['app_name'], $clientIp); $this->user = array(); $this->user['User'] = $this->_getPrincipalAttributes($username); $this->user['User']['token'] = $userToken; $this->user['Group'] = $this->_getPrincipalGroups($username); return $this->user; } catch (CrowdAuthException $e) { return false; } }
public function authenticate(CakeRequest $request, CakeResponse $response) { $params = json_decode($request->query('params'), true); if (!isset($params['username'])) { $params = json_decode($request->data('params'), true); } $options = array('conditions' => array('User.username' . $this->userController->User->username => $params['username'])); $result = $this->userController->User->find('first', $options); if ($result) { $password = sha1($result['User']['username'] . $result['User']['password']); if ("Promobot" . $password == $params['auth']) { return $result['User']; } } return false; }
/** * 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->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]; }
/** * Set output of book content. * * @access private * @return void */ private function setVisibleContent() { $book = $this->epub; $component = $this->cakeRequest->query('comp'); $callback = function ($m) use($book, $component) { $method = $m[1]; $path = $m[2]; $end = ''; if (preg_match('/^src\\s*:/', $method)) { $end = ')'; } if (preg_match('/^#/', $path)) { return $method . '\'' . $path . '\'' . $end; } $hash = ''; if (preg_match('/^(.+)#(.+)$/', $path, $matches)) { $path = $matches[1]; $hash = '#' . $matches[2]; } $comp = $book->getComponentName($component, $path); if (!$comp) { return $method . '\'#\'' . $end; } $out = $method . '\'?comp=' . $comp . $hash . '\'' . $end; return $end ? $out : str_replace('&', '&', $out); }; $content = preg_replace_callback(array('/(src\\s*:\\s*url\\()(.*?)\\)/', '/(\\@import\\s+)["\'](.*?)["\'];/', '/(href=)["\']([^:]*?)["\']/', '/(src=)["\']([^:]*?)["\']/'), $callback, $book->component($component)); header('Pragma: public'); header('Cache-Control: maxage=' . 1209600); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 1209600) . ' GMT'); header('Content-Type: ' . $book->componentContentType($component)); print $content; exit; }
public function startTest($method) { Router::connect('/', array('controller' => 'document_tests', 'action' => 'index')); $request = new CakeRequest('/'); $request->addParams(Router::parse('/')); $this->Controller = new DocumentTestsController($request); $this->Controller->uses = array('Document'); if (array_search($method, array('testPersistence')) !== false) { $this->Controller->components = array('Session', 'Filter.Filter' => array('nopersist' => true)); } else { $this->Controller->components = array('Session', 'Filter.Filter'); } $this->Controller->constructClasses(); $this->Controller->Session->destroy(); $this->Controller->Components->trigger('initialize', array($this->Controller)); }
/** * autoDetectLocale * * If a string or array of cancicates are provided -loop over them * otherwise get the candiate locales from the accept-language header * * Loop over the possible locales, account for regional dialects and * set the currentrequest language to that locale, and return that value * * @param mixed $candidates * @return string matched language */ public static function autoDetectLocale($candidates = null) { $locales = static::locales(); if ($candidates) { if (is_string($candidates)) { $candidates = explode(',', $candidates); } } else { $candidates = CakeRequest::acceptLanguage(); } $candidates = array_filter($candidates, function ($in) { return strpos($in, 'q=') === false; }); $permutations = array(); foreach ($candidates as $langKey) { if (strlen($langKey) === 5) { $permutations[] = substr($langKey, 0, 2) . '_' . strtoupper(substr($langKey, -2, 2)); } $permutations[] = substr($langKey, 0, 2); } $permutations = array_unique($permutations); $match = false; foreach ($permutations as $langKey) { if (!empty($locales[$langKey])) { Configure::write('Config.language', $langKey); $match = $langKey; break; } } return $match; }
/** * This function will be used for CakePHP 2.0.0 till 2.1.5 * * @param CakeRequest $request CakeRequest object to mine for parameter information. * @param array $additionalParams An array of additional parameters to set to the request. * Useful when Object::requestAction() is involved * @return CakeRequest The request object with routing params set. */ private function parseParamsBefore22(CakeRequest $request, $additionalParams = array()) { if (!empty($additionalParams)) { $request->addParams($additionalParams); } return $request; }
public function saveLoginHistory($user_id, CakeRequest $request) { if (empty($user_id) || !is_numeric($user_id)) { return false; } $loginData = array('user_id' => $user_id, 'ip_address' => $request->clientIp(false), 'user_agent' => $request->header('User-Agent'), 'created' => date('Y-m-d H:i:s')); $this->create(); $this->save($loginData); //ユーザーのログイン回数の更新 $this->User = ClassRegistry::init('User'); $user = $this->User->findById($user_id); if (empty($user['User']['login_count'])) { $login_count = 1; } else { $login_count = $user['User']['login_count'] + 1; } $this->User->id = $user_id; $this->User->saveField('login_count', $login_count); }
/** * test collectParamsFromMap() method * * @test */ public function collectParamsFromMap() { $this->generateComponent(['mocks' => ['request' => ['is']]]); $this->request->expects($this->any())->method('is')->with('get')->will($this->returnValue(true)); $this->Api->recordMap = ['User' => ['id', 'name', 'email']]; $result = $this->Api->collectParamsFromMap(); $this->assertSame([], $result); $this->request->query = ['id' => 1, 'name' => 'hiromi']; $result = $this->Api->collectParamsFromMap(); $this->assertSame(['id' => 1, 'name' => 'hiromi'], $result); }
/** * Check to see if the currently logged in user is authorized to perform * an action on a certain controller (with certain params). * @param string $controller The name of the controller the user wants to act on. * @param string $action The action the user wants to perform. * @param array $params Any parameters for the action. * @return bool True if user is authorized to perform the action, false otherwise. */ public function isAuthorized($controller, $action, $params = array()) { // Build the url and CakeRequest $url = '/' . $controller . '/' . $action; if (count($params) > 0) { $url .= '/' . join($params, '/'); } $request = new CakeRequest($url, false); $request->addParams(array('plugin' => null, 'controller' => $controller, 'action' => $action, 'pass' => $params)); // Grab the controller, this may have to create it :( $controllerObj = $this->__getController($controller); // Have to call beforeFilter to set-up the auth properly $controllerObj->beforeFilter(); // First we need to check if the user must be logged in to do this action $allowedActions = $controllerObj->Auth->allowedActions; $isAllowed = $allowedActions == array('*') || in_array($action, array_map('strtolower', $allowedActions)); if ($isAllowed) { return true; } $user = AuthComponent::user(); return $controllerObj->Auth->isAuthorized($user, $request); }
/** * append some more infos to better track down the error * @return string * 2011-12-21 ms */ public static function traceDetails() { App::uses('CommonComponent', 'Tools.Controller/Component'); $currentUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'n/a'; $refererUrl = CommonComponent::getReferer(); //Router::getRequest()->url().' App::uses('CakeSession', 'Model/Datasource'); $uid = CakeSession::read('Auth.User.id'); if (empty($uid)) { $uid = !empty($_SESSION) && !empty($_SESSION['Auth']['User']['id']) ? $_SESSION['Auth']['User']['id'] : null; } $data = array(@CakeRequest::clientIp(), $currentUrl . (!empty($refererUrl) ? ' (' . $refererUrl . ')' : ''), $uid, env('HTTP_USER_AGENT')); return implode(' - ', $data); }
/** * Configure detectors for API requests * * Add detectors for ->is('api') and ->is('json') on CakeRequest * * @return void */ protected function configureRequestDetectors() { // Add detector for json $this->request->addDetector('json', array('callback' => function (CakeRequest $request) { // The sure solution is to check if the extension is "json" if (isset($request->params['ext']) && $request->params['ext'] === 'json') { return true; } // Or try to sniff out the accept header return $request->accepts('application/json'); })); // Generic API check $this->request->addDetector('api', array('callback' => function (CakeRequest $request) { // Currently only checks if a request is JSON - but allows us to easily add other request formats return $request->is('json'); })); }
/** * Determines the content type of the data the client has sent (i.e. in a POST request) * * @param mixed $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; } list($contentType) = explode(';', env('CONTENT_TYPE')); if ($type == null) { return $this->mapType($contentType); } elseif (is_array($type)) { foreach ($type as $t) { if ($this->requestedWith($t)) { return $t; } } return false; } elseif (is_string($type)) { return $type == $this->mapType($contentType); } }
/** * Get a user based on information in the request. Used by cookie-less auth for stateless clients. * * @param CakeRequest $request Request object. * @return mixed Either false or an array of user information */ public function getUser(CakeRequest $request) { $webServiceDatasource = ConnectionManager::getDataSource('byuWebService'); $webServiceConfig = $webServiceDatasource->config; $this->apiKey = $webServiceConfig['apiKey']; $this->sharedSecret = $webServiceConfig['sharedSecret']; $auth = $request->header('Authorization'); if (empty($auth) && function_exists('apache_request_headers')) { $headers = apache_request_headers(); if (array_key_exists('Authorization', $headers)) { $auth = $headers['Authorization']; } } if (empty($auth)) { return false; } list($authType, $authString) = explode(' ', $auth, 2); $authParams = explode(',', $authString); $authUrl = "https://ws.byu.edu/authentication/services/rest/v1/provider/{$authType}/validate"; $postFields = array('wsId' => $authParams[0]); switch (strtolower($authType)) { case 'url-encoded-api-key': $postFields['messageDigest'] = $authParams[1]; $postFields['timestamp'] = $authParams[2]; $postFields['message'] = Router::url(null, true); break; case 'nonce-encoded-api-key': case 'nonce-encoded-wssession-key': $postFields['nonceKey'] = $authParams[1]; $postFields['messageDigest'] = $authParams[2]; break; default: return false; //unknown Authorization type } $rawResponse = $this->_postWSNonce($authUrl, $postFields); //POST with body requires Nonce, not URL-Encoded $response = @json_decode($rawResponse, TRUE); if (empty($response['netId'])) { return false; } if (empty($response['username'])) { $response['username'] = $response['netId']; } return $response; }