/** * Purge ConnectionManager configs. * * @return void */ public static function tearDownAfterClass() { foreach (self::$datasources as $ds => $configs) { \Cake\Datasource\ConnectionManager::drop($ds); } \Cake\Utility\Security::salt(''); }
/** * Callback for Routing.beforeDispatch event. * * @param \Cake\Event\Event $event The event instance. * * @return \Cake\Network\Response Response instance. */ public function beforeDispatch(Event $event) { $request = $event->data['request']; $response = $event->data['response']; $path = urldecode($request->url); if (Configure::read('Glide.secureUrls')) { SignatureFactory::create(Security::salt())->validateRequest('/' . $path, $request->query); } $server = ServerFactory::create(Configure::read('Glide.serverConfig')); $cache = Configure::read('Glide.cache'); if ($cache) { $timestamp = $server->getSource()->getTimestamp($server->getSourcePath($path)); $response->modified($timestamp); if (!$response->checkNotModified($request)) { $response = $server->getImageResponse($path, $request->query); } $response->cache($timestamp, $cache); } else { $response = $server->getImageResponse($path, $request->query); } $headers = Hash::filter((array) Configure::read('Glide.headers')); foreach ($headers as $key => $value) { $response->header($key, $value); } return $response; }
/** * Initialize config data and properties. * * @param array $config The config data. * @return void */ public function initialize(array $config) { if (!$this->_config['cypherKey']) { $this->config('cypherKey', Security::salt()); } $this->Cookie->configKey($this->config('cookieName'), ['key' => $this->config('cypherKey'), 'expires' => $this->config('period')]); }
/** * Get URL builder instance. * * @return \League\Urls\UrlBuilder URL builder instance. */ public function urlBuilder() { if (!isset($this->_urlBuilder)) { $this->_urlBuilder = UrlBuilderFactory::create(Configure::read('Glide.serverConfig.base_url'), Configure::read('Glide.secureUrls') ? Security::salt() : null); } return $this->_urlBuilder; }
/** * Authenticate users based on their JWT. This is inspired by * the method _findUser in admads JWT plugin * * @see https://github.com/ADmad/cakephp-jwt-auth/blob/master/src/Auth/JwtAuthenticate.php * @param string $token The token identifier. * @param mixed $extra Unused * @return array */ public function processAuthenticate($token, $extra = null) { try { $token = JWT::decode($token, Security::salt(), Configure::read('Websockets.allowedAlgs')); } catch (Exception $e) { if (Configure::read('debug')) { throw $e; } return ["FAILURE"]; } if ($token->id == 'server') { return ["SUCCESS", ["authid" => $token->id]]; } $fields = Configure::read('Websockets.fields'); $table = TableRegistry::get(Configure::read('Websockets.userModel')); $conditions = [$table->aliasField($fields['id']) => $token->id]; if (!empty(Configure::read('Websockets.scope'))) { $conditions = array_merge($conditions, Configure::read('Websockets.scope')); } $result = $table->find('all')->where($conditions)->first(); if (empty($result)) { return ["FAILURE"]; } return ["SUCCESS", ["authid" => $result->id]]; }
public function token() { $user = $this->Auth->identify(); if (!$user) { throw new UnauthorizedException('Invalid username or password'); } $this->set(['success' => true, 'data' => ['token' => $token = \JWT::encode(['id' => $user['id'], 'exp' => time() + 604800], Security::salt())], '_serialize' => ['success', 'data']]); }
/** * setUp * * @return void */ public function setUp() { parent::setUp(); Security::salt('12345678901234567890123456789012345678901'); $this->controller = new Controller(new Request(), new Response()); $this->controller->loadComponent('Cookie'); $this->controller->loadComponent('Auth'); }
public function login($provider = null) { if ($provider) { $config = ['path' => Router::url(['action' => 'login']) . '/', 'callback_url' => Router::url(['action' => 'callback']), 'security_salt' => Security::salt(), 'Strategy' => Configure::read('OpauthStrategy')]; $opauth = new \Opauth($config, true); } else { throw new NotFoundException(); } }
public function token() { $user = $this->Auth->identify(); if (!$user) { throw new UnauthorizedException('Invalid username or password'); } $this->set('data', ['user' => $user, 'token' => $token = \JWT::encode(['id' => $user['id'], 'user' => $user, 'exp' => time() + 604800], Security::salt())]); $this->ApiBuilder->execute(); }
public function google() { $data = $this->request->input('json_decode'); $user = $this->Users->find('all')->where(['Users.provider' => 'facebook', 'Users.provider_uid' => $data->clientId])->first(); if (!$user) { throw new UnauthorizedException('Invalid username or password'); } $this->Auth->setUser($user); $this->set(['success' => true, 'data' => ['token' => JWT::encode(['sub' => $user['id'], 'exp' => time() + 1800], Security::salt()), 'user_id' => $user['id']], '_serialize' => ['success', 'data']]); }
public function createToken() { $customer = $this->Customers->find('all', ['fields' => ['id', 'email', 'name', 'password'], 'conditions' => ['email' => $this->request->data('email'), 'gym_id' => $this->request->query('gym_id'), 'deleted' => false, 'is_active' => true]])->first(); if (!$customer || !(new DefaultPasswordHasher())->check($this->request->data('password'), $customer->password)) { throw new UnauthorizedException('Invalid username or password'); } $customer->sub = $customer->id; unset($customer->password); $this->set(['message' => ['user' => ['name' => $customer->name], 'token' => JWT::encode($customer->toArray(), Security::salt())]]); $this->set('_serialize', ['message']); }
/** * Test initialize method * * @return void */ public function testInitializeException() { $salt = Security::salt(); Security::salt('too small'); try { $this->rememberMeComponent = new RememberMeComponent($this->registry, []); } catch (InvalidArgumentException $ex) { $this->assertEquals('Invalid app salt, app salt must be at least 256 bits (32 bytes) long', $ex->getMessage()); } Security::salt($salt); }
/** * Setup * * @return void */ public function setUp() { parent::setUp(); Configure::write('App.namespace', 'TestApp'); Security::salt('not-the-default'); DispatcherFactory::add('Routing'); DispatcherFactory::add('ControllerFactory'); $this->object = $this->getObjectForTrait('Cake\\Routing\\RequestActionTrait'); Router::connect('/request_action/:action/*', ['controller' => 'RequestAction']); Router::connect('/tests_apps/:action/*', ['controller' => 'TestsApps']); }
/** * setup * * @return void */ public function setUp() { parent::setUp(); $this->request = new Request('posts/index'); Router::setRequestInfo($this->request); $this->response = $this->getMock('Cake\\Network\\Response'); Security::salt('Xety-Cake3CookieAuth_Xety-Cake3CookieAuth'); $this->registry = new ComponentRegistry(new Controller($this->request, $this->response)); $this->registry->load('Cookie'); $this->registry->load('Auth'); $this->auth = new CookieAuthenticate($this->registry); $password = password_hash('password', PASSWORD_DEFAULT); $Users = TableRegistry::get('Users'); $Users->updateAll(['password' => $password], []); }
/** * setup * * @return void */ public function setUp() { parent::setUp(); $this->request = new Request('posts/index'); Router::setRequestInfo($this->request); $this->response = $this->getMock('Cake\\Network\\Response'); Security::salt('somerandomhaskeysomerandomhaskey'); $this->Registry = new ComponentRegistry(new Controller($this->request, $this->response)); $this->Registry->load('Cookie'); $this->Registry->load('Auth'); $this->auth = new CookieAuthenticate($this->Registry, ['fields' => ['username' => 'user_name', 'password' => 'password'], 'userModel' => 'MultiUsers']); $password = password_hash('password', PASSWORD_DEFAULT); $MultiUsers = TableRegistry::get('MultiUsers'); $MultiUsers->updateAll(['password' => $password], []); }
/** * setUp method * * @return void */ public function setUp() { parent::setUp(); Security::salt('YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi'); Configure::write('App.namespace', 'TestApp'); Router::scope('/', function ($routes) { $routes->fallbacks('InflectedRoute'); }); $request = new Request(); $response = $this->getMock('Cake\\Network\\Response', ['stop']); $this->Controller = new AuthTestController($request, $response); $this->Auth = new TestAuthComponent($this->Controller->components()); $Users = TableRegistry::get('AuthUsers'); $Users->updateAll(['password' => password_hash('cake', PASSWORD_BCRYPT)], []); }
public function login() { $user = $this->Auth->user(); if (!$user) { $this->request->data('id', (string) $this->request->data('id')); if ($this->request->is('put') || $this->request->is('post')) { $user = $this->Auth->identify(); } } if (!$user) { throw new UnauthorizedException('Invalid username or password'); } $this->Auth->setUser($user); $this->set(['_serialize' => ['class' => 'Auth', 'token' => JWT::encode(['sub' => $user['id'], 'exp' => time() + 604800], Security::salt()), 'player' => '/players/' . $user['id']]]); }
/** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this->backupUsersConfig = Configure::read('Users'); Router::reload(); Plugin::routes('CakeDC/Users'); Router::connect('/route/*', ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'requestResetPassword']); Security::salt('YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi'); Configure::write('App.namespace', 'Users'); $this->request = $this->getMock('Cake\\Network\\Request', ['is', 'method']); $this->request->expects($this->any())->method('is')->will($this->returnValue(true)); $this->response = $this->getMock('Cake\\Network\\Response', ['stop']); $this->Controller = new Controller($this->request, $this->response); $this->Registry = $this->Controller->components(); $this->Controller->UsersAuth = new UsersAuthComponent($this->Registry); }
public function login() { $user = $this->Auth->identify(); if (!$user) { $this->set(['success' => false, 'message' => __('Invalid email or password'), '_serialize' => ['success', 'message']]); } else { $expire = !is_null(Configure::read('AuthToken.expire')) ? Configure::read('AuthToken.expire') : 3600; $access_token = JWT::encode(['sub' => $user['id'], 'exp' => time() + $expire], Security::salt()); $refresh_token = JWT::encode(['sub' => $user['id'], 'ref' => time()], Security::salt()); $authToken = $this->Users->AuthToken->newEntity(); $authToken->user_id = $user['id']; $authToken->access_token = $access_token; $authToken->refresh_token = $refresh_token; $this->Users->AuthToken->save($authToken); $this->set(['success' => true, 'data' => ['access_token' => $access_token, 'refresh_token' => $refresh_token, 'id' => $user['id'], 'username' => $user['username'], 'email' => $user['email']], '_serialize' => ['success', 'data']]); } }
public function token() { if ($this->request->is('post')) { $table = TableRegistry::get('AuthToken'); $refresh_token = $this->request->data('refresh_token'); $authToken = $table->find('all')->where(['refresh_token' => $refresh_token])->first(); if ($authToken) { $expire = !is_null(Configure::read('AuthToken.expire')) ? Configure::read('AuthToken.expire') : 3600; $access_token = JWT::encode(['sub' => $authToken['user_id'], 'exp' => time() + $expire], Security::salt()); $refresh_token = JWT::encode(['sub' => $authToken['user_id'], 'ref' => time()], Security::salt()); $authToken->access_token = $access_token; $authToken->refresh_token = $refresh_token; $table->save($authToken); $this->set(['success' => true, 'data' => ['access_token' => $access_token, 'refresh_token' => $refresh_token], '_serialize' => ['success', 'data']]); } else { $this->set(['success' => false, 'refresh_token_expired' => true, '_serialize' => ['success', 'refresh_token_expired']]); } } }
public function setUp() { parent::setUp(); Configure::write('Config.language', 'eng'); Configure::write('App.base', ''); Configure::write('App.namespace', 'BootstrapUI\\Test\\TestCase\\View\\Helper'); Configure::delete('Asset'); $this->View = new View(); $this->Form = new FormHelper($this->View); $request = new Request('articles/add'); $request->here = '/articles/add'; $request['controller'] = 'articles'; $request['action'] = 'add'; $request->webroot = ''; $request->base = ''; $this->Form->Url->request = $this->Form->request = $request; $this->article = ['schema' => ['id' => ['type' => 'integer'], 'author_id' => ['type' => 'integer', 'null' => true], 'title' => ['type' => 'string', 'null' => true], 'body' => 'text', 'published' => ['type' => 'boolean', 'length' => 1, 'default' => 0], '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]], 'required' => ['author_id' => true, 'title' => true]]; Security::salt('foo!'); Router::connect('/:controller', ['action' => 'index']); Router::connect('/:controller/:action/*'); }
/** * Generate the token data for the provided inputs. * * @param string $url The URL the form is being submitted to. * @param array $fields If set specifies the list of fields to use when * generating the hash. * @param array $unlockedFields The list of fields that are excluded from * field validation. * @return array The token data. */ protected function _buildFieldToken($url, $fields, $unlockedFields = []) { $locked = []; foreach ($fields as $key => $value) { if (is_numeric($value)) { $value = (string) $value; } if (!is_int($key)) { $locked[$key] = $value; unset($fields[$key]); } } sort($unlockedFields, SORT_STRING); sort($fields, SORT_STRING); ksort($locked, SORT_STRING); $fields += $locked; $locked = implode(array_keys($locked), '|'); $unlocked = implode($unlockedFields, '|'); $hashParts = [$url, serialize($fields), $unlocked, Security::salt()]; $fields = Security::hash(implode('', $hashParts), 'sha1'); return ['fields' => urlencode($fields . ':' . $locked), 'unlocked' => urlencode($unlocked)]; }
/** * Generates a hidden field with a security hash based on the fields used in * the form. * * If $secureAttributes is set, these HTML attributes will be merged into * the hidden input tags generated for the Security Component. This is * especially useful to set HTML5 attributes like 'form'. * * @param array $fields If set specifies the list of fields to use when * generating the hash, else $this->fields is being used. * @param array $secureAttributes will be passed as HTML attributes into the hidden * input elements generated for the Security Component. * @return string|null A hidden input field with a security hash */ public function secure(array $fields = [], array $secureAttributes = []) { if (empty($this->request['_Token'])) { return null; } $locked = []; $unlockedFields = $this->_unlockedFields; foreach ($fields as $key => $value) { if (is_numeric($value)) { $value = (string) $value; } if (!is_int($key)) { $locked[$key] = $value; unset($fields[$key]); } } sort($unlockedFields, SORT_STRING); sort($fields, SORT_STRING); ksort($locked, SORT_STRING); $fields += $locked; $locked = implode(array_keys($locked), '|'); $unlocked = implode($unlockedFields, '|'); $hashParts = [$this->_lastAction, serialize($fields), $unlocked, Security::salt()]; $fields = Security::hash(implode('', $hashParts), 'sha1'); $tokenFields = array_merge($secureAttributes, ['value' => urlencode($fields . ':' . $locked)]); $out = $this->hidden('_Token.fields', $tokenFields); $tokenUnlocked = array_merge($secureAttributes, ['value' => urlencode($unlocked)]); $out .= $this->hidden('_Token.unlocked', $tokenUnlocked); return $this->formatTemplate('hiddenBlock', ['content' => $out]); }
$s = null; if (env('HTTPS')) { $s = 's'; } $httpHost = env('HTTP_HOST'); if (isset($httpHost)) { Configure::write('App.fullBaseUrl', 'http' . $s . '://' . $httpHost); } unset($httpHost, $s); } Cache::config(Configure::consume('Cache')); ConnectionManager::config(Configure::consume('Datasources')); Email::configTransport(Configure::consume('EmailTransport')); Email::config(Configure::consume('Email')); Log::config(Configure::consume('Log')); Security::salt(Configure::consume('Security.salt')); /** * The default crypto extension in 3.0 is OpenSSL. * If you are migrating from 2.x uncomment this code to * use a more compatible Mcrypt based implementation */ // Security::engine(new \Cake\Utility\Crypto\Mcrypt()); /** * Setup detectors for mobile and tablet. */ Request::addDetector('mobile', function ($request) { $detector = new \Detection\MobileDetect(); return $detector->isMobile(); }); Request::addDetector('tablet', function ($request) { $detector = new \Detection\MobileDetect();
/** * Find a user record. * * @param string $token The token identifier. * @param string $password Unused password. * @return bool|array Either false on failure, or an array of user data. */ protected function _findUser($token, $password = null) { try { $token = JWT::decode($token, Security::salt(), $this->_config['allowedAlgs']); } catch (Exception $e) { if (Configure::read('debug')) { throw $e; } return false; } // Token has full user record. if (isset($token->record)) { // Trick to convert object of stdClass to array. Typecasting to // array doesn't convert property values which are themselves objects. return json_decode(json_encode($token->record), true); } $fields = $this->_config['fields']; $table = TableRegistry::get($this->_config['userModel']); $conditions = [$table->aliasField($fields['id']) => $token->id]; if (!empty($this->_config['scope'])) { $conditions = array_merge($conditions, $this->_config['scope']); } $query = $table->find('all')->where($conditions)->hydrate(false); if ($this->_config['contain']) { $query = $query->contain($this->_config['contain']); } $result = $query->first(); if (empty($result)) { return false; } unset($result[$fields['password']]); return $result; }
/** * Initialize config data and properties. * * @param array $config The config data. * @return void */ public function initialize(array $config) { if (!$this->_config['key']) { $this->config('key', Security::salt()); } $controller = $this->_registry->getController(); if ($controller && isset($controller->request)) { $this->_request = $controller->request; } else { $this->_request = Request::createFromGlobals(); } if (empty($this->_config['path'])) { $this->config('path', $this->_request->base ?: '/'); } if ($controller && isset($controller->response)) { $this->_response = $controller->response; } else { $this->_response = new Response(); } }
/** * Test that security hashes for postLink include the url. * * @return void */ public function testPostLinkSecurityHash() { $hash = Security::hash('/posts/delete/1' . serialize([]) . '' . Security::salt()); $hash .= '%3A'; $this->Form->request->params['_Token']['key'] = 'test'; $result = $this->Form->postLink('Delete', '/posts/delete/1'); $expected = ['form' => ['method' => 'post', 'action' => '/posts/delete/1', 'name', 'style' => 'display:none;'], ['input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST']], 'div' => ['style' => 'display:none;'], ['input' => ['type' => 'hidden', 'name' => '_Token[fields]', 'value' => $hash]], ['input' => ['type' => 'hidden', 'name' => '_Token[unlocked]', 'value' => '']], '/div', '/form', 'a' => ['href' => '#', 'onclick' => 'preg:/document\\.post_\\w+\\.submit\\(\\); event\\.returnValue = false; return false;/'], 'Delete', '/a']; $this->assertHtml($expected, $result); }
/** * Test that values like Foo.0.1 * * @return void * @triggers Controller.startup $this->Controller */ public function testValidateNestedNumericSets() { $event = new Event('Controller.startup', $this->Controller); $this->Controller->Security->startup($event); $unlocked = ''; $hashFields = ['TaxonomyData']; $fields = urlencode(Security::hash('/articles/index' . serialize($hashFields) . $unlocked . Security::salt())); $this->Controller->request->data = ['TaxonomyData' => [1 => [[2]], 2 => [[3]]], '_Token' => compact('fields', 'unlocked')]; $result = $this->Controller->Security->validatePost($this->Controller); $this->assertTrue($result); }
/** * Validate submitted form * * @param Controller $controller Instantiating controller * @return bool true if submitted form is valid */ protected function _validatePost(Controller $controller) { if (empty($controller->request->data)) { return true; } $check = $controller->request->data; if (!isset($check['_Token']) || !isset($check['_Token']['fields']) || !isset($check['_Token']['unlocked'])) { return false; } $locked = ''; $token = urldecode($check['_Token']['fields']); $unlocked = urldecode($check['_Token']['unlocked']); if (strpos($token, ':')) { list($token, $locked) = explode(':', $token, 2); } unset($check['_Token'], $check['_csrfToken']); $locked = explode('|', $locked); $unlocked = explode('|', $unlocked); $lockedFields = []; $fields = Hash::flatten($check); $fieldList = array_keys($fields); $multi = []; foreach ($fieldList as $i => $key) { if (preg_match('/(\\.\\d+){1,10}$/', $key)) { $multi[$i] = preg_replace('/(\\.\\d+){1,10}$/', '', $key); unset($fieldList[$i]); } else { $fieldList[$i] = (string) $key; } } if (!empty($multi)) { $fieldList += array_unique($multi); } $unlockedFields = array_unique(array_merge((array) $this->config('disabledFields'), (array) $this->_config['unlockedFields'], $unlocked)); foreach ($fieldList as $i => $key) { $isLocked = is_array($locked) && in_array($key, $locked); if (!empty($unlockedFields)) { foreach ($unlockedFields as $off) { $off = explode('.', $off); $field = array_values(array_intersect(explode('.', $key), $off)); $isUnlocked = $field === $off; if ($isUnlocked) { break; } } } if ($isUnlocked || $isLocked) { unset($fieldList[$i]); if ($isLocked) { $lockedFields[$key] = $fields[$key]; } } } sort($unlocked, SORT_STRING); sort($fieldList, SORT_STRING); ksort($lockedFields, SORT_STRING); $fieldList += $lockedFields; $unlocked = implode('|', $unlocked); $hashParts = [$controller->request->here(), serialize($fieldList), $unlocked, Security::salt()]; $check = Security::hash(implode('', $hashParts), 'sha1'); return $token === $check; }
/** * Verifies that the application's salt and cipher seed value has been changed from the default value. * * @return void */ public static function checkSecurityKeys() { if (Security::salt() === '__SALT__') { trigger_error(sprintf('Please change the value of %s in %s to a salt value specific to your application.', '\'Security.salt\'', 'ROOT/config/app.php'), E_USER_NOTICE); } }