From 193206f5d65a39792891160a59209deaf32f98ee Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 2 Feb 2018 14:06:45 +0100 Subject: [PATCH] Upgrade plugin to CakePHP 2.10 (latest Cake 2.x version) --- .semver | 4 +- .travis.yml | 32 +- CHANGELOG.md | 8 + .../Migration/001_initialize_users_schema.php | 81 +-- Config/Migration/002_renaming.php | 43 +- Config/Migration/map.php | 12 +- Config/Schema/schema.php | 73 +-- Config/routes.php | 14 +- .../Component/Auth/CookieAuthenticate.php | 194 +++---- .../Auth/MultiColumnAuthenticate.php | 168 +++--- .../Component/Auth/TokenAuthenticate.php | 280 +++++----- Controller/Component/RememberMeComponent.php | 478 +++++++++--------- Controller/UsersAppController.php | 4 +- Controller/UsersController.php | 206 ++++---- Locale/spa/LC_MESSAGES/users.po | 2 +- Model/User.php | 315 ++++++------ Model/UsersAppModel.php | 18 +- README.md | 12 +- Test/Case/AllAuthenticateTest.php | 45 +- Test/Case/AllUsersTest.php | 60 +-- .../Component/Auth/CookieAuthenticateTest.php | 185 +++---- .../Auth/MultiColumnAuthenticateTest.php | 305 +++++------ .../Component/Auth/TokenAuthenticateTest.php | 241 ++++----- .../Component/RememberMeComponentTest.php | 341 +++++++------ Test/Case/Controller/UsersControllerTest.php | 304 ++++++----- Test/Case/Model/UserTest.php | 177 ++++--- Test/Fixture/MultiUserFixture.php | 77 +-- Test/Fixture/UserFixture.php | 74 +-- View/Elements/Users/admin_sidebar.ctp | 10 +- View/Elements/Users/sidebar.ctp | 12 +- View/Elements/pagination.ctp | 10 +- View/Elements/paging.ctp | 5 +- View/Emails/text/account_verification.ctp | 6 +- View/Emails/text/new_password.ctp | 4 +- View/Emails/text/password_reset_request.ctp | 6 +- View/Users/add.ctp | 28 +- View/Users/admin_add.ctp | 34 +- View/Users/admin_edit.ctp | 24 +- View/Users/admin_index.ctp | 16 +- View/Users/admin_view.ctp | 4 +- View/Users/change_password.ctp | 18 +- View/Users/dashboard.ctp | 4 +- View/Users/edit.ctp | 6 +- View/Users/index.ctp | 12 +- View/Users/login.ctp | 26 +- View/Users/request_password_change.ctp | 14 +- View/Users/resend_verification.ctp | 14 +- View/Users/reset_password.ctp | 14 +- View/Users/search.ctp | 30 +- View/Users/view.ctp | 4 +- composer.json | 3 +- 51 files changed, 2075 insertions(+), 1982 deletions(-) diff --git a/.semver b/.semver index f7db3a29f..d15231aa7 100644 --- a/.semver +++ b/.semver @@ -1,5 +1,5 @@ --- :major: 2 -:minor: 1 -:patch: 3 +:minor: 2 +:patch: 0 :special: '' diff --git a/.travis.yml b/.travis.yml index e542016f9..a9ba14e70 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,39 +1,31 @@ language: php php: - - 5.3 - - 5.4 - - 5.5 + - 5.6 + - 7.0 + - 7.1 env: global: - PLUGIN_NAME=Users - DB=mysql - - REQUIRE="phpunit/phpunit:3.7.31" + - REQUIRE="phpunit/phpunit:3.7.38" matrix: - - DB=mysql CAKE_VERSION=2.6 + - DB=mysql CAKE_VERSION=2.10 matrix: include: - - php: 5.3 + - php: 5.6 env: - - CAKE_VERSION=2.6 - - php: 5.3 + - CAKE_VERSION=2.10 + - php: 7.0 env: - - CAKE_VERSION=2.7 - - php: 5.4 + - CAKE_VERSION=2.10 + - php: 7.1 env: - - CAKE_VERSION=2.6 - - php: 5.4 - env: - - CAKE_VERSION=2.7 - - php: 5.5 - env: - - CAKE_VERSION=2.6 - - php: 5.5 - env: - - CAKE_VERSION=2.7 + - CAKE_VERSION=2.10 + before_script: - git clone https://github.com/steinkel/travis.git --depth 1 ../travis diff --git a/CHANGELOG.md b/CHANGELOG.md index 85b29decc..036c19bc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,14 @@ Changelog ========= +Release 2.2.0 +------------- + +https://github.com/CakeDC/users/tree/2.2.0 + +* Upgrade plugin for compatibility with CakePHP 2.10 +* Remove deprecations + Release 2.1.3 ------------- diff --git a/Config/Migration/001_initialize_users_schema.php b/Config/Migration/001_initialize_users_schema.php index 4517dfdb4..99dbe17b9 100644 --- a/Config/Migration/001_initialize_users_schema.php +++ b/Config/Migration/001_initialize_users_schema.php @@ -2,19 +2,21 @@ /** * Users CakePHP Plugin * - * Copyright 2010 - 2014, Cake Development Corporation + * Copyright 2009 - 2018, Cake Development Corporation * 1785 E. Sahara Avenue, Suite 490-423 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @Copyright 2010 - 2014, Cake Development Corporation + * @Copyright 2009 - 2018, Cake Development Corporation * @link http://github.com/CakeDC/users * @package plugins.users.config.migrations * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + class M49c3417a54874a9d276811502cedc421 extends CakeMigration { + /** * Dependency array. Define what minimum version required for other part of db schema * @@ -22,50 +24,52 @@ class M49c3417a54874a9d276811502cedc421 extends CakeMigration { * * @var array $dependendOf */ - public $dependendOf = array(); + public $dependendOf = []; + /** * Migration array * * @var array $migration */ - public $migration = array( - 'up' => array( - 'create_table' => array( - 'users' => array( - 'id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'key' => 'primary'), - 'username' => array('type' => 'string', 'null' => false, 'default' => null), - 'slug' => array('type' => 'string', 'null' => false, 'default' => null), - 'password' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 128), - 'password_token' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 128), - 'email' => array('type' => 'string', 'null' => true, 'default' => null), - 'email_verified' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'email_token' => array('type' => 'string', 'null' => true, 'default' => null), - 'email_token_expiry' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'tos' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'active' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'last_login' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'last_action' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'is_admin' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'role' => array('type' => 'string', 'null' => true, 'default' => null), - 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'modified' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'indexes' => array( - 'PRIMARY' => array('column' => 'id', 'unique' => 1), - 'BY_USERNAME' => array('column' => array('username'), 'unique' => 0), - 'BY_EMAIL' => array('column' => array('email'), 'unique' => 0) - ), - ), - ), - ), - 'down' => array( - 'drop_table' => array('users'), - ) - ); + public $migration = [ + 'up' => [ + 'create_table' => [ + 'users' => [ + 'id' => ['type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'key' => 'primary'], + 'username' => ['type' => 'string', 'null' => false, 'default' => null], + 'slug' => ['type' => 'string', 'null' => false, 'default' => null], + 'password' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 128], + 'password_token' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 128], + 'email' => ['type' => 'string', 'null' => true, 'default' => null], + 'email_verified' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'email_token' => ['type' => 'string', 'null' => true, 'default' => null], + 'email_token_expiry' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'tos' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'active' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'last_login' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'last_action' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'is_admin' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'role' => ['type' => 'string', 'null' => true, 'default' => null], + 'created' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'modified' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'indexes' => [ + 'PRIMARY' => ['column' => 'id', 'unique' => 1], + 'BY_USERNAME' => ['column' => ['username'], 'unique' => 0], + 'BY_EMAIL' => ['column' => ['email'], 'unique' => 0] + ], + ], + ], + ], + 'down' => [ + 'drop_table' => ['users'], + ] + ]; /** * before migration callback * - * @param string $direction, up or down direction of migration process + * @param string $direction up or down direction of migration process + * @return bool */ public function before($direction) { return true; @@ -74,7 +78,8 @@ public function before($direction) { /** * after migration callback * - * @param string $direction, up or down direction of migration process + * @param string $direction up or down direction of migration process + * @return bool */ public function after($direction) { return true; diff --git a/Config/Migration/002_renaming.php b/Config/Migration/002_renaming.php index 4b116a71c..8ee9b0ca0 100644 --- a/Config/Migration/002_renaming.php +++ b/Config/Migration/002_renaming.php @@ -2,19 +2,21 @@ /** * Users CakePHP Plugin * - * Copyright 2010 - 2014, Cake Development Corporation + * Copyright 2009 - 2018, Cake Development Corporation * 1785 E. Sahara Avenue, Suite 490-423 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @Copyright 2010 - 2014, Cake Development Corporation + * @Copyright 2009 - 2018, Cake Development Corporation * @link http://github.com/CakeDC/users * @package plugins.users.config.migrations * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ + class M4ef8ba03ff504ab2b415980575f6eb26 extends CakeMigration { + /** * Dependency array. Define what minimum version required for other part of db schema * @@ -22,33 +24,35 @@ class M4ef8ba03ff504ab2b415980575f6eb26 extends CakeMigration { * * @var array $dependendOf */ - public $dependendOf = array(); + public $dependendOf = []; + /** * Migration array * * @var array $migration */ - public $migration = array( - 'up' => array( - 'rename_field' => array( - 'users' => array( + public $migration = [ + 'up' => [ + 'rename_field' => [ + 'users' => [ 'email_token_expiry' => 'email_token_expires' - ), - ), - ), - 'down' => array( - 'rename_field' => array( - 'users' => array( + ], + ], + ], + 'down' => [ + 'rename_field' => [ + 'users' => [ 'email_token_expires' => 'email_token_expiry' - ), - ), - ) - ); + ], + ], + ] + ]; /** * before migration callback * - * @param string $direction, up or down direction of migration process + * @param string $direction up or down direction of migration process + * @return bool */ public function before($direction) { return true; @@ -57,7 +61,8 @@ public function before($direction) { /** * after migration callback * - * @param string $direction, up or down direction of migration process + * @param string $direction up or down direction of migration process + * @return bool */ public function after($direction) { return true; diff --git a/Config/Migration/map.php b/Config/Migration/map.php index 8281b4d9e..1e527cff4 100644 --- a/Config/Migration/map.php +++ b/Config/Migration/map.php @@ -2,19 +2,19 @@ /** * Users CakePHP Plugin * - * Copyright 2010 - 2014, Cake Development Corporation + * Copyright 2009 - 2018, Cake Development Corporation * 1785 E. Sahara Avenue, Suite 490-423 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @Copyright 2010 - 2014, Cake Development Corporation + * @Copyright 2009 - 2018, Cake Development Corporation * @link http://github.com/CakeDC/users * @package plugins.users.config.migrations * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ -$map = array( - 1 => array('001_initialize_users_schema' => 'M49c3417a54874a9d276811502cedc421'), - 2 => array('002_renaming' => 'M4ef8ba03ff504ab2b415980575f6eb26') -); +$map = [ + 1 => ['001_initialize_users_schema' => 'M49c3417a54874a9d276811502cedc421'], + 2 => ['002_renaming' => 'M4ef8ba03ff504ab2b415980575f6eb26'] +]; diff --git a/Config/Schema/schema.php b/Config/Schema/schema.php index 4dabf4b01..065e7459b 100644 --- a/Config/Schema/schema.php +++ b/Config/Schema/schema.php @@ -1,52 +1,65 @@ - array('type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'key' => 'primary'), - 'username' => array('type' => 'string', 'null' => false, 'default' => null, 'key' => 'index'), - 'slug' => array('type' => 'string', 'null' => false, 'default' => null), - 'password' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 128), - 'password_token' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 128), - 'email' => array('type' => 'string', 'null' => true, 'default' => null, 'key' => 'index'), - 'email_verified' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'email_token' => array('type' => 'string', 'null' => true, 'default' => null), - 'email_token_expires' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'tos' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'active' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'last_login' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'last_action' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'is_admin' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'role' => array('type' => 'string', 'null' => true, 'default' => null), - 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'modified' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'indexes' => array( - 'PRIMARY' => array('column' => 'id', 'unique' => 1), - 'BY_USERNAME' => array('column' => array('username'), 'unique' => 0), - 'BY_EMAIL' => array('column' => array('email'), 'unique' => 0) - ) - ); + public $users = [ + 'id' => ['type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'key' => 'primary'], + 'username' => ['type' => 'string', 'null' => false, 'default' => null, 'key' => 'index'], + 'slug' => ['type' => 'string', 'null' => false, 'default' => null], + 'password' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 128], + 'password_token' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 128], + 'email' => ['type' => 'string', 'null' => true, 'default' => null, 'key' => 'index'], + 'email_verified' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'email_token' => ['type' => 'string', 'null' => true, 'default' => null], + 'email_token_expires' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'tos' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'active' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'last_login' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'last_action' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'is_admin' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'role' => ['type' => 'string', 'null' => true, 'default' => null], + 'created' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'modified' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'indexes' => [ + 'PRIMARY' => ['column' => 'id', 'unique' => 1], + 'BY_USERNAME' => ['column' => ['username'], 'unique' => 0], + 'BY_EMAIL' => ['column' => ['email'], 'unique' => 0] + ] + ]; } diff --git a/Config/routes.php b/Config/routes.php index 844bd54f0..a4e7f57ca 100644 --- a/Config/routes.php +++ b/Config/routes.php @@ -1,8 +1,8 @@ 'users', 'controller' => 'users')); -Router::connect('/users/index/*', array('plugin' => 'users', 'controller' => 'users')); -Router::connect('/users/:action/*', array('plugin' => 'users', 'controller' => 'users')); -Router::connect('/users/users/:action/*', array('plugin' => 'users', 'controller' => 'users')); -Router::connect('/login', array('plugin' => 'users', 'controller' => 'users', 'action' => 'login')); -Router::connect('/logout', array('plugin' => 'users', 'controller' => 'users', 'action' => 'logout')); -Router::connect('/register', array('plugin' => 'users', 'controller' => 'users', 'action' => 'add')); \ No newline at end of file +Router::connect('/users', ['plugin' => 'users', 'controller' => 'users']); +Router::connect('/users/index/*', ['plugin' => 'users', 'controller' => 'users']); +Router::connect('/users/:action/*', ['plugin' => 'users', 'controller' => 'users']); +Router::connect('/users/users/:action/*', ['plugin' => 'users', 'controller' => 'users']); +Router::connect('/login', ['plugin' => 'users', 'controller' => 'users', 'action' => 'login']); +Router::connect('/logout', ['plugin' => 'users', 'controller' => 'users', 'action' => 'logout']); +Router::connect('/register', ['plugin' => 'users', 'controller' => 'users', 'action' => 'add']); \ No newline at end of file diff --git a/Controller/Component/Auth/CookieAuthenticate.php b/Controller/Component/Auth/CookieAuthenticate.php index 554cb52f8..6322e4f59 100644 --- a/Controller/Component/Auth/CookieAuthenticate.php +++ b/Controller/Component/Auth/CookieAuthenticate.php @@ -1,87 +1,107 @@ -Auth->authenticate = array( - * 'Authenticate.Cookie' => array( - * 'fields' => array( - * 'username' => 'username', - * 'password' => 'password' - * ), - * 'userModel' => 'User', - * 'scope' => array('User.active' => 1), - * 'crypt' => 'rijndael', // Defaults to rijndael(safest), optionally set to 'cipher' if required - * 'cookie' => array( - * 'name' => 'RememberMe', - * 'time' => '+2 weeks', - * ) - * ) - * ) - * }}} - * - * @author Ceeram - * @copyright Ceeram - * @license MIT - * @link https://github.com/ceeram/Authenticate - */ -class CookieAuthenticate extends BaseAuthenticate { - - public function __construct(ComponentCollection $collection, $settings) { - $this->settings['cookie'] = array( - 'name' => 'RememberMe', - 'time' => '+2 weeks', - 'base' => Router::getRequest()->base - ); - $this->settings['crypt'] = 'rijndael'; - parent::__construct($collection, $settings); - } - -/** - * Authenticates the identity contained in the cookie. Will use the `settings.userModel`, and `settings.fields` - * to find COOKIE data that is used to find a matching record in the `settings.userModel`. Will return false if - * there is no cookie data, either username or password is missing, of if the scope conditions have not been met. - * - * @param CakeRequest $request The unused request object - * @return mixed False on login failure. An array of User data on success. - * @throws CakeException - */ - public function getUser(CakeRequest $request) { - if (!isset($this->_Collection->Cookie) || !$this->_Collection->Cookie instanceof CookieComponent) { - throw new CakeException('CookieComponent is not loaded'); - } - - $this->_Collection->Cookie->type($this->settings['crypt']); - list(, $model) = pluginSplit($this->settings['userModel']); - - $data = $this->_Collection->Cookie->read($model); - if (empty($data)) { - return false; - } - - extract($this->settings['fields']); - if (empty($data[$username]) || empty($data[$password])) { - return false; - } - - $user = $this->_findUser($data[$username], $data[$password]); - if ($user) { - $this->_Collection->Session->write(AuthComponent::$sessionKey, $user); - return $user; - } - return false; - } - - public function authenticate(CakeRequest $request, CakeResponse $response) { - return $this->getUser($request); - } - - public function logout($user) { - $this->_Collection->Cookie->destroy(); - } - -} +Auth->authenticate = array( + * 'Authenticate.Cookie' => array( + * 'fields' => array( + * 'username' => 'username', + * 'password' => 'password' + * ), + * 'userModel' => 'User', + * 'scope' => array('User.active' => 1), + * 'crypt' => 'rijndael', // Defaults to rijndael(safest), optionally set to 'cipher' if required + * 'cookie' => array( + * 'name' => 'RememberMe', + * 'time' => '+2 weeks', + * ) + * ) + * ) + * }}} + * + * @author Ceeram + * @copyright Ceeram + * @license MIT + * @link https://github.com/ceeram/Authenticate + */ +class CookieAuthenticate extends BaseAuthenticate { + +/** + * CookieAuthenticate constructor. + * + * @param ComponentCollection $collection Component collection + * @param array $settings Settings to configure + * @return void + */ + public function __construct(ComponentCollection $collection, $settings) { + $this->settings['cookie'] = [ + 'name' => 'RememberMe', + 'time' => '+2 weeks', + 'base' => Router::getRequest()->base + ]; + $this->settings['crypt'] = 'rijndael'; + parent::__construct($collection, $settings); + } + +/** + * Authenticates the identity contained in the cookie. Will use the `settings.userModel`, and `settings.fields` + * to find COOKIE data that is used to find a matching record in the `settings.userModel`. Will return false if + * there is no cookie data, either username or password is missing, of if the scope conditions have not been met. + * + * @param CakeRequest $request The unused request object + * @return mixed False on login failure. An array of User data on success. + * @throws CakeException + */ + public function getUser(CakeRequest $request) { + if (!isset($this->_Collection->Cookie) || !$this->_Collection->Cookie instanceof CookieComponent) { + throw new CakeException('CookieComponent is not loaded'); + } + + $this->_Collection->Cookie->type($this->settings['crypt']); + list(, $model) = pluginSplit($this->settings['userModel']); + + $data = $this->_Collection->Cookie->read($model); + if (empty($data)) { + return false; + } + + extract($this->settings['fields']); + if (empty($data[$username]) || empty($data[$password])) { + return false; + } + + $user = $this->_findUser($data[$username], $data[$password]); + if ($user) { + $this->_Collection->Session->write(AuthComponent::$sessionKey, $user); + return $user; + } + return false; + } + +/** + * Authenticate callback + * + * @param CakeRequest $request Request object + * @param CakeResponse $response Response object + * @return mixed + */ + public function authenticate(CakeRequest $request, CakeResponse $response) { + return $this->getUser($request); + } + +/** + * Logout feature + * + * @param array $user User object + * @return void + */ + public function logout($user) { + $this->_Collection->Cookie->destroy(); + } + +} diff --git a/Controller/Component/Auth/MultiColumnAuthenticate.php b/Controller/Component/Auth/MultiColumnAuthenticate.php index 73bca9927..15272fcc0 100644 --- a/Controller/Component/Auth/MultiColumnAuthenticate.php +++ b/Controller/Component/Auth/MultiColumnAuthenticate.php @@ -1,84 +1,84 @@ -Auth->authenticate = array( - * 'Authenticate.MultiColumn' => array( - * 'fields' => array( - * 'username' => 'username', - * 'password' => 'password' - * ), - * 'columns' => array('username', 'email'), - * 'userModel' => 'User', - * 'scope' => array('User.active' => 1) - * ) - * ) - * }}} - * - * @author Ceeram - * @copyright Ceeram - * @license MIT - * @link https://github.com/ceeram/Authenticate - */ -class MultiColumnAuthenticate extends FormAuthenticate { - -/** - * Settings for this object. - * - * - `fields` The fields to use to identify a user by. - * - 'columns' array of columns to check username form input against - * - `userModel` The model name of the User, defaults to User. - * - `scope` Additional conditions to use when looking up and authenticating users, - * i.e. `array('User.is_active' => 1).` - * - * @var array - */ - public $settings = array( - 'fields' => array( - 'username' => 'username', - 'password' => 'password' - ), - 'columns' => array(), - 'userModel' => 'User', - 'scope' => array() - ); - -/** - * Find a user record using the standard options. - * - * @param string $username The username/identifier. - * @param string $password The unhashed password. - * @return Mixed Either false on failure, or an array of user data. - */ - protected function _findUser($username, $password = null) { - $userModel = $this->settings['userModel']; - list($plugin, $model) = pluginSplit($userModel); - $fields = $this->settings['fields']; - $conditions = array($model . '.' . $fields['username'] => $username); - if ($this->settings['columns'] && is_array($this->settings['columns'])) { - $columns = array(); - foreach ($this->settings['columns'] as $column) { - $columns[] = array($model . '.' . $column => $username); - } - $conditions = array('OR' => $columns); - } - $conditions = array_merge($conditions, array($model . '.' . $fields['password'] => $this->_password($password))); - if (!empty($this->settings['scope'])) { - $conditions = array_merge($conditions, $this->settings['scope']); - } - $result = ClassRegistry::init($userModel)->find('first', array( - 'conditions' => $conditions, - 'recursive' => 0 - )); - if (empty($result) || empty($result[$model])) { - return false; - } - unset($result[$model][$fields['password']]); - return $result[$model]; - } - -} +Auth->authenticate = array( + * 'Authenticate.MultiColumn' => array( + * 'fields' => array( + * 'username' => 'username', + * 'password' => 'password' + * ), + * 'columns' => array('username', 'email'), + * 'userModel' => 'User', + * 'scope' => array('User.active' => 1) + * ) + * ) + * }}} + * + * @author Ceeram + * @copyright Ceeram + * @license MIT + * @link https://github.com/ceeram/Authenticate + */ +class MultiColumnAuthenticate extends FormAuthenticate { + +/** + * Settings for this object. + * + * - `fields` The fields to use to identify a user by. + * - 'columns' array of columns to check username form input against + * - `userModel` The model name of the User, defaults to User. + * - `scope` Additional conditions to use when looking up and authenticating users, + * i.e. `array('User.is_active' => 1).` + * + * @var array + */ + public $settings = [ + 'fields' => [ + 'username' => 'username', + 'password' => 'password' + ], + 'columns' => [], + 'userModel' => 'User', + 'scope' => [] + ]; + +/** + * Find a user record using the standard options. + * + * @param string $username The username/identifier. + * @param string $password The unhashed password. + * @return Mixed Either false on failure, or an array of user data. + */ + protected function _findUser($username, $password = null) { + $userModel = $this->settings['userModel']; + list($plugin, $model) = pluginSplit($userModel); + $fields = $this->settings['fields']; + $conditions = [$model . '.' . $fields['username'] => $username]; + if ($this->settings['columns'] && is_array($this->settings['columns'])) { + $columns = []; + foreach ($this->settings['columns'] as $column) { + $columns[] = [$model . '.' . $column => $username]; + } + $conditions = ['OR' => $columns]; + } + $conditions = array_merge($conditions, [$model . '.' . $fields['password'] => Security::hash($password, null, true)]); + if (!empty($this->settings['scope'])) { + $conditions = array_merge($conditions, $this->settings['scope']); + } + $result = ClassRegistry::init($userModel)->find('first', [ + 'conditions' => $conditions, + 'recursive' => 0 + ]); + if (empty($result) || empty($result[$model])) { + return false; + } + unset($result[$model][$fields['password']]); + return $result[$model]; + } + +} diff --git a/Controller/Component/Auth/TokenAuthenticate.php b/Controller/Component/Auth/TokenAuthenticate.php index eaadeaefa..4ba4cf633 100644 --- a/Controller/Component/Auth/TokenAuthenticate.php +++ b/Controller/Component/Auth/TokenAuthenticate.php @@ -1,140 +1,140 @@ -Auth->authenticate = array( - * 'Authenticate.Token' => array( - * 'fields' => array( - * 'username' => 'username', - * 'password' => 'password', - * 'token' => 'public_key', - * ), - * 'parameter' => '_token', - * 'header' => 'X-MyApiTokenHeader', - * 'userModel' => 'User', - * 'scope' => array('User.active' => 1) - * ) - * ) - * }}} - * - * @author Ceeram - * @copyright Ceeram - * @license MIT - * @link https://github.com/ceeram/Authenticate - */ -class TokenAuthenticate extends BaseAuthenticate { - -/** - * Settings for this object. - * - * - `fields` The fields to use to identify a user by. Make sure `'token'` has been added to the array - * - `parameter` The url parameter name of the token. - * - `header` The token header value. - * - `userModel` The model name of the User, defaults to User. - * - `scope` Additional conditions to use when looking up and authenticating users, - * i.e. `array('User.is_active' => 1).` - * - `recursive` The value of the recursive key passed to find(). Defaults to 0. - * - `contain` Extra models to contain and store in session. - * - * @var array - */ - public $settings = array( - 'fields' => array( - 'username' => 'username', - 'password' => 'password', - 'token' => 'token', - ), - 'parameter' => '_token', - 'header' => 'X-ApiToken', - 'userModel' => 'User', - 'scope' => array(), - 'recursive' => 0, - 'contain' => null, - ); - -/** - * Constructor - * - * @param ComponentCollection $collection The Component collection used on this request. - * @param array $settings Array of settings to use. - * @throws CakeException - */ - public function __construct(ComponentCollection $collection, $settings) { - parent::__construct($collection, $settings); - if (empty($this->settings['parameter']) && empty($this->settings['header'])) { - throw new CakeException(__d('users', 'You need to specify token parameter and/or header')); - } - } - -/** - * Authenticate user - * - * @param CakeRequest $request The request object - * @param CakeResponse $response response object. - * @return mixed. False on login failure. An array of User data on success. - */ - public function authenticate(CakeRequest $request, CakeResponse $response) { - $user = $this->getUser($request); - if (!$user) { - $response->statusCode(401); - $response->send(); - } - return $user; - } - -/** - * 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; - } - -/** - * Find a user record. - * - * @param string $username The token identifier. - * @param string $password Unused password. - * @return Mixed Either false on failure, or an array of user data. - */ - public function _findUser($username, $password = null) { - $userModel = $this->settings['userModel']; - list($plugin, $model) = pluginSplit($userModel); - $fields = $this->settings['fields']; - - $conditions = array( - $model . '.' . $fields['token'] => $username, - ); - if (!empty($this->settings['scope'])) { - $conditions = array_merge($conditions, $this->settings['scope']); - } - $result = ClassRegistry::init($userModel)->find('first', array( - 'conditions' => $conditions, - 'recursive' => (int)$this->settings['recursive'], - 'contain' => $this->settings['contain'], - )); - if (empty($result) || empty($result[$model])) { - return false; - } - $user = $result[$model]; - unset($user[$fields['password']]); - unset($result[$model]); - return array_merge($user, $result); - } - -} +Auth->authenticate = array( + * 'Authenticate.Token' => array( + * 'fields' => array( + * 'username' => 'username', + * 'password' => 'password', + * 'token' => 'public_key', + * ), + * 'parameter' => '_token', + * 'header' => 'X-MyApiTokenHeader', + * 'userModel' => 'User', + * 'scope' => array('User.active' => 1) + * ) + * ) + * }}} + * + * @author Ceeram + * @copyright Ceeram + * @license MIT + * @link https://github.com/ceeram/Authenticate + */ +class TokenAuthenticate extends BaseAuthenticate { + +/** + * Settings for this object. + * + * - `fields` The fields to use to identify a user by. Make sure `'token'` has been added to the array + * - `parameter` The url parameter name of the token. + * - `header` The token header value. + * - `userModel` The model name of the User, defaults to User. + * - `scope` Additional conditions to use when looking up and authenticating users, + * i.e. `array('User.is_active' => 1).` + * - `recursive` The value of the recursive key passed to find(). Defaults to 0. + * - `contain` Extra models to contain and store in session. + * + * @var array + */ + public $settings = [ + 'fields' => [ + 'username' => 'username', + 'password' => 'password', + 'token' => 'token', + ], + 'parameter' => '_token', + 'header' => 'X-ApiToken', + 'userModel' => 'User', + 'scope' => [], + 'recursive' => 0, + 'contain' => null, + ]; + +/** + * Constructor + * + * @param ComponentCollection $collection The Component collection used on this request. + * @param array $settings Array of settings to use. + * @throws CakeException + */ + public function __construct(ComponentCollection $collection, $settings) { + parent::__construct($collection, $settings); + if (empty($this->settings['parameter']) && empty($this->settings['header'])) { + throw new CakeException(__d('users', 'You need to specify token parameter and/or header')); + } + } + +/** + * Authenticate user + * + * @param CakeRequest $request The request object + * @param CakeResponse $response response object. + * @return mixed. False on login failure. An array of User data on success. + */ + public function authenticate(CakeRequest $request, CakeResponse $response) { + $user = $this->getUser($request); + if (!$user) { + $response->statusCode(401); + $response->send(); + } + return $user; + } + +/** + * 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; + } + +/** + * Find a user record. + * + * @param string $username The token identifier. + * @param string $password Unused password. + * @return Mixed Either false on failure, or an array of user data. + */ + protected function _findUser($username, $password = null) { + $userModel = $this->settings['userModel']; + list($plugin, $model) = pluginSplit($userModel); + $fields = $this->settings['fields']; + + $conditions = [ + $model . '.' . $fields['token'] => $username, + ]; + if (!empty($this->settings['scope'])) { + $conditions = array_merge($conditions, $this->settings['scope']); + } + $result = ClassRegistry::init($userModel)->find('first', [ + 'conditions' => $conditions, + 'recursive' => (int)$this->settings['recursive'], + 'contain' => $this->settings['contain'], + ]); + if (empty($result) || empty($result[$model])) { + return false; + } + $user = $result[$model]; + unset($user[$fields['password']]); + unset($result[$model]); + return array_merge($user, $result); + } + +} diff --git a/Controller/Component/RememberMeComponent.php b/Controller/Component/RememberMeComponent.php index fdd2a7dc1..fc16cdda3 100644 --- a/Controller/Component/RememberMeComponent.php +++ b/Controller/Component/RememberMeComponent.php @@ -1,239 +1,239 @@ - true, - 'userModel' => 'User', - 'cookieKey' => 'rememberMe', - 'cookieLifeTime' => '+1 year', - 'cookie' => array( - 'name' => 'User' - ), - 'fields' => array( - 'email', - 'username', - 'password' - ) - ); - -/** - * Constructor - * - * @param ComponentCollection $collection A ComponentCollection for this component - * @param array $settings Array of settings. - * @return RememberMeComponent - */ - public function __construct(ComponentCollection $collection, $settings = array()) { - parent::__construct($collection, $settings); - - $this->_checkAndSetCookieLifeTime(); - $this->settings = Hash::merge($this->_defaults, $settings); - $this->configureCookie($this->settings['cookie']); - } - -/** - * Check if the system is 32bit and uses DateTime() instead strtotime() to get - * an integer instead of a string that is passed on to CookieComponent::write() - * due to problems with strtotime() in CookieComponent::_expire(). See - * the link in this doc block. - * - * This method needs to be called in the constructor before the default config - * values are merged! - * - * @link https://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/3868-cookiecomponent_expires-fails-on-dates-set-far-in-the-future-on-32bit-systems - * @link http://stackoverflow.com/questions/3266077/php-strtotime-is-returning-false-for-a-future-date - * @return void - */ - protected function _checkAndSetCookieLifeTime() { - $lifeTime = $this->_defaults['cookieLifeTime']; - if (is_string($lifeTime) && strtotime($lifeTime) === false) { - $Date = new DateTime($lifeTime); - $this->_defaults['cookieLifeTime'] = $Date->format('U'); - } - } - -/** - * Initializes RememberMeComponent for use in the controller - * - * @param Controller $controller A reference to the instantiating controller object - * @return void - */ - public function initialize(Controller $controller) { - $this->request = $controller->request; - $this->Auth = $controller->Auth; - } - -/** - * startup - * - * @param Controller $controller - * @return void - */ - public function startup(Controller $controller) { - if ($this->settings['autoLogin'] == true && !$this->Auth->loggedIn()) { - $this->restoreLoginFromCookie(); - } - } - -/** - * Logs the user again in based on the cookie data - * - * @param boolean $checkLoginStatus - * @return boolean True on login success, false on failure - */ - public function restoreLoginFromCookie($checkLoginStatus = true) { - if ($checkLoginStatus && $this->Auth->loggedIn()) { - return true; - } - - if ($this->cookieIsSet()) { - extract($this->settings); - $cookie = $this->Cookie->read($cookieKey); - $request = $this->request->data; - - foreach ($fields as $field) { - if (!empty($cookie[$field])) { - $this->request->data[$userModel][$field] = $cookie[$field]; - } - } - - $result = $this->Auth->login(); - - if (!$result) { - $this->request->data = $request; - } - - return $result; - } - return false; - } - -/** - * Sets the cookie with the specified fields - * - * @param array Optional, login credentials array in the form of Model.field, if empty this->request[''] will be used - * @return boolean - */ - public function setCookie($data = array()) { - extract($this->settings); - - if (empty($data)) { - $data = $this->request->data; - if (empty($data)) { - $data = $this->Auth->user(); - } - } - - if (empty($data)) { - return false; - } - - $cookieData = array(); - - foreach ($fields as $field) { - if (isset($data[$userModel][$field]) && !empty($data[$userModel][$field])) { - $cookieData[$field] = $data[$userModel][$field]; - } - } - - $this->Cookie->write($cookieKey, $cookieData, true, $cookieLifeTime); - return true; - } - -/** - * Checks if the remember me cookie is set - * - * @return boolean - */ - public function cookieIsSet() { - extract($this->settings); - $cookie = $this->Cookie->read($cookieKey); - return (!empty($cookie)); - } - -/** - * Destroys the remember me cookie - * - * @return void - */ - public function destroyCookie() { - extract($this->settings); - if (isset($_COOKIE[$cookie['name']])) { - $this->Cookie->name = $cookie['name']; - $this->Cookie->destroy(); - } - } - -/** - * Configures the cookie component instance - * - * @param array $options - * @throws InvalidArgumentException Thrown if an invalid option key was passed - * @return void - */ - public function configureCookie($options = array()) { - $validProperties = array('domain', 'key', 'name', 'path', 'secure', 'time'); - $defaults = array( - 'time' => '1 month', - 'name' => 'User'); - - $options = array_merge($defaults, $options); - - foreach ($options as $key => $value) { - if (in_array($key, $validProperties)) { - $this->Cookie->{$key} = $value; - } else { - throw new InvalidArgumentException(__d('users', 'Invalid options %s', $key)); - } - } - } -} + true, + 'userModel' => 'User', + 'cookieKey' => 'rememberMe', + 'cookieLifeTime' => '+1 year', + 'cookie' => [ + 'name' => 'User' + ], + 'fields' => [ + 'email', + 'username', + 'password' + ] + ]; + +/** + * Constructor + * + * @param ComponentCollection $collection A ComponentCollection for this component + * @param array $settings Array of settings. + * @return RememberMeComponent + */ + public function __construct(ComponentCollection $collection, $settings = []) { + parent::__construct($collection, $settings); + + $this->_checkAndSetCookieLifeTime(); + $this->settings = Hash::merge($this->_defaults, $settings); + $this->configureCookie($this->settings['cookie']); + } + +/** + * Check if the system is 32bit and uses DateTime() instead strtotime() to get + * an integer instead of a string that is passed on to CookieComponent::write() + * due to problems with strtotime() in CookieComponent::_expire(). See + * the link in this doc block. + * + * This method needs to be called in the constructor before the default config + * values are merged! + * + * @link https://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/3868-cookiecomponent_expires-fails-on-dates-set-far-in-the-future-on-32bit-systems + * @link http://stackoverflow.com/questions/3266077/php-strtotime-is-returning-false-for-a-future-date + * @return void + */ + protected function _checkAndSetCookieLifeTime() { + $lifeTime = $this->_defaults['cookieLifeTime']; + if (is_string($lifeTime) && strtotime($lifeTime) === false) { + $Date = new DateTime($lifeTime); + $this->_defaults['cookieLifeTime'] = $Date->format('U'); + } + } + +/** + * Initializes RememberMeComponent for use in the controller + * + * @param Controller $controller A reference to the instantiating controller object + * @return void + */ + public function initialize(Controller $controller) { + $this->request = $controller->request; + $this->Auth = $controller->Auth; + } + +/** + * startup + * + * @param Controller $controller A reference to the instantiating controller object + * @return void + */ + public function startup(Controller $controller) { + if ($this->settings['autoLogin'] == true && !$this->Auth->user()) { + $this->restoreLoginFromCookie(); + } + } + +/** + * Logs the user again in based on the cookie data + * + * @param bool $checkLoginStatus Check login status if true + * @return bool True on login success, false on failure + */ + public function restoreLoginFromCookie($checkLoginStatus = true) { + if ($checkLoginStatus && $this->Auth->user()) { + return true; + } + + if ($this->cookieIsSet()) { + extract($this->settings); + $cookie = $this->Cookie->read($cookieKey); + $request = $this->request->data; + + foreach ($fields as $field) { + if (!empty($cookie[$field])) { + $this->request->data[$userModel][$field] = $cookie[$field]; + } + } + + $result = $this->Auth->login(); + + if (!$result) { + $this->request->data = $request; + } + + return $result; + } + return false; + } + +/** + * Sets the cookie with the specified fields + * + * @param array $data Optional, login credentials array in the form of Model.field, if empty this->request[''] will be used + * @return bool + */ + public function setCookie($data = []) { + extract($this->settings); + + if (empty($data)) { + $data = $this->request->data; + if (empty($data)) { + $data = $this->Auth->user(); + } + } + + if (empty($data)) { + return false; + } + + $cookieData = []; + + foreach ($fields as $field) { + if (isset($data[$userModel][$field]) && !empty($data[$userModel][$field])) { + $cookieData[$field] = $data[$userModel][$field]; + } + } + + $this->Cookie->write($cookieKey, $cookieData, true, $cookieLifeTime); + return true; + } + +/** + * Checks if the remember me cookie is set + * + * @return bool + */ + public function cookieIsSet() { + extract($this->settings); + $cookie = $this->Cookie->read($cookieKey); + return (!empty($cookie)); + } + +/** + * Destroys the remember me cookie + * + * @return void + */ + public function destroyCookie() { + extract($this->settings); + if (isset($_COOKIE[$cookie['name']])) { + $this->Cookie->name = $cookie['name']; + $this->Cookie->destroy(); + } + } + +/** + * Configures the cookie component instance + * + * @param array $options Options to configure + * @throws InvalidArgumentException Thrown if an invalid option key was passed + * @return void + */ + public function configureCookie($options = []) { + $validProperties = ['domain', 'key', 'name', 'path', 'secure', 'time']; + $defaults = [ + 'time' => '1 month', + 'name' => 'User']; + + $options = array_merge($defaults, $options); + + foreach ($options as $key => $value) { + if (in_array($key, $validProperties)) { + $this->Cookie->{$key} = $value; + } else { + throw new InvalidArgumentException(__d('users', 'Invalid options %s', $key)); + } + } + } +} diff --git a/Controller/UsersAppController.php b/Controller/UsersAppController.php index baec383d7..a3dd1c7f2 100644 --- a/Controller/UsersAppController.php +++ b/Controller/UsersAppController.php @@ -1,11 +1,11 @@ $plugin)); + throw new MissingPluginException(['plugin' => $plugin]); } return $result; } @@ -184,13 +184,13 @@ protected function _setDefaultEmail() { * @return void */ protected function _setupPagination() { - $this->Paginator->settings = array( + $this->Paginator->settings = [ 'limit' => 12, - 'conditions' => array( + 'conditions' => [ $this->modelClass . '.active' => 1, $this->modelClass . '.email_verified' => 1 - ) - ); + ] + ]; } /** @@ -202,12 +202,12 @@ protected function _setupPagination() { * @return void */ protected function _setupAdminPagination() { - $this->Paginator->settings[$this->modelClass] = array( + $this->Paginator->settings[$this->modelClass] = [ 'limit' => 20, - 'order' => array( + 'order' => [ $this->modelClass . '.created' => 'desc' - ), - ); + ], + ]; } /** @@ -230,22 +230,22 @@ protected function _setupAuth() { $this->Components->disable('Auth'); } - $this->Auth->authenticate = array( - 'Form' => array( - 'fields' => array( + $this->Auth->authenticate = [ + 'Form' => [ + 'fields' => [ 'username' => 'email', - 'password' => 'password'), + 'password' => 'password'], 'userModel' => $this->_pluginDot() . $this->modelClass, - 'scope' => array( + 'scope' => [ $this->modelClass . '.active' => 1, $this->modelClass . '.email_verified' => 1 - ) - ) - ); + ] + ] + ]; $this->Auth->loginRedirect = '/'; - $this->Auth->logoutRedirect = array('plugin' => Inflector::underscore($this->plugin), 'controller' => 'users', 'action' => 'login'); - $this->Auth->loginAction = array('admin' => false, 'plugin' => Inflector::underscore($this->plugin), 'controller' => 'users', 'action' => 'login'); + $this->Auth->logoutRedirect = ['plugin' => Inflector::underscore($this->plugin), 'controller' => 'users', 'action' => 'login']; + $this->Auth->loginAction = ['admin' => false, 'plugin' => Inflector::underscore($this->plugin), 'controller' => 'users', 'action' => 'login']; } /** @@ -277,7 +277,7 @@ public function view($slug = null) { try { $this->set('user', $this->{$this->modelClass}->view($slug)); } catch (Exception $e) { - $this->Session->setFlash($e->getMessage()); + $this->Flash->set($e->getMessage()); $this->redirect('/'); } } @@ -311,7 +311,7 @@ public function admin_index() { if ($this->{$this->modelClass}->Behaviors->loaded('Searchable')) { $parsedConditions = $this->{$this->modelClass}->parseCriteria($this->passedArgs); } else { - $parsedConditions = array(); + $parsedConditions = []; } $this->_setupAdminPagination(); @@ -329,8 +329,8 @@ public function admin_view($id = null) { try { $user = $this->{$this->modelClass}->view($id, 'id'); } catch (NotFoundException $e) { - $this->Session->setFlash(__d('users', 'Invalid User.')); - $this->redirect(array('action' => 'index')); + $this->Flash->set(__d('users', 'Invalid User.')); + $this->redirect(['action' => 'index']); } $this->set('user', $user); @@ -347,8 +347,8 @@ public function admin_add() { $this->request->data[$this->modelClass]['email_verified'] = true; if ($this->{$this->modelClass}->add($this->request->data)) { - $this->Session->setFlash(__d('users', 'The User has been saved')); - $this->redirect(array('action' => 'index')); + $this->Flash->set(__d('users', 'The User has been saved')); + $this->redirect(['action' => 'index']); } } $this->set('roles', Configure::read('Users.roles')); @@ -357,22 +357,22 @@ public function admin_add() { /** * Admin edit * - * @param null $userId + * @param mixed $userId User id * @return void */ public function admin_edit($userId = null) { try { $result = $this->{$this->modelClass}->edit($userId, $this->request->data); if ($result === true) { - $this->Session->setFlash(__d('users', 'User saved')); - $this->redirect(array('action' => 'index')); + $this->Flash->set(__d('users', 'User saved')); + $this->redirect(['action' => 'index']); } else { unset($result[$this->modelClass]['password']); $this->request->data = $result; } } catch (OutOfBoundsException $e) { - $this->Session->setFlash($e->getMessage()); - $this->redirect(array('action' => 'index')); + $this->Flash->set($e->getMessage()); + $this->redirect(['action' => 'index']); } if (empty($this->request->data)) { @@ -390,12 +390,12 @@ public function admin_edit($userId = null) { */ public function admin_delete($userId = null) { if ($this->{$this->modelClass}->delete($userId)) { - $this->Session->setFlash(__d('users', 'User deleted')); + $this->Flash->set(__d('users', 'User deleted')); } else { - $this->Session->setFlash(__d('users', 'Invalid User')); + $this->Flash->set(__d('users', 'Invalid User')); } - $this->redirect(array('action' => 'index')); + $this->redirect(['action' => 'index']); } /** @@ -414,7 +414,7 @@ public function admin_search() { */ public function add() { if ($this->Auth->user()) { - $this->Session->setFlash(__d('users', 'You are already registered and logged in!')); + $this->Flash->set(__d('users', 'You are already registered and logged in!')); $this->redirect('/'); } @@ -424,22 +424,22 @@ public function add() { $Event = new CakeEvent( 'Users.Controller.Users.afterRegistration', $this, - array( + [ 'data' => $this->request->data, - ) + ] ); $this->getEventManager()->dispatch($Event); if ($Event->isStopped()) { - $this->redirect(array('action' => 'login')); + $this->redirect(['action' => 'login']); } $this->_sendVerificationEmail($this->{$this->modelClass}->data); - $this->Session->setFlash(__d('users', 'Your account has been created. You should receive an e-mail shortly to authenticate your account. Once validated you will be able to login.')); - $this->redirect(array('action' => 'login')); + $this->Flash->set(__d('users', 'Your account has been created. You should receive an e-mail shortly to authenticate your account. Once validated you will be able to login.')); + $this->redirect(['action' => 'login']); } else { unset($this->request->data[$this->modelClass]['password']); unset($this->request->data[$this->modelClass]['temppassword']); - $this->Session->setFlash(__d('users', 'Your account could not be created. Please, try again.'), 'default', array('class' => 'message warning')); + $this->Flash->set(__d('users', 'Your account could not be created. Please, try again.'), ['element' => 'default', 'params' => ['class' => 'message warning']]); } } } @@ -453,9 +453,9 @@ public function login() { $Event = new CakeEvent( 'Users.Controller.Users.beforeLogin', $this, - array( + [ 'data' => $this->request->data, - ) + ] ); $this->getEventManager()->dispatch($Event); @@ -469,10 +469,10 @@ public function login() { $Event = new CakeEvent( 'Users.Controller.Users.afterLogin', $this, - array( + [ 'data' => $this->request->data, 'isFirstLogin' => !$this->Auth->user('last_login') - ) + ] ); $this->getEventManager()->dispatch($Event); @@ -483,7 +483,7 @@ public function login() { if ($this->here == $this->Auth->loginRedirect) { $this->Auth->loginRedirect = '/'; } - $this->Session->setFlash(sprintf(__d('users', '%s you have successfully logged in'), $this->Auth->user($this->{$this->modelClass}->displayField))); + $this->Flash->set(sprintf(__d('users', '%s you have successfully logged in'), $this->Auth->user($this->{$this->modelClass}->displayField))); if (!empty($this->request->data)) { $data = $this->request->data[$this->modelClass]; if (empty($this->request->data[$this->modelClass]['remember_me'])) { @@ -546,18 +546,18 @@ public function search() { } $this->request->data[$this->modelClass]['search'] = $searchTerm; - $this->Paginator->settings = array( + $this->Paginator->settings = [ 'search', 'limit' => 12, 'by' => $by, 'search' => $searchTerm, - 'conditions' => array( - 'AND' => array( + 'conditions' => [ + 'AND' => [ $this->modelClass . '.active' => 1, $this->modelClass . '.email_verified' => 1 - ) - ) - ); + ] + ] + ]; $this->set('users', $this->Paginator->paginate($this->modelClass)); $this->set('searchTerm', $searchTerm); @@ -572,7 +572,7 @@ public function logout() { $user = $this->Auth->user(); $this->Session->destroy(); $this->RememberMe->destroyCookie(); - $this->Session->setFlash(sprintf(__d('users', '%s you have successfully logged out'), $user[$this->{$this->modelClass}->displayField])); + $this->Flash->set(sprintf(__d('users', '%s you have successfully logged out'), $user[$this->{$this->modelClass}->displayField])); $this->redirect($this->Auth->logout()); } @@ -586,13 +586,13 @@ public function resend_verification() { try { if ($this->{$this->modelClass}->checkEmailVerification($this->request->data)) { $this->_sendVerificationEmail($this->{$this->modelClass}->data); - $this->Session->setFlash(__d('users', 'The email was resent. Please check your inbox.')); + $this->Flash->set(__d('users', 'The email was resent. Please check your inbox.')); $this->redirect('login'); } else { - $this->Session->setFlash(__d('users', 'The email could not be sent. Please check errors.')); + $this->Flash->set(__d('users', 'The email could not be sent. Please check errors.')); } } catch (Exception $e) { - $this->Session->setFlash($e->getMessage()); + $this->Flash->set($e->getMessage()); } } } @@ -612,10 +612,10 @@ public function verify($type = 'email', $token = null) { try { $this->{$this->modelClass}->verifyEmail($token); - $this->Session->setFlash(__d('users', 'Your e-mail has been validated!')); - return $this->redirect(array('action' => 'login')); + $this->Flash->set(__d('users', 'Your e-mail has been validated!')); + return $this->redirect(['action' => 'login']); } catch (RuntimeException $e) { - $this->Session->setFlash($e->getMessage()); + $this->Flash->set($e->getMessage()); return $this->redirect('/'); } } @@ -635,24 +635,24 @@ public function request_new_password($token = null) { $data = $this->{$this->modelClass}->verifyEmail($token); if (!$data) { - $this->Session->setFlash(__d('users', 'The url you accessed is not longer valid')); + $this->Flash->set(__d('users', 'The url you accessed is not longer valid')); return $this->redirect('/'); } - if ($this->{$this->modelClass}->save($data, array('validate' => false))) { + if ($this->{$this->modelClass}->save($data, ['validate' => false])) { $this->_sendNewPassword($data); - $this->Session->setFlash(__d('users', 'Your password was sent to your registered email account')); - $this->redirect(array('action' => 'login')); + $this->Flash->set(__d('users', 'Your password was sent to your registered email account')); + $this->redirect(['action' => 'login']); } - $this->Session->setFlash(__d('users', 'There was an error verifying your account. Please check the email you were sent, and retry the verification link.')); + $this->Flash->set(__d('users', 'There was an error verifying your account. Please check the email you were sent, and retry the verification link.')); $this->redirect('/'); } /** * Sends the password reset email * - * @param array + * @param array $userData User data * @return void */ protected function _sendNewPassword($userData) { @@ -663,9 +663,9 @@ protected function _sendNewPassword($userData) { ->return(Configure::read('App.defaultEmail')) ->subject(env('HTTP_HOST') . ' ' . __d('users', 'Password Reset')) ->template($this->_pluginDot() . 'new_password') - ->viewVars(array( + ->viewVars([ 'model' => $this->modelClass, - 'userData' => $userData)) + 'userData' => $userData]) ->send(); } @@ -678,7 +678,7 @@ public function change_password() { if ($this->request->is('post')) { $this->request->data[$this->modelClass]['id'] = $this->Auth->user('id'); if ($this->{$this->modelClass}->changePassword($this->request->data)) { - $this->Session->setFlash(__d('users', 'Password changed.')); + $this->Flash->set(__d('users', 'Password changed.')); // we don't want to keep the cookie with the old password around $this->RememberMe->destroyCookie(); $this->redirect('/'); @@ -712,11 +712,11 @@ public function reset_password($token = null, $user = null) { /** * Sets a list of languages to the view which can be used in selects * - * @deprecated No fallback provided, use the Utils plugin in your app directly * @param string $viewVar View variable name, default is languages * @throws MissingPluginException * @return void * @link https://github.com/CakeDC/utils + * @deprecated No fallback provided, use the Utils plugin in your app directly */ protected function _setLanguages($viewVar = 'languages') { $this->_pluginLoaded('Utils'); @@ -732,18 +732,18 @@ protected function _setLanguages($viewVar = 'languages') { * controller can override this method to change the varification mail sending * in any possible way. * - * @param string $to Receiver email address + * @param string $userData User data * @param array $options EmailComponent options * @return void */ - protected function _sendVerificationEmail($userData, $options = array()) { - $defaults = array( + protected function _sendVerificationEmail($userData, $options = []) { + $defaults = [ 'from' => Configure::read('App.defaultEmail'), 'subject' => __d('users', 'Account verification'), 'template' => $this->_pluginDot() . 'account_verification', 'layout' => 'default', 'emailFormat' => CakeEmail::MESSAGE_TEXT - ); + ]; $options = array_merge($defaults, $options); @@ -753,10 +753,10 @@ protected function _sendVerificationEmail($userData, $options = array()) { ->emailFormat($options['emailFormat']) ->subject($options['subject']) ->template($options['template'], $options['layout']) - ->viewVars(array( + ->viewVars([ 'model' => $this->modelClass, 'user' => $userData - )) + ]) ->send(); } @@ -764,18 +764,18 @@ protected function _sendVerificationEmail($userData, $options = array()) { * Checks if the email is in the system and authenticated, if yes create the token * save it and send the user an email * - * @param boolean $admin Admin boolean + * @param bool $admin Admin boolean * @param array $options Options * @return void */ - protected function _sendPasswordReset($admin = null, $options = array()) { - $defaults = array( + protected function _sendPasswordReset($admin = null, $options = []) { + $defaults = [ 'from' => Configure::read('App.defaultEmail'), 'subject' => __d('users', 'Password Reset'), 'template' => $this->_pluginDot() . 'password_reset_request', 'emailFormat' => CakeEmail::MESSAGE_TEXT, 'layout' => 'default' - ); + ]; $options = array_merge($defaults, $options); @@ -790,23 +790,23 @@ protected function _sendPasswordReset($admin = null, $options = array()) { ->emailFormat($options['emailFormat']) ->subject($options['subject']) ->template($options['template'], $options['layout']) - ->viewVars(array( + ->viewVars([ 'model' => $this->modelClass, 'user' => $this->{$this->modelClass}->data, - 'token' => $this->{$this->modelClass}->data[$this->modelClass]['password_token'])) + 'token' => $this->{$this->modelClass}->data[$this->modelClass]['password_token']]) ->send(); if ($admin) { - $this->Session->setFlash(sprintf( + $this->Flash->set(sprintf( __d('users', '%s has been sent an email with instruction to reset their password.'), $user[$this->modelClass]['email'])); - $this->redirect(array('action' => 'index', 'admin' => true)); + $this->redirect(['action' => 'index', 'admin' => true]); } else { - $this->Session->setFlash(__d('users', 'You should receive an email with further instructions shortly')); - $this->redirect(array('action' => 'login')); + $this->Flash->set(__d('users', 'You should receive an email with further instructions shortly')); + $this->redirect(['action' => 'login']); } } else { - $this->Session->setFlash(__d('users', 'No user was found with that email.')); + $this->Flash->set(__d('users', 'No user was found with that email.')); $this->redirect($this->referer('/')); } } @@ -816,12 +816,12 @@ protected function _sendPasswordReset($admin = null, $options = array()) { /** * Sets the cookie to remember the user * - * @param array RememberMe (Cookie) component properties as array, like array('domain' => 'yourdomain.com') - * @param string Cookie data keyname for the userdata, its default is "User". This is set to User and NOT using the model alias to make sure it works with different apps with different user models across different (sub)domains. + * @param array $options RememberMe (Cookie) component properties as array, like array('domain' => 'yourdomain.com') + * @param string $cookieKey Cookie data keyname for the userdata, its default is "User". This is set to User and NOT using the model alias to make sure it works with different apps with different user models across different (sub)domains. * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html */ - protected function _setCookie($options = array(), $cookieKey = 'rememberMe') { + protected function _setCookie($options = [], $cookieKey = 'rememberMe') { $this->RememberMe->settings['cookieKey'] = $cookieKey; $this->RememberMe->configureCookie($options); $this->RememberMe->setCookie(); @@ -836,17 +836,17 @@ protected function _setCookie($options = array(), $cookieKey = 'rememberMe') { protected function _resetPassword($token) { $user = $this->{$this->modelClass}->checkPasswordToken($token); if (empty($user)) { - $this->Session->setFlash(__d('users', 'Invalid password reset token, try again.')); - $this->redirect(array('action' => 'reset_password')); + $this->Flash->set(__d('users', 'Invalid password reset token, try again.')); + $this->redirect(['action' => 'reset_password']); return; } if (!empty($this->request->data) && $this->{$this->modelClass}->resetPassword(Hash::merge($user, $this->request->data))) { if ($this->RememberMe->cookieIsSet()) { - $this->Session->setFlash(__d('users', 'Password changed.')); + $this->Flash->set(__d('users', 'Password changed.')); $this->_setCookie(); } else { - $this->Session->setFlash(__d('users', 'Password changed, you can now login with your new password.')); + $this->Flash->set(__d('users', 'Password changed, you can now login with your new password.')); $this->redirect($this->Auth->loginAction); } } @@ -869,8 +869,8 @@ protected function _getMailInstance() { * * This is called to see if a user (when logged in) is able to access an action * - * @param array $user - * @return boolean True if allowed + * @param array $user User to check + * @return bool True if allowed * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#using-controllerauthorize */ public function isAuthorized($user = null) { diff --git a/Locale/spa/LC_MESSAGES/users.po b/Locale/spa/LC_MESSAGES/users.po index 40898c3d6..be5fb5abf 100644 --- a/Locale/spa/LC_MESSAGES/users.po +++ b/Locale/spa/LC_MESSAGES/users.po @@ -239,7 +239,7 @@ msgstr "Público" #: View/Elements/Users/sidebar.ctp:4 #: View/Users/login.ctp:13 msgid "Login" -msgstr "Nombre de Usuario" +msgstr "Iniciar sesión" #: View/Elements/Users/sidebar.ctp:6 msgid "Register an account" diff --git a/Model/User.php b/Model/User.php index a73ab8c56..afa22fc44 100644 --- a/Model/User.php +++ b/Model/User.php @@ -1,11 +1,11 @@ true - ); + ]; /** * All search fields need to be configured in the Model::filterArgs array. @@ -44,10 +44,10 @@ class User extends UsersAppModel { * @var array * @link https://github.com/CakeDC/search */ - public $filterArgs = array( - 'username' => array('type' => 'like'), - 'email' => array('type' => 'value') - ); + public $filterArgs = [ + 'username' => ['type' => 'like'], + 'email' => ['type' => 'value'] + ]; /** * Displayfield @@ -59,7 +59,7 @@ class User extends UsersAppModel { /** * Time the email verification token is valid in seconds * - * @var integer + * @var int */ public $emailTokenExpirationTime = 86400; @@ -74,7 +74,7 @@ class User extends UsersAppModel { * Enable / Disable callbacks parameter. * Can be use when subclassing to ensure callbacks run. * - * @var boolean + * @var bool */ public $enableCallbacks = false; @@ -83,53 +83,53 @@ class User extends UsersAppModel { * * @var array */ - public $validate = array( - 'username' => array( - 'required' => array( - 'rule' => array('custom', '/.+/'), + public $validate = [ + 'username' => [ + 'required' => [ + 'rule' => ['custom', '/.+/'], 'required' => true, 'allowEmpty' => false, 'message' => 'Please enter a username.' - ), - 'alpha' => array( - 'rule' => array('alphaNumeric'), + ], + 'alpha' => [ + 'rule' => ['alphaNumeric'], 'message' => 'The username must be alphanumeric.' - ), - 'unique_username' => array( - 'rule' => array('isUnique', 'username'), + ], + 'unique_username' => [ + 'rule' => ['isUnique', 'username'], 'message' => 'This username is already in use.' - ), - 'username_min' => array( - 'rule' => array('minLength', '3'), + ], + 'username_min' => [ + 'rule' => ['minLength', '3'], 'message' => 'The username must have at least 3 characters.' - ) - ), - 'email' => array( - 'isValid' => array( + ] + ], + 'email' => [ + 'isValid' => [ 'rule' => 'email', 'required' => true, 'message' => 'Please enter a valid email address.' - ), - 'isUnique' => array( - 'rule' => array('isUnique', 'email'), + ], + 'isUnique' => [ + 'rule' => ['isUnique', 'email'], 'message' => 'This email is already in use.' - ) - ), - 'password' => array( - 'too_short' => array( - 'rule' => array('minLength', '6'), + ] + ], + 'password' => [ + 'too_short' => [ + 'rule' => ['minLength', '6'], 'message' => 'The password must have at least 6 characters.' - ), - ), - 'temppassword' => array( + ], + ], + 'temppassword' => [ 'rule' => 'confirmPassword', 'message' => 'The passwords are not equal, please try again.' - ), - 'tos' => array( - 'rule' => array('custom','[1]'), + ], + 'tos' => [ + 'rule' => ['custom', '[1]'], 'message' => 'You must agree to the terms of use.' - ) - ); + ] + ]; /** * Constructor @@ -159,10 +159,10 @@ protected function _setupBehaviors() { } if (CakePlugin::loaded('Utils') && class_exists('SluggableBehavior') && Configure::read('Users.disableSlugs') !== true) { - $this->actsAs['Utils.Sluggable'] = array( + $this->actsAs['Utils.Sluggable'] = [ 'label' => 'username', 'method' => 'multibyteSlug' - ); + ]; } } @@ -172,14 +172,14 @@ protected function _setupBehaviors() { * @return void */ protected function _setupValidation() { - $this->validatePasswordChange = array( + $this->validatePasswordChange = [ 'new_password' => $this->validate['password'], - 'confirm_password' => array( - 'required' => array('rule' => array('compareFields', 'new_password', 'confirm_password'), 'required' => true, 'message' => __d('users', 'The passwords are not equal.'))), - 'old_password' => array( - 'to_short' => array('rule' => 'validateOldPassword', 'required' => true, 'message' => __d('users', 'Invalid password.')) - ) - ); + 'confirm_password' => [ + 'required' => ['rule' => ['compareFields', 'new_password', 'confirm_password'], 'required' => true, 'message' => __d('users', 'The passwords are not equal.')]], + 'old_password' => [ + 'to_short' => ['rule' => 'validateOldPassword', 'required' => true, 'message' => __d('users', 'Invalid password.')] + ] + ]; } /** @@ -190,7 +190,7 @@ protected function _setupValidation() { * * @param string $string String to hash * @param string $type Method to use (sha1/sha256/md5) - * @param boolean $salt If true, automatically appends the application's salt + * @param bool $salt If true, automatically appends the application's salt * value to $string (Security.salt) * @return string Hash */ @@ -202,7 +202,7 @@ public function hash($string, $type = null, $salt = false) { * Custom validation method to ensure that the two entered passwords match * * @param string $password Password - * @return boolean Success + * @return bool Success */ public function confirmPassword($password = null) { if ((isset($this->data[$this->alias]['password']) && isset($password['temppassword'])) @@ -217,7 +217,7 @@ public function confirmPassword($password = null) { * Compares the email confirmation * * @param array $email Email data - * @return boolean + * @return bool */ public function confirmEmail($email = null) { if ((isset($this->data[$this->alias]['email']) && isset($email['confirm_email'])) @@ -231,18 +231,18 @@ public function confirmEmail($email = null) { /** * Checks the token for email verification * - * @param string $token + * @param string $token Token to check * @return array */ public function checkEmailVerificationToken($token = null) { - $result = $this->find('first', array( - 'contain' => array(), - 'conditions' => array( + $result = $this->find('first', [ + 'contain' => [], + 'conditions' => [ $this->alias . '.email_verified' => 0, - $this->alias . '.email_token' => $token), - 'fields' => array( - 'id', 'email', 'email_token_expires', 'role') - ) + $this->alias . '.email_token' => $token], + 'fields' => [ + 'id', 'email', 'email_token_expires', 'role'] + ] ); if (empty($result)) { @@ -276,10 +276,10 @@ public function verifyEmail($token = null) { $user[$this->alias]['email_token'] = null; $user[$this->alias]['email_token_expires'] = null; - $user = $this->save($user, array( + $user = $this->save($user, [ 'validate' => false, 'callbacks' => $this->enableCallbacks - )); + ]); $this->data = $user; return $user; } @@ -289,14 +289,19 @@ public function verifyEmail($token = null) { * * @param string $userId User id * @param string $field Default is "last_action", changing it allows you to use this method also for "last_login" for example - * @return boolean True on success + * @return bool True on success + * @throws Exception */ public function updateLastActivity($userId = null, $field = 'last_action') { if (!empty($userId)) { $this->id = $userId; } if ($this->exists()) { - return $this->saveField($field, date('Y-m-d H:i:s', time())); + $this->create(false); + return $this->save( + [$this->alias => [$this->primaryKey => $userId, $field => date('Y-m-d H:i:s', time())]], + ['validate' => false, 'fieldList' => [$field]] + ); } return false; } @@ -307,12 +312,12 @@ public function updateLastActivity($userId = null, $field = 'last_action') { * @param array $postData post data from controller * @return mixed False or user data as array on success */ - public function passwordReset($postData = array()) { - $user = $this->find('first', array( - 'contain' => array(), - 'conditions' => array( + public function passwordReset($postData = []) { + $user = $this->find('first', [ + 'contain' => [], + 'conditions' => [ $this->alias . '.active' => 1, - $this->alias . '.email' => $postData[$this->alias]['email']))); + $this->alias . '.email' => $postData[$this->alias]['email']]]); if (!empty($user) && $user[$this->alias]['email_verified'] == 1) { $sixtyMins = time() + 43000; @@ -338,12 +343,12 @@ public function passwordReset($postData = array()) { * @return mixed False or user data as array */ public function checkPasswordToken($token = null) { - $user = $this->find('first', array( - 'contain' => array(), - 'conditions' => array( + $user = $this->find('first', [ + 'contain' => [], + 'conditions' => [ $this->alias . '.active' => 1, $this->alias . '.password_token' => $token, - $this->alias . '.email_token_expires >=' => date('Y-m-d H:i:s')))); + $this->alias . '.email_token_expires >=' => date('Y-m-d H:i:s')]]); if (empty($user)) { return false; } @@ -356,24 +361,24 @@ public function checkPasswordToken($token = null) { * @return array Set of rules required for the User::resetPassword() method */ public function setUpResetPasswordValidationRules() { - return array( + return [ 'new_password' => $this->validate['password'], - 'confirm_password' => array( - 'required' => array( - 'rule' => array('compareFields', 'new_password', 'confirm_password'), + 'confirm_password' => [ + 'required' => [ + 'rule' => ['compareFields', 'new_password', 'confirm_password'], 'message' => __d('users', 'The passwords are not equal.') - ) - ) - ); + ] + ] + ]; } /** * Resets the password * * @param array $postData Post data from controller - * @return boolean True on success + * @return bool True on success */ - public function resetPassword($postData = array()) { + public function resetPassword($postData = []) { $result = false; $tmp = $this->validate; @@ -383,9 +388,9 @@ public function resetPassword($postData = array()) { if ($this->validates()) { $this->data[$this->alias]['password'] = $this->hash($this->data[$this->alias]['new_password'], null, true); $this->data[$this->alias]['password_token'] = null; - $result = $this->save($this->data, array( + $result = $this->save($this->data, [ 'validate' => false, - 'callbacks' => $this->enableCallbacks) + 'callbacks' => $this->enableCallbacks] ); } @@ -397,17 +402,17 @@ public function resetPassword($postData = array()) { * Changes the password for a user * * @param array $postData Post data from controller - * @return boolean True on success + * @return bool True on success */ - public function changePassword($postData = array()) { + public function changePassword($postData = []) { $this->validate = $this->validatePasswordChange; $this->set($postData); if ($this->validates()) { $this->data[$this->alias]['password'] = $this->hash($this->data[$this->alias]['new_password'], null, true); - $this->save($postData, array( + $this->save($postData, [ 'validate' => false, - 'callbacks' => $this->enableCallbacks)); + 'callbacks' => $this->enableCallbacks]); return true; } return false; @@ -416,9 +421,9 @@ public function changePassword($postData = array()) { /** * Validation method to check the old password * - * @param array $password + * @param array $password Password to validate * @throws OutOfBoundsException - * @return boolean True on success + * @return bool True on success */ public function validateOldPassword($password) { if (!isset($this->data[$this->alias]['id']) || empty($this->data[$this->alias]['id'])) { @@ -427,7 +432,7 @@ public function validateOldPassword($password) { } } - $currentPassword = $this->field('password', array($this->alias . '.id' => $this->data[$this->alias]['id'])); + $currentPassword = $this->field('password', [$this->alias . '.id' => $this->data[$this->alias]['id']]); return $currentPassword === $this->hash($password['old_password'], null, true); } @@ -436,7 +441,7 @@ public function validateOldPassword($password) { * * @param mixed $field1 Array or string, if array the first key is used as fieldname * @param string $field2 Second fieldname - * @return boolean True on success + * @return bool True on success */ public function compareFields($field1, $field2) { if (is_array($field1)) { @@ -453,20 +458,20 @@ public function compareFields($field1, $field2) { /** * Returns all data about a user * - * @param string|integer $slug user slug or the uuid of a user - * @param string $field + * @param string|int $slug user slug or the uuid of a user + * @param string $field Field to find by * @throws NotFoundException * @return array */ public function view($slug = null, $field = 'slug') { - $user = $this->find('first', array( - 'contain' => array(), - 'conditions' => array( - 'OR' => array( + $user = $this->find('first', [ + 'contain' => [], + 'conditions' => [ + 'OR' => [ $this->alias . '.' . $field => $slug, - $this->alias . '.' . $this->primaryKey => $slug), + $this->alias . '.' . $this->primaryKey => $slug], $this->alias . '.active' => 1, - $this->alias . '.email_verified' => 1))); + $this->alias . '.email_verified' => 1]]); if (empty($user)) { throw new NotFoundException(__d('users', 'The user does not exist.')); @@ -484,26 +489,26 @@ public function view($slug = null, $field = 'slug') { * * Override it as needed, to add additional models to contain for example * - * @param string $email + * @param string $email Email to find * @return array */ public function findByEmail($email = null) { - return $this->find('first', array( - 'contain' => array(), - 'conditions' => array( + return $this->find('first', [ + 'contain' => [], + 'conditions' => [ $this->alias . '.email' => $email, - ) - )); + ] + ]); } /** * Checks if an email is already verified and if not renews the expiration time * * @param array $postData the post data from the request - * @param boolean $renew + * @param bool $renew Renew token if true * @return bool True if the email was not already verified */ - public function checkEmailVerification($postData = array(), $renew = true) { + public function checkEmailVerification($postData = [], $renew = true) { $user = $this->findByEmail($postData[$this->alias]['email']); if (empty($user)) { @@ -519,10 +524,10 @@ public function checkEmailVerification($postData = array(), $renew = true) { if ($user[$this->alias]['email_verified'] == 0) { if ($renew === true) { $user[$this->alias]['email_token_expires'] = $this->emailTokenExpirationTime(); - $this->save($user, array( + $this->save($user, [ 'validate' => false, 'callbacks' => $this->enableCallbacks, - )); + ]); } $this->data = $user; return true; @@ -538,17 +543,18 @@ public function checkEmailVerification($postData = array(), $renew = true) { * - bool returnData : Default is true, if false the method returns true/false the data is always available through $this->User->data * * @param array $postData Post data from controller - * @param mixed should be array now but can be boolean for emailVerification because of backward compatibility + * @param mixed $options should be array now but can be bool for emailVerification because of backward compatibility * @return mixed + * @throws Exception */ - public function register($postData = array(), $options = array()) { + public function register($postData = [], $options = []) { $Event = new CakeEvent( 'Users.Model.User.beforeRegister', $this, - array( + [ 'data' => $postData, 'options' => $options - ) + ] ); $this->getEventManager()->dispatch($Event); @@ -557,13 +563,13 @@ public function register($postData = array(), $options = array()) { } if (is_bool($options)) { - $options = array('emailVerification' => $options); + $options = ['emailVerification' => $options]; } - $defaults = array( + $defaults = [ 'emailVerification' => true, 'removeExpiredRegistrations' => true, - 'returnData' => true); + 'returnData' => true]; extract(array_merge($defaults, $options)); $postData = $this->_beforeRegistration($postData, $emailVerification); @@ -582,10 +588,10 @@ public function register($postData = array(), $options = array()) { $Event = new CakeEvent( 'Users.Model.User.afterRegister', $this, - array( + [ 'data' => $this->data, 'options' => $options - ) + ] ); $this->getEventManager()->dispatch($Event); @@ -608,7 +614,7 @@ public function register($postData = array(), $options = array()) { * @param array $postData Post data from controller * @return mixed False or user data array on success */ - public function resendVerification($postData = array()) { + public function resendVerification($postData = []) { if (!isset($postData[$this->alias]['email']) || empty($postData[$this->alias]['email'])) { $this->invalidate('email', __d('users', 'Please enter your email address.')); return false; @@ -655,9 +661,9 @@ public function emailTokenExpirationTime() { public function generatePassword($length = 10) { srand((double)microtime() * 1000000); $password = ''; - $vowels = array("a", "e", "i", "o", "u"); - $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr", - "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl"); + $vowels = ["a", "e", "i", "o", "u"]; + $cons = ["b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr", + "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl"]; for ($i = 0; $i < $length; $i++) { $password .= $cons[mt_rand(0, 31)] . $vowels[mt_rand(0, 4)]; } @@ -688,11 +694,11 @@ public function generateToken($length = 10) { /** * Optional data manipulation before the registration record is saved * - * @param array post data array - * @param boolean Use email generation, create token, default true + * @param array $postData post data array + * @param bool $useEmailVerification Use email generation, create token, default true * @return array */ - protected function _beforeRegistration($postData = array(), $useEmailVerification = true) { + protected function _beforeRegistration($postData = [], $useEmailVerification = true) { if ($useEmailVerification == true) { $postData[$this->alias]['email_token'] = $this->generateToken(); $postData[$this->alias]['email_token_expires'] = date('Y-m-d H:i:s', time() + 86400); @@ -719,14 +725,14 @@ protected function _beforeRegistration($postData = array(), $useEmailVerificatio * @return array * @link https://github.com/CakeDC/search */ - protected function _findSearch($state, $query, $results = array()) { + protected function _findSearch($state, $query, $results = []) { if (!class_exists('SearchableBehavior')) { - throw new MissingPluginException(array('plugin' => 'Utils')); + throw new MissingPluginException(['plugin' => 'Utils']); } if ($state == 'before') { - $this->Behaviors->load('Containable', array( - 'autoFields' => false) + $this->Behaviors->load('Containable', [ + 'autoFields' => false] ); $results = $query; @@ -741,19 +747,19 @@ protected function _findSearch($state, $query, $results = array()) { case 'username': $results['conditions'] = Hash::merge( $query['conditions'], - array($this->alias . '.username LIKE' => $like)); + [$this->alias . '.username LIKE' => $like]); break; case 'email': $results['conditions'] = Hash::merge( $query['conditions'], - array($this->alias . '.email LIKE' => $like)); + [$this->alias . '.email LIKE' => $like]); break; case 'any': $results['conditions'] = Hash::merge( $query['conditions'], - array('OR' => array( - array($this->alias . '.username LIKE' => $like), - array($this->alias . '.email LIKE' => $like)))); + ['OR' => [ + [$this->alias . '.username LIKE' => $like], + [$this->alias . '.email LIKE' => $like]]]); break; case '' : $results['conditions'] = $query['conditions']; @@ -761,12 +767,12 @@ protected function _findSearch($state, $query, $results = array()) { default : $results['conditions'] = Hash::merge( $query['conditions'], - array($this->alias . '.username LIKE' => $like)); + [$this->alias . '.username LIKE' => $like]); break; } if (isset($query['operation']) && $query['operation'] == 'count') { - $results['fields'] = array('COUNT(DISTINCT ' . $this->alias . '.id)'); + $results['fields'] = ['COUNT(DISTINCT ' . $this->alias . '.id)']; } return $results; @@ -789,7 +795,7 @@ protected function _findSearch($state, $query, $results = array()) { * @param array $extra Extra options * @return array */ - public function paginateCount($conditions = array(), $recursive = 0, $extra = array()) { + public function paginateCount($conditions = [], $recursive = 0, $extra = []) { $parameters = compact('conditions'); if ($recursive != $this->recursive) { $parameters['recursive'] = $recursive; @@ -811,8 +817,9 @@ public function paginateCount($conditions = array(), $recursive = 0, $extra = ar * The difference to register() is that this method here is intended to be used * by admins to add new users without going through all the registration logic * - * @param array post data, should be Controller->data - * @return boolean True if the data was saved successfully. + * @param array $postData post data, should be Controller->data + * @return bool True if the data was saved successfully. + * @throws Exception */ public function add($postData = null) { if (!empty($postData)) { @@ -859,7 +866,7 @@ public function edit($userId = null, $postData = null) { if (!empty($postData)) { $this->set($postData); if ($this->validates()) { - if(isset($postData[$this->alias]['password'])) { + if (isset($postData[$this->alias]['password'])) { $this->data[$this->alias]['password'] = $this->hash($postData[$this->alias]['password'], 'sha1', true); } $result = $this->save(null, false); @@ -878,18 +885,18 @@ public function edit($userId = null, $postData = null) { * * Override this method and inject the conditions you need * - * @var mixed $userId - * @var array $options + * @param mixed $userId User id + * @param array $options Options array * @return array $user * @throws NotFoundException */ - public function getUserForEditing($userId = null, $options = array()) { - $defaults = array( - 'contain' => array(), - 'conditions' => array( + public function getUserForEditing($userId = null, $options = []) { + $defaults = [ + 'contain' => [], + 'conditions' => [ $this->alias . '.id' => $userId - ) - ); + ] + ]; $options = Hash::merge($defaults, $options); $user = $this->find('first', $options); @@ -909,9 +916,9 @@ public function getUserForEditing($userId = null, $options = array()) { * @return void */ protected function _removeExpiredRegistrations() { - $this->deleteAll(array( + $this->deleteAll([ $this->alias . '.email_verified' => 0, - $this->alias . '.email_token_expires <' => date('Y-m-d H:i:s')) + $this->alias . '.email_token_expires <' => date('Y-m-d H:i:s')] ); } diff --git a/Model/UsersAppModel.php b/Model/UsersAppModel.php index 94765e049..30ef598cd 100644 --- a/Model/UsersAppModel.php +++ b/Model/UsersAppModel.php @@ -1,11 +1,11 @@ recursive) { $parameters['recursive'] = $recursive; diff --git a/README.md b/README.md index 6b2217e3c..4ab75f165 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,11 @@ Versions and branches | CakePHP | CakeDC Users Plugin | Tag | Notes | | :-------------: | :------------------------: | :--: | :---- | -| 2.x | [master](https://github.com/cakedc/users/tree/master) | 2.1.3 | Note CakePHP 2.7 is currently not supported, we are working on it now | -| 3.0 | [3.0.x](https://github.com/cakedc/users/tree/3.0.x) | 3.0.0 | stability is beta, but pretty stable now | -| 3.1 | [3.1.x](https://github.com/cakedc/users/tree/3.1.x) | 3.1.0 | stability is beta, but pretty stable now | +| ^3.5 | [master](https://github.com/cakedc/users/tree/master) | 6.0.0 | stable | +| ^3.5 | [develop](https://github.com/cakedc/users/tree/develop) | - | unstable | +| 3.4 | [5.x](https://github.com/cakedc/users/tree/5.x) | 5.2.0 | stable | +| 3.3 | [4.x](https://github.com/cakedc/users/tree/4.x) | 4.2.0 | stable | +| 2.x | [2.x](https://github.com/cakedc/users/tree/2.x) | 2.2.0 | stable | The **Users** plugin is for allowing users to register and login manage their profile. It also allows admins to manage the users. @@ -24,8 +26,8 @@ That it works out of the box doesn't mean it is thought to be used exactly like Requirements ------------ -* CakePHP 2.5+ -* PHP 5.2.8+ +* CakePHP 2.10+ +* PHP 5.6.0+ - PHP 7.1 * [CakeDC Utils plugin](http://github.com/CakeDC/utils) (Optional but recommended) * [CakeDC Search plugin](http://github.com/CakeDC/search) (Optional but recommended) diff --git a/Test/Case/AllAuthenticateTest.php b/Test/Case/AllAuthenticateTest.php index bab10b726..e8342eff8 100644 --- a/Test/Case/AllAuthenticateTest.php +++ b/Test/Case/AllAuthenticateTest.php @@ -1,22 +1,23 @@ -addTestDirectoryRecursive($path); - - return $suite; - } -} +addTestDirectoryRecursive($path); + + return $suite; + } +} diff --git a/Test/Case/AllUsersTest.php b/Test/Case/AllUsersTest.php index 49233bf7b..453c5eea9 100644 --- a/Test/Case/AllUsersTest.php +++ b/Test/Case/AllUsersTest.php @@ -1,30 +1,30 @@ -addTestDirectory($basePath . DS . 'Controller'); - $Suite->addTestDirectory($basePath . DS . 'Controller' . DS . 'Component'); - $Suite->addTestDirectory($basePath . DS . 'Controller' . DS . 'Component' . DS . 'Auth'); - $Suite->addTestDirectory($basePath . DS . 'Model'); - return $Suite; - } - -} \ No newline at end of file +addTestDirectory($basePath . DS . 'Controller'); + $Suite->addTestDirectory($basePath . DS . 'Controller' . DS . 'Component'); + $Suite->addTestDirectory($basePath . DS . 'Controller' . DS . 'Component' . DS . 'Auth'); + $Suite->addTestDirectory($basePath . DS . 'Model'); + return $Suite; + } + +} diff --git a/Test/Case/Controller/Component/Auth/CookieAuthenticateTest.php b/Test/Case/Controller/Component/Auth/CookieAuthenticateTest.php index 1ca0188e8..58e4b5f8b 100644 --- a/Test/Case/Controller/Component/Auth/CookieAuthenticateTest.php +++ b/Test/Case/Controller/Component/Auth/CookieAuthenticateTest.php @@ -1,92 +1,93 @@ -request = new CakeRequest('posts/index', false); - Router::setRequestInfo($this->request); - $this->Collection = new ComponentCollection(); - $this->Collection->load('Cookie'); - $this->Collection->load('Session'); - $this->auth = new CookieAuthenticate($this->Collection, array( - 'fields' => array('username' => 'user', 'password' => 'password'), - 'userModel' => 'MultiUser', - )); - $password = Security::hash('password', null, true); - $User = ClassRegistry::init('MultiUser'); - $User->updateAll(array('password' => $User->getDataSource()->value($password))); - $this->response = $this->getMock('CakeResponse'); - } - -/** - * tearDown - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - $this->Collection->Cookie->destroy(); - } - -/** - * test authenticate email or username - * - * @return void - */ - public function testAuthenticate() { - $expected = array( - 'id' => 1, - 'user' => 'mariano', - 'email' => 'mariano@example.com', - 'token' => '12345', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ); - - $result = $this->auth->authenticate($this->request, $this->response); - $this->assertFalse($result); - - $this->Collection->Cookie->write('MultiUser', array('user' => 'mariano', 'password' => 'password')); - $result = $this->auth->authenticate($this->request, $this->response); - $this->assertEquals($expected, $result); - } -} +request = new CakeRequest('posts/index', false); + Router::setRequestInfo($this->request); + $this->Collection = new ComponentCollection(); + $this->Collection->load('Cookie'); + $this->Collection->load('Session'); + $this->auth = new CookieAuthenticate($this->Collection, [ + 'fields' => ['username' => 'user', 'password' => 'password'], + 'userModel' => 'MultiUser', + ]); + $password = Security::hash('password', null, true); + $User = ClassRegistry::init('MultiUser'); + $User->updateAll(['password' => $User->getDataSource()->value($password)]); + $this->response = $this->getMockBuilder('CakeResponse')->getMock(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + $this->Collection->Cookie->destroy(); + } + +/** + * test authenticate email or username + * + * @return void + */ + public function testAuthenticate() { + $expected = [ + 'id' => 1, + 'user' => 'mariano', + 'email' => 'mariano@example.com', + 'token' => '12345', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ]; + + $result = $this->auth->authenticate($this->request, $this->response); + $this->assertFalse($result); + + $this->Collection->Cookie->write('MultiUser', ['user' => 'mariano', 'password' => 'password']); + $result = $this->auth->authenticate($this->request, $this->response); + $this->assertEquals($expected, $result); + } +} diff --git a/Test/Case/Controller/Component/Auth/MultiColumnAuthenticateTest.php b/Test/Case/Controller/Component/Auth/MultiColumnAuthenticateTest.php index 2097812de..156c108df 100644 --- a/Test/Case/Controller/Component/Auth/MultiColumnAuthenticateTest.php +++ b/Test/Case/Controller/Component/Auth/MultiColumnAuthenticateTest.php @@ -1,152 +1,153 @@ -Collection = $this->getMock('ComponentCollection'); - $this->auth = new MultiColumnAuthenticate($this->Collection, array( - 'fields' => array('username' => 'user', 'password' => 'password'), - 'userModel' => 'MultiUser', - 'columns' => array('user', 'email') - )); - $password = Security::hash('password', null, true); - $User = ClassRegistry::init('MultiUser'); - $User->updateAll(array('password' => $User->getDataSource()->value($password))); - $this->response = $this->getMock('CakeResponse'); - } - -/** - * test authenticate email or username - * - * @return void - */ - public function testAuthenticateEmailOrUsername() { - $request = new CakeRequest('posts/index', false); - $expected = array( - 'id' => 1, - 'user' => 'mariano', - 'email' => 'mariano@example.com', - 'token' => '12345', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ); - - $request->data = array('MultiUser' => array( - 'user' => 'mariano', - 'password' => 'password' - )); - $result = $this->auth->authenticate($request, $this->response); - $this->assertEquals($expected, $result); - - $request->data = array('MultiUser' => array( - 'user' => 'mariano@example.com', - 'password' => 'password' - )); - $result = $this->auth->authenticate($request, $this->response); - $this->assertEquals($expected, $result); - } - -/** - * test the authenticate method - * - * @return void - */ - public function testAuthenticateNoData() { - $request = new CakeRequest('posts/index', false); - $request->data = array(); - $this->assertFalse($this->auth->authenticate($request, $this->response)); - } - -/** - * test the authenticate method - * - * @return void - */ - public function testAuthenticateNoUsername() { - $request = new CakeRequest('posts/index', false); - $request->data = array('MultiUser' => array('password' => 'foobar')); - $this->assertFalse($this->auth->authenticate($request, $this->response)); - } - -/** - * test the authenticate method - * - * @return void - */ - public function testAuthenticateNoPassword() { - $request = new CakeRequest('posts/index', false); - $request->data = array('MultiUser' => array('user' => 'mariano')); - $this->assertFalse($this->auth->authenticate($request, $this->response)); - - $request->data = array('MultiUser' => array('user' => 'mariano@example.com')); - $this->assertFalse($this->auth->authenticate($request, $this->response)); - } - -/** - * test the authenticate method - * - * @return void - */ - public function testAuthenticateInjection() { - $request = new CakeRequest('posts/index', false); - $request->data = array( - 'MultiUser' => array( - 'user' => '> 1', - 'password' => "' OR 1 = 1" - )); - $this->assertFalse($this->auth->authenticate($request, $this->response)); - } - -/** - * test scope failure. - * - * @return void - */ - public function testAuthenticateScopeFail() { - $this->auth->settings['scope'] = array('user' => 'nate'); - $request = new CakeRequest('posts/index', false); - $request->data = array('User' => array( - 'user' => 'mariano', - 'password' => 'password' - )); - - $this->assertFalse($this->auth->authenticate($request, $this->response)); - } - -} +Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $this->auth = new MultiColumnAuthenticate($this->Collection, [ + 'fields' => ['username' => 'user', 'password' => 'password'], + 'userModel' => 'MultiUser', + 'columns' => ['user', 'email'] + ]); + $password = Security::hash('password', null, true); + $User = ClassRegistry::init('MultiUser'); + $User->updateAll(['password' => $User->getDataSource()->value($password)]); + $this->response = $this->getMockBuilder('CakeResponse')->getMock(); + } + +/** + * test authenticate email or username + * + * @return void + */ + public function testAuthenticateEmailOrUsername() { + $request = new CakeRequest('posts/index', false); + $expected = [ + 'id' => 1, + 'user' => 'mariano', + 'email' => 'mariano@example.com', + 'token' => '12345', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ]; + + $request->data = ['MultiUser' => [ + 'user' => 'mariano', + 'password' => 'password' + ]]; + $result = $this->auth->authenticate($request, $this->response); + $this->assertEquals($expected, $result); + + $request->data = ['MultiUser' => [ + 'user' => 'mariano@example.com', + 'password' => 'password' + ]]; + $result = $this->auth->authenticate($request, $this->response); + $this->assertEquals($expected, $result); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoData() { + $request = new CakeRequest('posts/index', false); + $request->data = []; + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoUsername() { + $request = new CakeRequest('posts/index', false); + $request->data = ['MultiUser' => ['password' => 'foobar']]; + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoPassword() { + $request = new CakeRequest('posts/index', false); + $request->data = ['MultiUser' => ['user' => 'mariano']]; + $this->assertFalse($this->auth->authenticate($request, $this->response)); + + $request->data = ['MultiUser' => ['user' => 'mariano@example.com']]; + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateInjection() { + $request = new CakeRequest('posts/index', false); + $request->data = [ + 'MultiUser' => [ + 'user' => '> 1', + 'password' => "' OR 1 = 1" + ]]; + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test scope failure. + * + * @return void + */ + public function testAuthenticateScopeFail() { + $this->auth->settings['scope'] = ['user' => 'nate']; + $request = new CakeRequest('posts/index', false); + $request->data = ['User' => [ + 'user' => 'mariano', + 'password' => 'password' + ]]; + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +} diff --git a/Test/Case/Controller/Component/Auth/TokenAuthenticateTest.php b/Test/Case/Controller/Component/Auth/TokenAuthenticateTest.php index 3befe1282..01d7652ee 100644 --- a/Test/Case/Controller/Component/Auth/TokenAuthenticateTest.php +++ b/Test/Case/Controller/Component/Auth/TokenAuthenticateTest.php @@ -1,120 +1,121 @@ -Collection = $this->getMock('ComponentCollection'); - $this->auth = new TokenAuthenticate($this->Collection, array( - 'fields' => array( - 'username' => 'user', - 'password' => 'password', - 'token' => 'token' - ), - 'userModel' => 'MultiUser', - )); - $password = Security::hash('password', null, true); - $User = ClassRegistry::init('MultiUser'); - $User->updateAll(array('password' => $User->getDataSource()->value($password))); - $this->response = $this->getMock('CakeResponse'); - } - -/** - * test authenticate token as query parameter - * - * @return void - */ - public function testAuthenticateTokenParameter() { - $this->auth->settings['_parameter'] = 'token'; - $request = new CakeRequest('posts/index?_token=54321'); - - $result = $this->auth->getUser($request, $this->response); - $this->assertFalse($result); - - $expected = array( - 'id' => '1', - 'user' => 'mariano', - 'email' => 'mariano@example.com', - 'token' => '12345', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ); - $request = new CakeRequest('posts/index?_token=12345'); - $result = $this->auth->getUser($request, $this->response); - $this->assertEquals($expected, $result); - - $this->auth->settings['parameter'] = 'tokenname'; - $request = new CakeRequest('posts/index?tokenname=12345'); - $result = $this->auth->getUser($request, $this->response); - $this->assertEquals($expected, $result); - } - -/** - * test authenticate token as request header - * - * @return void - */ - public function testAuthenticateTokenHeader() { - $_SERVER['HTTP_X_APITOKEN'] = '54321'; - $request = new CakeRequest('posts/index', false); - - $result = $this->auth->getUser($request, $this->response); - $this->assertFalse($result); - - $expected = array( - 'id' => '1', - 'user' => 'mariano', - 'email' => 'mariano@example.com', - 'token' => '12345', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ); - $_SERVER['HTTP_X_APITOKEN'] = '12345'; - $result = $this->auth->getUser($request, $this->response); - $this->assertEquals($expected, $result); - } - -} +Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $this->auth = new TokenAuthenticate($this->Collection, [ + 'fields' => [ + 'username' => 'user', + 'password' => 'password', + 'token' => 'token' + ], + 'userModel' => 'MultiUser', + ]); + $password = Security::hash('password', null, true); + $User = ClassRegistry::init('MultiUser'); + $User->updateAll(['password' => $User->getDataSource()->value($password)]); + $this->response = $this->getMockBuilder('CakeResponse')->getMock(); + } + +/** + * test authenticate token as query parameter + * + * @return void + */ + public function testAuthenticateTokenParameter() { + $this->auth->settings['_parameter'] = 'token'; + $request = new CakeRequest('posts/index?_token=54321'); + + $result = $this->auth->getUser($request, $this->response); + $this->assertFalse($result); + + $expected = [ + 'id' => '1', + 'user' => 'mariano', + 'email' => 'mariano@example.com', + 'token' => '12345', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ]; + $request = new CakeRequest('posts/index?_token=12345'); + $result = $this->auth->getUser($request, $this->response); + $this->assertEquals($expected, $result); + + $this->auth->settings['parameter'] = 'tokenname'; + $request = new CakeRequest('posts/index?tokenname=12345'); + $result = $this->auth->getUser($request, $this->response); + $this->assertEquals($expected, $result); + } + +/** + * test authenticate token as request header + * + * @return void + */ + public function testAuthenticateTokenHeader() { + $_SERVER['HTTP_X_APITOKEN'] = '54321'; + $request = new CakeRequest('posts/index', false); + + $result = $this->auth->getUser($request, $this->response); + $this->assertFalse($result); + + $expected = [ + 'id' => '1', + 'user' => 'mariano', + 'email' => 'mariano@example.com', + 'token' => '12345', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ]; + $_SERVER['HTTP_X_APITOKEN'] = '12345'; + $result = $this->auth->getUser($request, $this->response); + $this->assertEquals($expected, $result); + } + +} diff --git a/Test/Case/Controller/Component/RememberMeComponentTest.php b/Test/Case/Controller/Component/RememberMeComponentTest.php index 7f5dbbffc..135a3da1e 100644 --- a/Test/Case/Controller/Component/RememberMeComponentTest.php +++ b/Test/Case/Controller/Component/RememberMeComponentTest.php @@ -1,171 +1,170 @@ - array( - 'email' => 'test@cakedc.com', - 'password' => 'test' - ), - 'admin' => array( - 'email' => 'admin@cakedc.com', - 'password' => 'admin' - ) - ); - -/** - * start - * - * @return void - */ - public function setUp() { - $_COOKIE = array(); - Configure::write('Config.language', 'eng'); - $this->request = new CakeRequest(); - $this->Controller = new RememberMeComponentTestController($this->request, new CakeResponse()); - $this->Controller->constructClasses(); - - $this->RememberMe = $this->Controller->RememberMe; - $this->RememberMe->Cookie = $this->getMock('CookieComponent', - array(), - array($this->Controller->Components)); - $this->RememberMe->Auth = $this->getMock('AuthComponent', - array(), - array($this->Controller->Components)); - $this->RememberMe->request = $this->request; - } - -/** - * testSetCookie - * - * @return void - */ - public function testSetCookie() { - $this->RememberMe->Cookie->expects($this->once()) - ->method('write') - ->with('rememberMe', array( - 'email' => 'email', - 'password' => 'password'), true); - - $this->RememberMe->setCookie(array( - 'User' => array( - 'email' => 'email', - 'password' => 'password') - ) - ); - } - -/** - * testRestoreLoginFromCookie - * - * @return void - */ - public function testRestoreLoginFromCookie() { - $this->RememberMe->Cookie->expects($this->any()) - ->method('read') - ->with($this->equalTo('rememberMe')) - ->will($this->returnValue($this->usersData['admin'])); - - $this->RememberMe->Auth->expects($this->once()) - ->method('login') - ->will($this->returnValue(true)); - - $this->__setPostData(array('User' => $this->usersData['test'])); - - $this->RememberMe->restoreLoginFromCookie(); - - // even if we post "test" user, we have a remember me cookie set and will prioritize the cookie over the post - // NOTE we check if the user is logged in in the startup method of the Component - $this->assertEquals($this->RememberMe->request->data, array( - 'User' => $this->usersData['admin'] - )); - } - -/** - * testRestoreLoginFromCookieIncorrectLogin - * - * We check the post request data is not modified when the cookie holds incorrect login credentials - * - * @return void - */ - public function testRestoreLoginFromCookieIncorrectLogin() { - // cookie will hold "admin" data, and post request will have "test" - $this->RememberMe->Cookie->expects($this->any()) - ->method('read') - ->with($this->equalTo('rememberMe')) - ->will($this->returnValue($this->usersData['admin'])); - // admin will not login - $this->RememberMe->Auth->expects($this->once()) - ->method('login') - ->will($this->returnValue(false)); - // post has "test" data - $this->__setPostData(array('User' => $this->usersData['test'])); - $this->RememberMe->restoreLoginFromCookie(); - $this->assertEquals($this->RememberMe->request->data, array( - 'User' => $this->usersData['test'])); - } - -/** - * testDestroyCookie - * - * @return void - */ - public function testDestroyCookie() { - $_COOKIE['User'] = 'defined'; - $this->RememberMe->Cookie->expects($this->once()) - ->method('destroy'); - $this->RememberMe->destroyCookie(); - } - -/** - * Set post data to the test controller - * - * @var array $data - * @return void - */ - private function __setPostData($data = array()) { - $_SERVER['REQUEST_METHOD'] = 'POST'; - $this->RememberMe->request->data = $data; - } -} + [ + 'email' => 'test@cakedc.com', + 'password' => 'test' + ], + 'admin' => [ + 'email' => 'admin@cakedc.com', + 'password' => 'admin' + ] + ]; + +/** + * start + * + * @return void + */ + public function setUp() { + $_COOKIE = []; + Configure::write('Config.language', 'eng'); + $this->request = new CakeRequest(); + $this->Controller = new RememberMeComponentTestController($this->request, new CakeResponse()); + $this->Controller->constructClasses(); + + $this->RememberMe = $this->Controller->RememberMe; + $this->RememberMe->Cookie = $this->getMockBuilder('CookieComponent') + ->setConstructorArgs([$this->Controller->Components]) + ->getMock(); + $this->RememberMe->Auth = $this->getMockbuilder('AuthComponent')->setConstructorArgs([$this->Controller->Components])->getMock(); + $this->RememberMe->request = $this->request; + } + +/** + * testSetCookie + * + * @return void + */ + public function testSetCookie() { + $this->RememberMe->Cookie->expects($this->once()) + ->method('write') + ->with('rememberMe', [ + 'email' => 'email', + 'password' => 'password'], true); + + $this->RememberMe->setCookie([ + 'User' => [ + 'email' => 'email', + 'password' => 'password'] + ] + ); + } + +/** + * testRestoreLoginFromCookie + * + * @return void + */ + public function testRestoreLoginFromCookie() { + $this->RememberMe->Cookie->expects($this->any()) + ->method('read') + ->with($this->equalTo('rememberMe')) + ->will($this->returnValue($this->usersData['admin'])); + + $this->RememberMe->Auth->expects($this->once()) + ->method('login') + ->will($this->returnValue(true)); + + $this->__setPostData(['User' => $this->usersData['test']]); + + $this->RememberMe->restoreLoginFromCookie(); + + // even if we post "test" user, we have a remember me cookie set and will prioritize the cookie over the post + // NOTE we check if the user is logged in in the startup method of the Component + $this->assertEquals($this->RememberMe->request->data, [ + 'User' => $this->usersData['admin'] + ]); + } + +/** + * testRestoreLoginFromCookieIncorrectLogin + * + * We check the post request data is not modified when the cookie holds incorrect login credentials + * + * @return void + */ + public function testRestoreLoginFromCookieIncorrectLogin() { + // cookie will hold "admin" data, and post request will have "test" + $this->RememberMe->Cookie->expects($this->any()) + ->method('read') + ->with($this->equalTo('rememberMe')) + ->will($this->returnValue($this->usersData['admin'])); + // admin will not login + $this->RememberMe->Auth->expects($this->once()) + ->method('login') + ->will($this->returnValue(false)); + // post has "test" data + $this->__setPostData(['User' => $this->usersData['test']]); + $this->RememberMe->restoreLoginFromCookie(); + $this->assertEquals($this->RememberMe->request->data, [ + 'User' => $this->usersData['test']]); + } + +/** + * testDestroyCookie + * + * @return void + */ + public function testDestroyCookie() { + $_COOKIE['User'] = 'defined'; + $this->RememberMe->Cookie->expects($this->once()) + ->method('destroy'); + $this->RememberMe->destroyCookie(); + } + +/** + * Set post data to the test controller + * + * @var array $data + * @return void + */ + private function __setPostData($data = []) { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->RememberMe->request->data = $data; + } +} diff --git a/Test/Case/Controller/UsersControllerTest.php b/Test/Case/Controller/UsersControllerTest.php index aca10d220..3c20cf84c 100644 --- a/Test/Case/Controller/UsersControllerTest.php +++ b/Test/Case/Controller/UsersControllerTest.php @@ -1,11 +1,11 @@ Auth->authorize = array('Controller'); - $this->Auth->fields = array('username' => 'email', 'password' => 'password'); - $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login', 'plugin' => 'users'); + $this->Auth->authorize = ['Controller']; + $this->Auth->fields = ['username' => 'email', 'password' => 'password']; + $this->Auth->loginAction = ['controller' => 'users', 'action' => 'login', 'plugin' => 'users']; $this->Auth->loginRedirect = $this->Session->read('Auth.redirect'); $this->Auth->logoutRedirect = '/'; $this->Auth->authError = __d('users', 'Sorry, but you need to login to access this location.'); $this->Auth->autoRedirect = true; $this->Auth->userModel = 'User'; - $this->Auth->userScope = array( - 'OR' => array( + $this->Auth->userScope = [ + 'OR' => [ 'AND' => - array('User.active' => 1, 'User.email_verified' => 1 - ) - ) - ); + ['User.active' => 1, 'User.email_verified' => 1 + ] + ] + ]; } /** * Public interface to _setCookie */ - public function setCookie($options = array()) { + public function setCookie($options = []) { parent::_setCookie($options); } @@ -81,7 +81,7 @@ public function getMailInstance() { /** * Auto render * - * @var boolean + * @var bool */ public $autoRender = false; @@ -112,7 +112,7 @@ public function redirect($url, $status = null, $exit = true) { * @param string * @param string * @param string - * @return string + * @return void */ public function render($action = null, $layout = null, $file = null) { $this->renderedView = $action; @@ -129,22 +129,6 @@ protected function _getMailInstance() { } -/** - * Email configuration override for testing - */ -class EmailConfig { - - public $default = array( - 'transport' => 'Debug', - 'from' => 'default@example.com', - ); - - public $another = array( - 'transport' => 'Debug', - 'from' => 'another@example.com', - ); -} - class UsersControllerTestCase extends CakeTestCase { /** @@ -159,30 +143,30 @@ class UsersControllerTestCase extends CakeTestCase { * * @var array */ - public $fixtures = array( + public $fixtures = [ 'plugin.users.user', - ); + ]; /** * Sampletdata used for post data * * @var array */ - public $usersData = array( - 'admin' => array( + public $usersData = [ + 'admin' => [ 'email' => 'adminuser@cakedc.com', 'username' => 'adminuser', - 'password' => 'test'), - 'validUser' => array( + 'password' => 'test'], + 'validUser' => [ 'email' => 'testuser@cakedc.com', 'username' => 'testuser', 'password' => 'secretkey', - 'redirect' => '/user/slugname'), - 'invalidUser' => array( + 'redirect' => '/user/slugname'], + 'invalidUser' => [ 'email' => 'wronguser@wronguser.com', 'username' => 'invalidUser', - 'password' => 'invalid-password!'), - ); + 'password' => 'invalid-password!'], + ]; /** * Start test @@ -196,25 +180,30 @@ public function setUp() { Configure::write('App.UserClass', null); $request = new CakeRequest(); - $response = $this->getMock('CakeResponse'); + $response = $this->getMockBuilder('CakeResponse')->getMock(); $this->Users = new TestUsersController($request, $response); $this->Users->constructClasses(); - $this->Users->request->params = array( - 'pass' => array(), - 'named' => array(), + $this->Users->request->params = [ + 'pass' => [], + 'named' => [], 'controller' => 'users', 'admin' => false, 'plugin' => 'users', - 'url' => array()); + 'url' => []]; if (CakePlugin::loaded('Search')) { - $this->Users->Prg = $this->getMock('PrgComponent', - array('commonProcess'), - array($this->Users->Components, array())); + $this->Users->Prg = $this->getMockBuilder('PrgComponent') + ->setMethods(['commonProcess']) + ->setConstructorArgs([$this->Users->Components, []]) + ->getMock(); } - $this->Users->CakeEmail = $this->getMock('CakeEmail'); + $this->Users->CakeEmail = $this->getMockBuilder('CakeEmail') + ->setConstructorArgs([ + 'transport' => 'Debug', + 'from' => 'default@example.com', + ])->getMock(); $this->Users->CakeEmail->expects($this->any()) ->method('to') ->will($this->returnSelf()); @@ -253,17 +242,23 @@ public function testUsersControllerInstance() { */ public function testUserLogin() { $this->Users->request->params['action'] = 'login'; - $this->__setPost(array('User' => $this->usersData['admin'])); + $this->__setPost(['User' => $this->usersData['admin']]); $this->Users->request->url = '/users/users/login'; - $this->Collection = $this->getMock('ComponentCollection'); - $session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); - $this->Users->Session = $session; - $this->Users->Session->expects($this->any()) - ->method('setFlash') + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->any()) + ->method('set') ->with(__d('users', 'adminuser you have successfully logged in')); - $this->Users->Auth = $this->getMock('AuthComponent', array('login', 'user', 'redirectUrl'), array($this->Collection)); - $this->Users->Auth->Session = $session; + $this->Users->Auth = $this->getMockBuilder('AuthComponent') + ->setMethods(['login', 'user', 'redirectUrl']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Auth->Flash = $flash; $this->Users->Auth->expects($this->once()) ->method('login') ->will($this->returnValue(true)); @@ -285,7 +280,9 @@ public function testUserLogin() { ->with(null) ->will($this->returnValue(Router::normalize('/'))); - $this->Users->RememberMe = $this->getMock('RememberMeComponent', array(), array($this->Collection)); + $this->Users->RememberMe = $this->getMockBuilder('RememberMeComponent') + ->setConstructorArgs([$this->Collection]) + ->getMock(); $this->Users->RememberMe->expects($this->any()) ->method('destroyCookie'); @@ -304,10 +301,14 @@ public function testUserLoginGet() { $this->Users->request->params['action'] = 'login'; $this->__setGet(); $this->Users->login(); - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); - $this->Users->Session->expects($this->never()) - ->method('setFlash'); + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->never()) + ->method('set'); } /** @@ -317,9 +318,12 @@ public function testUserLoginGet() { */ public function testFailedUserLogin() { $this->Users->request->params['action'] = 'login'; - $this->__setPost(array('User' => $this->usersData['invalidUser'])); - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->Auth = $this->getMock('AuthComponent', array('flash', 'login'), array($this->Collection)); + $this->__setPost(['User' => $this->usersData['invalidUser']]); + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $this->Users->Auth = $this->getMockBuilder('AuthComponent') + ->setMethods(['flash', 'login']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); $this->Users->Auth->expects($this->once()) ->method('login') ->will($this->returnValue(false)); @@ -339,31 +343,39 @@ public function testAdd() { ->method('send'); $_SERVER['HTTP_HOST'] = 'test.com'; $this->Users->params['action'] = 'add'; - $this->__setPost(array( - 'User' => array( + $this->__setPost([ + 'User' => [ 'username' => 'newUser', 'email' => 'newUser@newemail.com', 'password' => 'password', 'temppassword' => 'password', - 'tos' => 1))); + 'tos' => 1]]); $this->Users->beforeFilter(); - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); - $this->Users->Session->expects($this->once()) - ->method('setFlash') + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->once()) + ->method('set') ->with(__d('users', 'Your account has been created. You should receive an e-mail shortly to authenticate your account. Once validated you will be able to login.')); $this->Users->add(); - $this->__setPost(array( - 'User' => array( + $this->__setPost([ + 'User' => [ 'username' => 'newUser', 'email' => '', 'password' => '', 'temppassword' => '', - 'tos' => 0))); + 'tos' => 0]]); $this->Users->beforeFilter(); - $this->Users->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); - $this->Users->Session->expects($this->once()) - ->method('setFlash') + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->once()) + ->method('set') ->with(__d('users', 'Your account could not be created. Please, try again.')); $this->Users->add(); } @@ -377,18 +389,26 @@ public function testVerify() { $this->Users->beforeFilter(); $this->Users->User->id = '37ea303a-3bdc-4251-b315-1316c0b300fa'; $this->Users->User->saveField('email_token_expires', date('Y-m-d H:i:s', strtotime('+1 year'))); - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); - $this->Users->Session->expects($this->once()) - ->method('setFlash') + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->once()) + ->method('set') ->with(__d('users', 'Your e-mail has been validated!')); $this->Users->verify('email', 'testtoken2'); $this->Users->beforeFilter(); - $this->Users->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection)); - $this->Users->Session->expects($this->once()) - ->method('setFlash') + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->once()) + ->method('set') ->with(__d('users', 'Invalid token, please check the email you were sent, and retry the verification link.')); $this->Users->verify('email', 'invalid-token'); @@ -401,22 +421,36 @@ public function testVerify() { */ public function testLogout() { $this->Users->beforeFilter(); - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->Cookie = $this->getMock('CookieComponent', array(), array($this->Collection)); - $this->Users->Session = $this->getMock('SessionComponent', array('setFlash', 'destroy'), array($this->Collection)); - $this->Users->Session->expects($this->once()) - ->method('setFlash') + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $this->Users->Cookie = $this->getMockBuilder('CookieComponent') + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Session = $this->getMockBuilder('SessionComponent') + ->setMethods(['destroy']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $flash = $this->getMockBuilder('FlashComponent') + ->setMethods(['set']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); + $this->Users->Flash = $flash; + $this->Users->Flash->expects($this->once()) + ->method('set') ->with(__d('users', 'testuser you have successfully logged out')); $this->Users->Session->expects($this->once()) ->method('destroy'); - $this->Users->Auth = $this->getMock('AuthComponent', array('logout', 'user'), array($this->Collection)); + $this->Users->Auth = $this->getMockbuilder('AuthComponent') + ->setMethods(['logout', 'user']) + ->setConstructorArgs([$this->Collection])->getMock(); $this->Users->Auth->expects($this->once()) ->method('logout') ->will($this->returnValue('/')); $this->Users->Auth->staticExpects($this->at(0)) ->method('user') ->will($this->returnValue($this->usersData['validUser'])); - $this->Users->RememberMe = $this->getMock('RememberMeComponent', array(), array($this->Collection)); + $this->Users->RememberMe = $this->getMockBuilder('RememberMeComponent') + ->setConstructorArgs([$this->Collection]) + ->getMock(); $this->Users->RememberMe->expects($this->any()) ->method('destroyCookie'); @@ -430,7 +464,7 @@ public function testLogout() { * @return void */ public function testIndex() { - $this->Users->passedArgs = array(); + $this->Users->passedArgs = []; $this->Users->index(); $this->assertTrue(isset($this->Users->viewVars['users'])); } @@ -454,18 +488,21 @@ public function testView() { * @return void */ public function testChangePassword() { - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->Auth = $this->getMock('AuthComponent', array('user'), array($this->Collection)); + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $this->Users->Auth = $this->getMockbuilder('AuthComponent') + ->setMethods(['user']) + ->setConstructorArgs([$this->Collection]) + ->getMock(); $this->Users->Auth->staticExpects($this->once()) ->method('user') ->with('id') ->will($this->returnValue(1)); - $this->__setPost(array( - 'User' => array( + $this->__setPost([ + 'User' => [ 'new_password' => 'newpassword', 'confirm_password' => 'newpassword', - 'old_password' => 'test'))); - $this->Users->RememberMe = $this->getMock('RememberMeComponent', array(), array($this->Collection)); + 'old_password' => 'test']]); + $this->Users->RememberMe = $this->getMockBuilder('RememberMeComponent')->setConstructorArgs([$this->Collection])->getMock(); $this->Users->RememberMe->expects($this->any()) ->method('destroyCookie'); @@ -484,21 +521,21 @@ public function testResetPassword() { $_SERVER['HTTP_HOST'] = 'test.com'; $this->Users->User->id = '1'; $this->Users->User->saveField('email_token_expires', date('Y-m-d H:i:s', strtotime('+1 year'))); - $this->Users->data = array( - 'User' => array( + $this->Users->data = [ + 'User' => [ 'email' => 'adminuser@cakedc.com' - ) - ); + ] + ]; $this->Users->reset_password(); - $this->assertEquals($this->Users->redirectUrl, array('action' => 'login')); - $this->Users->data = array( - 'User' => array( + $this->assertEquals($this->Users->redirectUrl, ['action' => 'login']); + $this->Users->data = [ + 'User' => [ 'new_password' => 'newpassword', 'confirm_password' => 'newpassword' - ) - ); + ] + ]; $this->Users->reset_password('testtoken'); - $this->assertEquals($this->Users->redirectUrl, array('action' => 'reset_password')); + $this->assertEquals($this->Users->redirectUrl, ['action' => 'reset_password']); } /** @@ -507,11 +544,11 @@ public function testResetPassword() { * @return void */ public function testAdminIndex() { - $this->Users->params = array( - 'url' => array(), - 'named' => array( - 'search' => 'adminuser')); - $this->Users->passedArgs = array(); + $this->Users->params = [ + 'url' => [], + 'named' => [ + 'search' => 'adminuser']]; + $this->Users->passedArgs = []; $this->Users->admin_index(); $this->assertTrue(isset($this->Users->viewVars['users'])); } @@ -535,10 +572,10 @@ public function testAdminDelete() { $this->Users->User->id = '1'; $this->assertTrue($this->Users->User->exists(true)); $this->Users->admin_delete('1'); - $this->assertEquals($this->Users->redirectUrl, array('action' => 'index')); + $this->assertEquals($this->Users->redirectUrl, ['action' => 'index']); $this->assertFalse($this->Users->User->exists(true)); $this->Users->admin_delete('INVALID-ID'); - $this->assertEquals($this->Users->redirectUrl, array('action' => 'index')); + $this->assertEquals($this->Users->redirectUrl, ['action' => 'index']); } /** @@ -547,21 +584,21 @@ public function testAdminDelete() { * @return void */ public function testSetCookie() { - $this->__setPost(array( - 'User' => array( + $this->__setPost([ + 'User' => [ 'remember_me' => 1, 'email' => 'testuser@cakedc.com', 'username' => 'test', - 'password' => 'testtest'))); - $this->Collection = $this->getMock('ComponentCollection'); - $this->Users->RememberMe = $this->getMock('RememberMeComponent', array(), array($this->Collection)); + 'password' => 'testtest']]); + $this->Collection = $this->getMockBuilder('ComponentCollection')->getMock(); + $this->Users->RememberMe = $this->getMockBuilder('RememberMeComponent')->setConstructorArgs([$this->Collection])->getMock(); $this->Users->RememberMe->expects($this->once()) ->method('configureCookie') - ->with(array('name' => 'userTestCookie')); + ->with(['name' => 'userTestCookie']); $this->Users->RememberMe->expects($this->once()) ->method('setCookie'); - $this->Users->setCookie(array( - 'name' => 'userTestCookie')); + $this->Users->setCookie([ + 'name' => 'userTestCookie']); $this->assertEquals($this->Users->RememberMe->settings['cookieKey'], 'rememberMe'); } @@ -571,14 +608,15 @@ public function testSetCookie() { * @return void */ public function testGetMailInstance() { + $this->Users->User = $this->getMockBuilder('User')->setMethods(['getMailInstance'])->getMock(); + $this->Users->User->expects($this->once()) + ->method('getMailInstance') + ->will($this->returnValue(new CakeEmail([ + 'transport' => 'Debug', + 'from' => 'default@example.com', + ]))); $defaultConfig = $this->Users->getMailInstance()->config(); $this->assertEquals($defaultConfig['from'], 'default@example.com'); - Configure::write('Users.emailConfig', 'another'); - $anotherConfig = $this->Users->getMailInstance()->config(); - $this->assertEquals($anotherConfig['from'], 'another@example.com'); - $this->setExpectedException('ConfigureException'); - Configure::write('Users.emailConfig', 'doesnotexist'); - $anotherConfig = $this->Users->getMailInstance()->config(); } /** @@ -587,9 +625,9 @@ public function testGetMailInstance() { * @var array $data * @return void */ - private function __setPost($data = array()) { + private function __setPost($data = []) { $_SERVER['REQUEST_METHOD'] = 'POST'; - $this->Users->request->data = array_merge($data, array('_method' => 'POST')); + $this->Users->request->data = array_merge($data, ['_method' => 'POST']); } /** diff --git a/Test/Case/Model/UserTest.php b/Test/Case/Model/UserTest.php index 1cb06c46c..fdc7e68f9 100755 --- a/Test/Case/Model/UserTest.php +++ b/Test/Case/Model/UserTest.php @@ -1,11 +1,11 @@ User->data['User']['password'] = 'password'; - $result = $this->User->confirmPassword(array('temppassword' => 'password')); + $result = $this->User->confirmPassword(['temppassword' => 'password']); $this->assertTrue($result); $this->User->data['User']['password'] = 'different_password'; - $result = $this->User->confirmPassword(array('temppassword' => 'password')); + $result = $this->User->confirmPassword(['temppassword' => 'password']); $this->assertFalse($result); } @@ -92,13 +92,13 @@ public function testConfirmPassword() { * @return void */ public function testConfirmEmail() { - $this->User->data['User'] = array( - 'email' => 'test@email.com'); - $this->assertFalse($this->User->confirmEmail(array('confirm_email' => 'test@wrong.com'))); + $this->User->data['User'] = [ + 'email' => 'test@email.com']; + $this->assertFalse($this->User->confirmEmail(['confirm_email' => 'test@wrong.com'])); - $this->User->data['User'] = array( - 'email' => 'test@email.com'); - $this->assertTrue($this->User->confirmEmail(array('confirm_email' => 'test@email.com'))); + $this->User->data['User'] = [ + 'email' => 'test@email.com']; + $this->assertTrue($this->User->confirmEmail(['confirm_email' => 'test@email.com'])); } /** @@ -128,32 +128,31 @@ public function testUpdateLastActivity() { $this->assertFalse($this->User->updateLastActivity('invalid-id!')); } - /** * testResetPassword * * @return void */ public function testResetPassword() { - $data = array( - 'User' => array( + $data = [ + 'User' => [ 'id' => 1, 'new_password' => '', - 'confirm_password' => 'dsgdsgsdg')); + 'confirm_password' => 'dsgdsgsdg']]; $this->assertFalse($this->User->resetPassword($data)); - $data = array( - 'User' => array( + $data = [ + 'User' => [ 'id' => 1, 'new_password' => '', - 'confirm_password' => '')); + 'confirm_password' => '']]; $this->assertFalse($this->User->resetPassword($data)); - $data = array( - 'User' => array( + $data = [ + 'User' => [ 'id' => 1, 'new_password' => 'newpassword', - 'confirm_password' => 'newpassword')); + 'confirm_password' => 'newpassword']]; $this->assertInternalType('array', $this->User->resetPassword($data)); } @@ -175,18 +174,18 @@ public function testCheckPasswordToken() { * @return void */ public function testPasswordReset() { - $data = array( - 'User' => array( + $data = [ + 'User' => [ 'id' => 1, - 'email' => 'somethingwrong in here!')); + 'email' => 'somethingwrong in here!']]; $this->assertFalse($this->User->passwordReset($data)); $this->User->id = '1'; $this->User->saveField('email_token_expires', date('Y-m-d H:i:s', strtotime('+1 year'))); - $data = array( - 'User' => array( + $data = [ + 'User' => [ 'id' => 1, - 'email' => 'adminuser@cakedc.com')); + 'email' => 'adminuser@cakedc.com']]; $this->assertInternalType('array', $this->User->passwordReset($data)); } @@ -199,15 +198,15 @@ public function testValidateOldPassword() { $password = $this->User->hash('password', null, true); $this->User->id = '1'; $this->User->saveField('password', $password); - $this->User->data = array( - 'User' => array( + $this->User->data = [ + 'User' => [ 'id' => '1', - 'password')); + 'password']]; - $result = $this->User->validateOldPassword(array('old_password' => 'password')); + $result = $this->User->validateOldPassword(['old_password' => 'password']); $this->assertTrue($result); - $result = $this->User->validateOldPassword(array('old_password' => 'FAIL!')); + $result = $this->User->validateOldPassword(['old_password' => 'FAIL!']); $this->assertFalse($result); } @@ -220,7 +219,7 @@ public function testView() { $result = $this->User->view('adminuser'); $this->assertTrue(is_array($result) && !empty($result)); - $this->expectException('NotFoundException'); + $this->setExpectedException('NotFoundException'); $result = $this->User->view('non-existing-user-slug'); } @@ -230,61 +229,61 @@ public function testView() { * @return void */ public function testRegister() { - $postData = array(); + $postData = []; $result = $this->User->register($postData); $this->assertFalse($result); - $postData = array('User' => array( + $postData = ['User' => [ 'username' => '#236236326sdg!!!.s#invalid', 'email' => 'invalid', 'password' => 'password', 'temppassword' => 'wrong', - 'tos' => 0)); + 'tos' => 0]]; $result = $this->User->register($postData); $this->assertFalse($result); - $this->assertEquals(array_keys($this->User->invalidFields()), array( - 'username', 'email', 'temppassword', 'tos')); + $this->assertEquals(array_keys($this->User->invalidFields()), [ + 'username', 'email', 'temppassword', 'tos']); - $postData = array('User' => array( + $postData = ['User' => [ 'username' => 'validusername', 'email' => 'test@test.com', 'password' => '12345', 'temppassword' => '12345', - 'tos' => 1)); + 'tos' => 1]]; $result = $this->User->register($postData); $this->assertFalse($result); - $this->assertEquals(array_keys($this->User->invalidFields()), array( - 'password')); + $this->assertEquals(array_keys($this->User->invalidFields()), [ + 'password']); - $postData = array('User' => array( + $postData = ['User' => [ 'username' => ' ', 'email' => 'test@test.com', 'password' => '123456', 'temppassword' => '123456', - 'tos' => 1)); + 'tos' => 1]]; $result = $this->User->register($postData); $this->assertFalse($result); - $this->assertEquals(array_keys($this->User->invalidFields()), array( - 'username')); + $this->assertEquals(array_keys($this->User->invalidFields()), [ + 'username']); - $postData = array('User' => array( + $postData = ['User' => [ 'username' => ' ', 'email' => 'test@test.com', 'password' => '123456', 'temppassword' => '123456', - 'tos' => 1)); + 'tos' => 1]]; $result = $this->User->register($postData); $this->assertFalse($result); - $this->assertEquals(array_keys($this->User->invalidFields()), array( - 'username')); + $this->assertEquals(array_keys($this->User->invalidFields()), [ + 'username']); - $postData = array('User' => array( + $postData = ['User' => [ 'username' => 'imanewuser', 'email' => 'foo@bar.com', 'password' => 'password', 'temppassword' => 'password', - 'tos' => 1)); - $result = $this->User->register($postData, array('returnData' => false)); + 'tos' => 1]]; + $result = $this->User->register($postData, ['returnData' => false]); $this->assertTrue($result); $result = $this->User->data; @@ -302,33 +301,33 @@ public function testRegister() { * @return void */ public function testChangePassword() { - $postData = array(); + $postData = []; $result = $this->User->changePassword($postData); $this->assertFalse($result); - $postData = array( - 'User' => array( + $postData = [ + 'User' => [ 'id' => 1, 'old_password' => 'test', 'new_password' => 'not', - 'confirm_password' => 'equal')); + 'confirm_password' => 'equal']]; $result = $this->User->changePassword($postData); $this->assertFalse($result); - $this->assertEquals(array('new_password', 'confirm_password'), array_keys($this->User->invalidFields())); + $this->assertEquals(['new_password', 'confirm_password'], array_keys($this->User->invalidFields())); - $postData = array( - 'User' => array( + $postData = [ + 'User' => [ 'id' => 1, 'old_password' => 'test', 'new_password' => 'testtest', - 'confirm_password' => 'testtest')); + 'confirm_password' => 'testtest']]; $result = $this->User->changePassword($postData); $this->assertTrue($result); - $ressult = $this->User->find('first', array( + $ressult = $this->User->find('first', [ 'recursive' => -1, - 'conditions' => array( - 'User.id' => 1))); + 'conditions' => [ + 'User.id' => 1]]); $this->assertEquals($ressult['User']['password'], $this->User->hash('testtest', null, true)); } @@ -338,16 +337,16 @@ public function testChangePassword() { * @return void */ public function testCompareFields() { - $this->User->data = array( - 'User' => array( + $this->User->data = [ + 'User' => [ 'field1' => 'foo', - 'field2' => 'bar')); + 'field2' => 'bar']]; $this->assertFalse($this->User->compareFields('field1', 'field2')); - $this->User->data = array( - 'User' => array( + $this->User->data = [ + 'User' => [ 'field1' => 'foo', - 'field2' => 'foo')); + 'field2' => 'foo']]; $this->assertTrue($this->User->compareFields('field1', 'field2')); } @@ -357,23 +356,23 @@ public function testCompareFields() { * @return void */ public function testResendVerification() { - $postData = array( - 'User' => array()); + $postData = [ + 'User' => []]; $this->assertFalse($this->User->resendVerification($postData)); - $postData = array( - 'User' => array( - 'email' => 'doesnotexist!')); + $postData = [ + 'User' => [ + 'email' => 'doesnotexist!']]; $this->assertFalse($this->User->resendVerification($postData)); - $postData = array( - 'User' => array( - 'email' => 'adminuser@cakedc.com')); + $postData = [ + 'User' => [ + 'email' => 'adminuser@cakedc.com']]; $this->assertFalse($this->User->resendVerification($postData)); - $postData = array( - 'User' => array( - 'email' => 'oidtest2@testuser.com')); + $postData = [ + 'User' => [ + 'email' => 'oidtest2@testuser.com']]; $result = $this->User->resendVerification($postData); $this->assertTrue(is_array($result)); } @@ -411,13 +410,13 @@ public function testDelete() { * @return void */ public function testAdd() { - $postData = array( - 'User' => array( + $postData = [ + 'User' => [ 'username' => 'newusername', 'email' => 'newusername@newusername.com', 'password' => 'password', 'temppassword' => 'password', - 'tos' => 1)); + 'tos' => 1]]; $result = $this->User->add($postData); $this->assertTrue($result); } @@ -505,8 +504,8 @@ public function testDisableSlugs() { ClassRegistry::flush(); $this->User = ClassRegistry::init('Users.User'); $this->User->create(); - $this->User->save(array( - 'username' => 'foo2'), array('validate' => false)); + $this->User->save([ + 'username' => 'foo2'], ['validate' => false]); $result = $this->User->read(null, $this->User->id); $this->assertEquals($result['User']['slug'], 'foo2'); @@ -514,8 +513,8 @@ public function testDisableSlugs() { Configure::write('Users.disableSlugs', true); $this->User = ClassRegistry::init('Users.User'); $this->User->create(); - $this->User->save(array( - 'username' => 'bar2'), array('validate' => false)); + $this->User->save([ + 'username' => 'bar2'], ['validate' => false]); $result = $this->User->read(null, $this->User->id); $this->assertTrue(empty($result['User']['slug'])); } diff --git a/Test/Fixture/MultiUserFixture.php b/Test/Fixture/MultiUserFixture.php index 230ecb2fe..dd54bc83e 100644 --- a/Test/Fixture/MultiUserFixture.php +++ b/Test/Fixture/MultiUserFixture.php @@ -1,38 +1,39 @@ - array('type' => 'integer', 'key' => 'primary'), - 'user' => array('type' => 'string', 'null' => false), - 'email' => array('type' => 'string', 'null' => false), - 'password' => array('type' => 'string', 'null' => false), - 'token' => array('type' => 'string', 'null' => false), - 'created' => 'datetime', - 'updated' => 'datetime' - ); - -/** - * records property - * - * @var array - */ - public $records = array( - array('user' => 'mariano', 'email' => 'mariano@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '12345', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), - array('user' => 'nate', 'email' => 'nate@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '23456', 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31'), - array('user' => 'larry', 'email' => 'larry@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '34567', 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31'), - array('user' => 'garrett', 'email' => 'garrett@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '45678', 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31'), - array('user' => 'chartjes', 'email' => 'chartjes@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '56789', 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31'), - ); -} + ['type' => 'integer', 'key' => 'primary'], + 'user' => ['type' => 'string', 'null' => false], + 'email' => ['type' => 'string', 'null' => false], + 'password' => ['type' => 'string', 'null' => false], + 'token' => ['type' => 'string', 'null' => false], + 'created' => 'datetime', + 'updated' => 'datetime' + ]; + +/** + * records property + * + * @var array + */ + public $records = [ + ['user' => 'mariano', 'email' => 'mariano@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '12345', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'], + ['user' => 'nate', 'email' => 'nate@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '23456', 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31'], + ['user' => 'larry', 'email' => 'larry@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '34567', 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31'], + ['user' => 'garrett', 'email' => 'garrett@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '45678', 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31'], + ['user' => 'chartjes', 'email' => 'chartjes@example.com', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'token' => '56789', 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31'], + ]; +} diff --git a/Test/Fixture/UserFixture.php b/Test/Fixture/UserFixture.php index 838df1cd2..49b172ee1 100644 --- a/Test/Fixture/UserFixture.php +++ b/Test/Fixture/UserFixture.php @@ -1,11 +1,11 @@ array('type' => 'string', 'null' => false, 'length' => 36, 'key' => 'primary'), - 'username' => array('type' => 'string', 'null' => false, 'default' => null), - 'slug' => array('type' => 'string', 'null' => false, 'default' => null), - 'password' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 128), - 'password_token' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 128), - 'email' => array('type' => 'string', 'null' => true, 'default' => null), - 'email_verified' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'email_token' => array('type' => 'string', 'null' => true, 'default' => null), - 'email_token_expires' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'tos' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'active' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'last_action' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'last_login' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'is_admin' => array('type' => 'boolean', 'null' => true, 'default' => '0'), - 'role' => array('type' => 'string', 'null' => true, 'default' => null), - 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'modified' => array('type' => 'datetime', 'null' => true, 'default' => null), - 'indexes' => array( - 'PRIMARY' => array('column' => 'id', 'unique' => 1)) - ); + public $fields = [ + 'id' => ['type' => 'string', 'null' => false, 'length' => 36, 'key' => 'primary'], + 'username' => ['type' => 'string', 'null' => false, 'default' => null], + 'slug' => ['type' => 'string', 'null' => false, 'default' => null], + 'password' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 128], + 'password_token' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 128], + 'email' => ['type' => 'string', 'null' => true, 'default' => null], + 'email_verified' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'email_token' => ['type' => 'string', 'null' => true, 'default' => null], + 'email_token_expires' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'tos' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'active' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'last_action' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'last_login' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'is_admin' => ['type' => 'boolean', 'null' => true, 'default' => '0'], + 'role' => ['type' => 'string', 'null' => true, 'default' => null], + 'created' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'modified' => ['type' => 'datetime', 'null' => true, 'default' => null], + 'indexes' => [ + 'PRIMARY' => ['column' => 'id', 'unique' => 1]] + ]; /** * Records * * @var array */ - public $records = array( - array( + public $records = [ + [ 'id' => '1', 'username' => 'adminuser', 'slug' => 'adminuser', @@ -82,8 +82,8 @@ class UserFixture extends CakeTestFixture { 'role' => 'admin', 'created' => '2008-03-25 02:45:46', 'modified' => '2008-03-25 02:45:46' - ), - array( + ], + [ 'id' => '47ea303a-3cyc-k251-b313-4811c0a800bf', 'username' => 'testuser', 'slug' => 'testuser', @@ -101,8 +101,8 @@ class UserFixture extends CakeTestFixture { 'role' => 'user', 'created' => '2008-03-25 02:45:46', 'modified' => '2008-03-25 02:45:46' - ), - array( + ], + [ 'id' => '37ea303a-3bdc-4251-b315-1316c0b300fa', 'username' => 'user1', 'slug' => 'user1', @@ -120,8 +120,8 @@ class UserFixture extends CakeTestFixture { 'role' => 'user', 'created' => '2008-03-25 02:45:46', 'modified' => '2008-03-25 02:45:46' - ), - array( + ], + [ 'id' => '495e36a2-1f00-46b9-8247-58a367265f11', 'username' => 'oidtest', 'slug' => 'oistest', @@ -139,8 +139,8 @@ class UserFixture extends CakeTestFixture { 'role' => 'user', 'created' => '2008-03-25 02:45:46', 'modified' => '2008-03-25 02:45:46' - ), - array( + ], + [ 'id' => '315e36a2-1fxj-46b9-8247-58a367265f11', 'username' => 'oidtest2', 'slug' => 'oistest', @@ -158,8 +158,8 @@ class UserFixture extends CakeTestFixture { 'role' => 'user', 'created' => '2008-03-25 02:45:46', 'modified' => '2008-03-25 02:45:46' - ), - array( + ], + [ 'id' => '515e36a2-5fjj-46b9-8247-584367265f11', 'username' => 'resetuser', 'slug' => 'resetuser', @@ -177,8 +177,8 @@ class UserFixture extends CakeTestFixture { 'role' => 'user', 'created' => '2008-03-25 02:45:46', 'modified' => '2008-03-25 02:45:46' - ) - ); + ] + ]; /** * Constructor diff --git a/View/Elements/Users/admin_sidebar.ctp b/View/Elements/Users/admin_sidebar.ctp index fb93c0c38..7cc38731f 100644 --- a/View/Elements/Users/admin_sidebar.ctp +++ b/View/Elements/Users/admin_sidebar.ctp @@ -1,11 +1,11 @@
    -
  • Html->link(__d('users', 'Logout'), array('admin' => false, 'action' => 'logout')); ?> -
  • Html->link(__d('users', 'My Account'), array('admin' => false, 'action' => 'edit')); ?> +
  • Html->link(__d('users', 'Logout'), ['admin' => false, 'action' => 'logout']); ?> +
  • Html->link(__d('users', 'My Account'), ['admin' => false, 'action' => 'edit']); ?>
  •  
  • -
  • Html->link(__d('users', 'Add Users'), array('admin' => true, 'action'=>'add'));?>
  • -
  • Html->link(__d('users', 'List Users'), array('admin' => true, 'action'=>'index'));?>
  • +
  • Html->link(__d('users', 'Add Users'), ['admin' => true, 'action'=>'add']);?>
  • +
  • Html->link(__d('users', 'List Users'), ['admin' => true, 'action'=>'index']);?>
  •  
  • -
  • Html->link(__d('users', 'Frontend'), array('admin' => false, 'action'=>'index')); ?>
  • +
  • Html->link(__d('users', 'Frontend'), ['admin' => false, 'action'=>'index']); ?>
\ No newline at end of file diff --git a/View/Elements/Users/sidebar.ctp b/View/Elements/Users/sidebar.ctp index 68bc08a98..550b9d72a 100644 --- a/View/Elements/Users/sidebar.ctp +++ b/View/Elements/Users/sidebar.ctp @@ -1,18 +1,18 @@
    Session->read('Auth.User.id')) : ?> -
  • Html->link(__d('users', 'Login'), array('plugin' => 'users', 'controller' => 'users', 'action' => 'login')); ?>
  • +
  • Html->link(__d('users', 'Login'), ['plugin' => 'users', 'controller' => 'users', 'action' => 'login']); ?>
  • -
  • Html->link(__d('users', 'Register an account'), array('plugin' => 'users', 'controller' => 'users', 'action' => 'add')); ?>
  • +
  • Html->link(__d('users', 'Register an account'), ['plugin' => 'users', 'controller' => 'users', 'action' => 'add']); ?>
  • -
  • Html->link(__d('users', 'Logout'), array('plugin' => 'users', 'controller' => 'users', 'action' => 'logout')); ?> -
  • Html->link(__d('users', 'My Account'), array('plugin' => 'users', 'controller' => 'users', 'action' => 'edit')); ?> -
  • Html->link(__d('users', 'Change password'), array('plugin' => 'users', 'controller' => 'users', 'action' => 'change_password')); ?> +
  • Html->link(__d('users', 'Logout'), ['plugin' => 'users', 'controller' => 'users', 'action' => 'logout']); ?> +
  • Html->link(__d('users', 'My Account'), ['plugin' => 'users', 'controller' => 'users', 'action' => 'edit']); ?> +
  • Html->link(__d('users', 'Change password'), ['plugin' => 'users', 'controller' => 'users', 'action' => 'change_password']); ?> Session->read('Auth.User.is_admin')) : ?>
  •  
  • -
  • Html->link(__d('users', 'List Users'), array('plugin' => 'users', 'controller' => 'users', 'action' => 'index'));?>
  • +
  • Html->link(__d('users', 'List Users'), ['plugin' => 'users', 'controller' => 'users', 'action' => 'index']);?>
diff --git a/View/Elements/pagination.ctp b/View/Elements/pagination.ctp index ca280b6ab..231984a5c 100644 --- a/View/Elements/pagination.ctp +++ b/View/Elements/pagination.ctp @@ -1,18 +1,18 @@
Paginator->prev('< ' . __d('users', 'previous'), array(), null, array('class' => 'prev disabled')); - echo $this->Paginator->numbers(array('separator' => '')); - echo $this->Paginator->next(__d('users', 'next') . ' >', array(), null, array('class' => 'next disabled')); + echo $this->Paginator->prev('< ' . __d('users', 'previous'), [], null, ['class' => 'prev disabled']); + echo $this->Paginator->numbers(['separator' => '']); + echo $this->Paginator->next(__d('users', 'next') . ' >', [], null, ['class' => 'next disabled']); ?>
diff --git a/View/Elements/paging.ctp b/View/Elements/paging.ctp index 477e734dc..d3448eb00 100644 --- a/View/Elements/paging.ctp +++ b/View/Elements/paging.ctp @@ -1,4 +1,3 @@ Paginator->counter(array( - 'format' => 'Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%')); -?> \ No newline at end of file + echo $this->Paginator->counter([ + 'format' => 'Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%']); \ No newline at end of file diff --git a/View/Emails/text/account_verification.ctp b/View/Emails/text/account_verification.ctp index e884215e5..fd2503e9f 100644 --- a/View/Emails/text/account_verification.ctp +++ b/View/Emails/text/account_verification.ctp @@ -1,11 +1,11 @@ false, 'plugin' => 'users', 'controller' => 'users', 'action' => 'verify', 'email', $user[$model]['email_token']), true); +echo Router::url(['admin' => false, 'plugin' => 'users', 'controller' => 'users', 'action' => 'verify', 'email', $user[$model]['email_token']], true); diff --git a/View/Emails/text/new_password.ctp b/View/Emails/text/new_password.ctp index 08f9571e7..164f9c11e 100644 --- a/View/Emails/text/new_password.ctp +++ b/View/Emails/text/new_password.ctp @@ -1,11 +1,11 @@ false, 'plugin' => 'users', 'controller' => 'users', 'action' => 'reset_password', $token), true); +echo Router::url(['admin' => false, 'plugin' => 'users', 'controller' => 'users', 'action' => 'reset_password', $token], true); diff --git a/View/Users/add.ctp b/View/Users/add.ctp index c736d7d5c..66fbaa02e 100644 --- a/View/Users/add.ctp +++ b/View/Users/add.ctp @@ -1,11 +1,11 @@ @@ -14,21 +14,21 @@
Form->create($model); - echo $this->Form->input('username', array( - 'label' => __d('users', 'Username'))); - echo $this->Form->input('email', array( + echo $this->Form->input('username', [ + 'label' => __d('users', 'Username')]); + echo $this->Form->input('email', [ 'label' => __d('users', 'E-mail (used as login)'), - 'error' => array('isValid' => __d('users', 'Must be a valid email address'), - 'isUnique' => __d('users', 'An account with that email already exists')))); - echo $this->Form->input('password', array( + 'error' => ['isValid' => __d('users', 'Must be a valid email address'), + 'isUnique' => __d('users', 'An account with that email already exists')]]); + echo $this->Form->input('password', [ 'label' => __d('users', 'Password'), - 'type' => 'password')); - echo $this->Form->input('temppassword', array( + 'type' => 'password']); + echo $this->Form->input('temppassword', [ 'label' => __d('users', 'Password (confirm)'), - 'type' => 'password')); - $tosLink = $this->Html->link(__d('users', 'Terms of Service'), array('controller' => 'pages', 'action' => 'tos', 'plugin' => null)); - echo $this->Form->input('tos', array( - 'label' => __d('users', 'I have read and agreed to ') . $tosLink)); + 'type' => 'password']); + $tosLink = $this->Html->link(__d('users', 'Terms of Service'), ['controller' => 'pages', 'action' => 'tos', 'plugin' => null]); + echo $this->Form->input('tos', [ + 'label' => __d('users', 'I have read and agreed to ') . $tosLink]); echo $this->Form->end(__d('users', 'Submit')); ?>
diff --git a/View/Users/admin_add.ctp b/View/Users/admin_add.ctp index 8b0efff4e..07d6db50e 100644 --- a/View/Users/admin_add.ctp +++ b/View/Users/admin_add.ctp @@ -1,11 +1,11 @@ @@ -14,26 +14,26 @@
Form->input('username', array( - 'label' => __d('users', 'Username'))); - echo $this->Form->input('email', array( + echo $this->Form->input('username', [ + 'label' => __d('users', 'Username')]); + echo $this->Form->input('email', [ 'label' => __d('users', 'E-mail (used as login)'), - 'error' => array('isValid' => __d('users', 'Must be a valid email address'), - 'isUnique' => __d('users', 'An account with that email already exists')))); - echo $this->Form->input('password', array( + 'error' => ['isValid' => __d('users', 'Must be a valid email address'), + 'isUnique' => __d('users', 'An account with that email already exists')]]); + echo $this->Form->input('password', [ 'label' => __d('users', 'Password'), - 'type' => 'password')); - echo $this->Form->input('temppassword', array( + 'type' => 'password']); + echo $this->Form->input('temppassword', [ 'label' => __d('users', 'Password (confirm)'), - 'type' => 'password')); + 'type' => 'password']); if (!empty($roles)) { - echo $this->Form->input('role', array( - 'label' => __d('users', 'Role'), 'values' => $roles)); + echo $this->Form->input('role', [ + 'label' => __d('users', 'Role'), 'values' => $roles]); } - echo $this->Form->input('is_admin', array( - 'label' => __d('users', 'Is Admin'))); - echo $this->Form->input('active', array( - 'label' => __d('users', 'Active'))); + echo $this->Form->input('is_admin', [ + 'label' => __d('users', 'Is Admin')]); + echo $this->Form->input('active', [ + 'label' => __d('users', 'Active')]); ?>
Form->end('Submit'); ?> diff --git a/View/Users/admin_edit.ctp b/View/Users/admin_edit.ctp index 02cd058ca..17e1ef46d 100644 --- a/View/Users/admin_edit.ctp +++ b/View/Users/admin_edit.ctp @@ -1,11 +1,11 @@ @@ -15,18 +15,18 @@ Form->input('id'); - echo $this->Form->input('username', array( - 'label' => __d('users', 'Username'))); - echo $this->Form->input('email', array( - 'label' => __d('users', 'Email'))); + echo $this->Form->input('username', [ + 'label' => __d('users', 'Username')]); + echo $this->Form->input('email', [ + 'label' => __d('users', 'Email')]); if (!empty($roles)) { - echo $this->Form->input('role', array( - 'label' => __d('users', 'Role'), 'values' => $roles)); + echo $this->Form->input('role', [ + 'label' => __d('users', 'Role'), 'values' => $roles]); } - echo $this->Form->input('is_admin', array( - 'label' => __d('users', 'Is Admin'))); - echo $this->Form->input('active', array( - 'label' => __d('users', 'Active'))); + echo $this->Form->input('is_admin', [ + 'label' => __d('users', 'Is Admin')]); + echo $this->Form->input('active', [ + 'label' => __d('users', 'Active')]); ?> Form->end('Submit'); ?> diff --git a/View/Users/admin_index.ctp b/View/Users/admin_index.ctp index b89b567c2..5f79534b9 100644 --- a/View/Users/admin_index.ctp +++ b/View/Users/admin_index.ctp @@ -1,11 +1,11 @@ @@ -15,9 +15,9 @@ ' . __d('users', 'Filter') . ''; - echo $this->Form->create($model, array('action' => 'index')); - echo $this->Form->input('username', array('label' => __d('users', 'Username'))); - echo $this->Form->input('email', array('label' => __d('users', 'Email'))); + echo $this->Form->create($model, ['action' => 'index']); + echo $this->Form->input('username', ['label' => __d('users', 'Username')]); + echo $this->Form->input('email', ['label' => __d('users', 'Email')]); echo $this->Form->end(__d('users', 'Search')); } ?> @@ -58,9 +58,9 @@ - Html->link(__d('users', 'View'), array('action' => 'view', $user[$model]['id'])); ?> - Html->link(__d('users', 'Edit'), array('action' => 'edit', $user[$model]['id'])); ?> - Html->link(__d('users', 'Delete'), array('action' => 'delete', $user[$model]['id']), null, sprintf(__d('users', 'Are you sure you want to delete # %s?'), $user[$model]['id'])); ?> + Html->link(__d('users', 'View'), ['action' => 'view', $user[$model]['id']]); ?> + Html->link(__d('users', 'Edit'), ['action' => 'edit', $user[$model]['id']]); ?> + Html->link(__d('users', 'Delete'), ['action' => 'delete', $user[$model]['id']], null, sprintf(__d('users', 'Are you sure you want to delete # %s?'), $user[$model]['id'])); ?> diff --git a/View/Users/admin_view.ctp b/View/Users/admin_view.ctp index 8960a41ba..1d0521b11 100644 --- a/View/Users/admin_view.ctp +++ b/View/Users/admin_view.ctp @@ -1,11 +1,11 @@ diff --git a/View/Users/change_password.ctp b/View/Users/change_password.ctp index 3817a0532..588cf6eb8 100644 --- a/View/Users/change_password.ctp +++ b/View/Users/change_password.ctp @@ -1,11 +1,11 @@ @@ -13,16 +13,16 @@

Form->create($model, array('action' => 'change_password')); - echo $this->Form->input('old_password', array( + echo $this->Form->create($model, ['action' => 'change_password']); + echo $this->Form->input('old_password', [ 'label' => __d('users', 'Old Password'), - 'type' => 'password')); - echo $this->Form->input('new_password', array( + 'type' => 'password']); + echo $this->Form->input('new_password', [ 'label' => __d('users', 'New Password'), - 'type' => 'password')); - echo $this->Form->input('confirm_password', array( + 'type' => 'password']); + echo $this->Form->input('confirm_password', [ 'label' => __d('users', 'Confirm'), - 'type' => 'password')); + 'type' => 'password']); echo $this->Form->end(__d('users', 'Submit')); ?> diff --git a/View/Users/dashboard.ctp b/View/Users/dashboard.ctp index 41cccf50b..33a7346d2 100644 --- a/View/Users/dashboard.ctp +++ b/View/Users/dashboard.ctp @@ -1,11 +1,11 @@ diff --git a/View/Users/edit.ctp b/View/Users/edit.ctp index cc929de0b..ca6858649 100644 --- a/View/Users/edit.ctp +++ b/View/Users/edit.ctp @@ -1,11 +1,11 @@ @@ -14,7 +14,7 @@

- Html->link(__d('users', 'Change your password'), array('action' => 'change_password')); ?> + Html->link(__d('users', 'Change your password'), ['action' => 'change_password']); ?>

Form->end(__d('users', 'Submit')); ?> diff --git a/View/Users/index.ctp b/View/Users/index.ctp index 82116ca27..4c5ea809a 100644 --- a/View/Users/index.ctp +++ b/View/Users/index.ctp @@ -1,11 +1,11 @@ @@ -13,9 +13,9 @@

Paginator->counter(array( + echo $this->Paginator->counter([ 'format' => __d('users', 'Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%') - )); + ]); ?>

@@ -33,10 +33,10 @@ endif; ?> > - + diff --git a/View/Users/login.ctp b/View/Users/login.ctp index f6fde0dcc..d86d4e109 100644 --- a/View/Users/login.ctp +++ b/View/Users/login.ctp @@ -1,31 +1,31 @@

- Session->flash('auth');?> + Flash->render('auth');?>
Form->create($model, array( - 'id' => 'LoginForm')); - echo $this->Form->input('email', array( - 'label' => __d('users', 'Email'))); - echo $this->Form->input('password', array( - 'label' => __d('users', 'Password'))); + echo $this->Form->create($model, [ + 'id' => 'LoginForm']); + echo $this->Form->input('email', [ + 'label' => __d('users', 'Email')]); + echo $this->Form->input('password', [ + 'label' => __d('users', 'Password')]); - echo '

' . $this->Form->input('remember_me', array('type' => 'checkbox', 'label' => __d('users', 'Remember Me'))) . '

'; - echo '

' . $this->Html->link(__d('users', 'I forgot my password'), array('action' => 'reset_password')) . '

'; + echo '

' . $this->Form->input('remember_me', ['type' => 'checkbox', 'label' => __d('users', 'Remember Me')]) . '

'; + echo '

' . $this->Html->link(__d('users', 'I forgot my password'), ['action' => 'reset_password']) . '

'; - echo $this->Form->hidden('User.return_to', array( - 'value' => $return_to)); + echo $this->Form->hidden('User.return_to', [ + 'value' => $return_to]); echo $this->Form->end(__d('users', 'Submit')); ?>
diff --git a/View/Users/request_password_change.ctp b/View/Users/request_password_change.ctp index a62b0a3d2..dd783b37c 100644 --- a/View/Users/request_password_change.ctp +++ b/View/Users/request_password_change.ctp @@ -1,11 +1,11 @@ @@ -13,12 +13,12 @@

Form->create($model, array( - 'url' => array( + echo $this->Form->create($model, [ + 'url' => [ 'admin' => false, - 'action' => 'reset_password'))); - echo $this->Form->input('email', array( - 'label' => __d('users', 'Your Email'))); + 'action' => 'reset_password']]); + echo $this->Form->input('email', [ + 'label' => __d('users', 'Your Email')]); echo $this->Form->submit(__d('users', 'Submit')); echo $this->Form->end(); ?> diff --git a/View/Users/resend_verification.ctp b/View/Users/resend_verification.ctp index cfa55f022..147d2cee7 100644 --- a/View/Users/resend_verification.ctp +++ b/View/Users/resend_verification.ctp @@ -1,11 +1,11 @@ @@ -13,12 +13,12 @@

Form->create($model, array( - 'url' => array( + echo $this->Form->create($model, [ + 'url' => [ 'admin' => false, - 'action' => 'resend_verification'))); - echo $this->Form->input('email', array( - 'label' => __d('users', 'Your Email'))); + 'action' => 'resend_verification']]); + echo $this->Form->input('email', [ + 'label' => __d('users', 'Your Email')]); echo $this->Form->submit(__d('users', 'Submit')); echo $this->Form->end(); ?> diff --git a/View/Users/reset_password.ctp b/View/Users/reset_password.ctp index 325a2aa1b..01f4e89be 100644 --- a/View/Users/reset_password.ctp +++ b/View/Users/reset_password.ctp @@ -1,16 +1,16 @@

Form->create($model, array( - 'url' => array( + echo $this->Form->create($model, [ + 'url' => [ 'action' => 'reset_password', - $token))); - echo $this->Form->input('new_password', array( + $token]]); + echo $this->Form->input('new_password', [ 'label' => __d('users', 'New Password'), - 'type' => 'password')); - echo $this->Form->input('confirm_password', array( + 'type' => 'password']); + echo $this->Form->input('confirm_password', [ 'label' => __d('users', 'Confirm'), - 'type' => 'password')); + 'type' => 'password']); echo $this->Form->submit(__d('users', 'Submit')); echo $this->Form->end(); ?> diff --git a/View/Users/search.ctp b/View/Users/search.ctp index 4e10d788e..1a7bce6d7 100644 --- a/View/Users/search.ctp +++ b/View/Users/search.ctp @@ -1,31 +1,31 @@

Form->create($model, array( - 'action' => 'search')); - echo $this->Form->input('username', array( - 'label' => __d('users', 'Username'))); - echo $this->Form->input('email', array( - 'label' => __d('users', 'Email'))); - echo $this->Form->input('Profile.name', array( - 'label' => __d('users', 'Name'))); + echo $this->Form->create($model, [ + 'action' => 'search']); + echo $this->Form->input('username', [ + 'label' => __d('users', 'Username')]); + echo $this->Form->input('email', [ + 'label' => __d('users', 'Email')]); + echo $this->Form->input('Profile.name', [ + 'label' => __d('users', 'Name')]); echo $this->Form->end(__d('users', 'Search')); ?>

Paginator->counter(array( + echo $this->Paginator->counter([ 'format' => __d('users', 'Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%') - )); + ]); ?>

Html->link($user[$model]['username'], array('action' => 'view', $user[$model]['id'])); ?>Html->link($user[$model]['username'], ['action' => 'view', $user[$model]['id']]); ?> - Html->link(__d('users', 'View'), array('action' => 'view', $user[$model]['id'])); ?> + Html->link(__d('users', 'View'), ['action' => 'view', $user[$model]['id']]); ?>
@@ -46,11 +46,11 @@
- Html->link(__d('users', 'View'), array('action' => 'view', $user[$model]['id'])); ?> - Html->link(__d('users', 'Edit'), array('action' => 'edit', $user[$model]['id'])); ?> + Html->link(__d('users', 'View'), ['action' => 'view', $user[$model]['id']]); ?> + Html->link(__d('users', 'Edit'), ['action' => 'edit', $user[$model]['id']]); ?> Html->link( __d('users', 'Delete'), - array('action' => 'delete', $user[$model]['id']), + ['action' => 'delete', $user[$model]['id']], null, sprintf(__d('users', 'Are you sure you want to delete # %s?'), $user[$model]['id']) ); ?> diff --git a/View/Users/view.ctp b/View/Users/view.ctp index c80f27152..49ab5d2d9 100644 --- a/View/Users/view.ctp +++ b/View/Users/view.ctp @@ -1,11 +1,11 @@ diff --git a/composer.json b/composer.json index 994be689f..1868aa702 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,8 @@ "source": "https://github.com/CakeDC/users" }, "require": { - "php": ">=5.2.8", + "php": ">=5.6.0", + "cakephp/cakephp": "^2.10", "composer/installers": "*" }, "suggest": {