diff --git a/CHANGES.md b/CHANGES.md index eff759a..0c08075 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -65,9 +65,9 @@ - email => emailFrom - name => emailFromName - email_config => emailConfig - - admin_group => adminGroup - - default_group => defaultGroup - - public_group => publicGroup + - admin_group => groupAdmin + - default_group => groupDefault + - public_group => groupPublic - db_profile => dbProfile - users => dbTableUsers - user_variables => dbTableUserVariables diff --git a/app/Config/Aauth.php b/app/Config/Aauth.php index 3826fcb..f7106f3 100644 --- a/app/Config/Aauth.php +++ b/app/Config/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -244,24 +244,24 @@ class Aauth extends BaseConfig | Group Variables |-------------------------------------------------------------------------- | - | 'adminGroup' + | 'groupAdmin' | | Name of admin group | (default: 'admin') | - | 'defaultGroup' + | 'groupDefault' | | Name of default group, the new user is added in it | (default: 'default') | - | 'publicGroup' + | 'groupPublic' | | Name of Public group , people who not logged in | (default: 'public') */ - public $adminGroup = 'admin'; - public $defaultGroup = 'default'; - public $publicGroup = 'public'; + public $groupAdmin = 'admin'; + public $groupDefault = 'default'; + public $groupPublic = 'public'; /* |-------------------------------------------------------------------------- diff --git a/app/Controllers/Account/Edit.php b/app/Controllers/Account/Edit.php index 6328e48..825691c 100644 --- a/app/Controllers/Account/Edit.php +++ b/app/Controllers/Account/Edit.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Home.php b/app/Controllers/Account/Home.php index 37ffa22..ee31300 100644 --- a/app/Controllers/Account/Home.php +++ b/app/Controllers/Account/Home.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Login.php b/app/Controllers/Account/Login.php index 53cd832..0d2cd24 100644 --- a/app/Controllers/Account/Login.php +++ b/app/Controllers/Account/Login.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Logout.php b/app/Controllers/Account/Logout.php index 2921b7c..4260439 100644 --- a/app/Controllers/Account/Logout.php +++ b/app/Controllers/Account/Logout.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Register.php b/app/Controllers/Account/Register.php index 05eb2e2..0badbd5 100644 --- a/app/Controllers/Account/Register.php +++ b/app/Controllers/Account/Register.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Remind_password.php b/app/Controllers/Account/Remind_password.php index cf1ddc7..0e52f74 100644 --- a/app/Controllers/Account/Remind_password.php +++ b/app/Controllers/Account/Remind_password.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Reset_password.php b/app/Controllers/Account/Reset_password.php index 4f2d60d..916cbf4 100644 --- a/app/Controllers/Account/Reset_password.php +++ b/app/Controllers/Account/Reset_password.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Account/Verification.php b/app/Controllers/Account/Verification.php index 40935c3..abdb334 100644 --- a/app/Controllers/Account/Verification.php +++ b/app/Controllers/Account/Verification.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Admin/Home.php b/app/Controllers/Admin/Home.php index d5fbf8d..2397502 100644 --- a/app/Controllers/Admin/Home.php +++ b/app/Controllers/Admin/Home.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -18,7 +18,6 @@ namespace App\Controllers\Admin; use CodeIgniter\Controller; -use Config\Aauth as AauthConfig; /** * Aauth Admin/Home Controller diff --git a/app/Controllers/Admin/Migrate.php b/app/Controllers/Admin/Migrate.php index 877afbd..82c2815 100644 --- a/app/Controllers/Admin/Migrate.php +++ b/app/Controllers/Admin/Migrate.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Admin/Users.php b/app/Controllers/Admin/Users.php index 59bd259..f05c920 100644 --- a/app/Controllers/Admin/Users.php +++ b/app/Controllers/Admin/Users.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php index daa5e8b..5b4919b 100644 --- a/app/Controllers/Home.php +++ b/app/Controllers/Home.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -18,7 +18,6 @@ namespace App\Controllers; use CodeIgniter\Controller; -use Config\Aauth as AauthConfig; /** * Aauth Home Controller diff --git a/app/Database/Migrations/20181026042034_create_ci_sessions_table.php b/app/Database/Migrations/20181026042034_create_ci_sessions_table.php index fa42915..c2bd162 100644 --- a/app/Database/Migrations/20181026042034_create_ci_sessions_table.php +++ b/app/Database/Migrations/20181026042034_create_ci_sessions_table.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181026110732_create_users_table.php b/app/Database/Migrations/20181026110732_create_users_table.php index b29c14b..92fd396 100644 --- a/app/Database/Migrations/20181026110732_create_users_table.php +++ b/app/Database/Migrations/20181026110732_create_users_table.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181031062503_create_user_variables.php b/app/Database/Migrations/20181031062503_create_user_variables.php index 766d4cc..f35ab08 100644 --- a/app/Database/Migrations/20181031062503_create_user_variables.php +++ b/app/Database/Migrations/20181031062503_create_user_variables.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181031063113_create_login_attempts.php b/app/Database/Migrations/20181031063113_create_login_attempts.php index e685870..1fa83f2 100644 --- a/app/Database/Migrations/20181031063113_create_login_attempts.php +++ b/app/Database/Migrations/20181031063113_create_login_attempts.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181031063642_create_login_tokens.php b/app/Database/Migrations/20181031063642_create_login_tokens.php index e2fe934..c27deb6 100644 --- a/app/Database/Migrations/20181031063642_create_login_tokens.php +++ b/app/Database/Migrations/20181031063642_create_login_tokens.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181031064211_create_groups.php b/app/Database/Migrations/20181031064211_create_groups.php index e08acc7..d247e64 100644 --- a/app/Database/Migrations/20181031064211_create_groups.php +++ b/app/Database/Migrations/20181031064211_create_groups.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -53,6 +53,11 @@ class Migration_create_groups extends Migration ], 'created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP', 'updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP', + 'deleted' => [ + 'type' => 'TINYINT', + 'constraint' => 1, + 'default' => 0, + ], ]); $this->forge->addKey('id', true); $this->forge->createTable($config->dbTableGroups, true); diff --git a/app/Database/Migrations/20181031064431_create_group_to_user.php b/app/Database/Migrations/20181031064431_create_group_to_user.php index d6b83c1..98276e3 100644 --- a/app/Database/Migrations/20181031064431_create_group_to_user.php +++ b/app/Database/Migrations/20181031064431_create_group_to_user.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181031064550_create_group_to_group.php b/app/Database/Migrations/20181031064550_create_group_to_group.php index 2f1cfb9..f8e3830 100644 --- a/app/Database/Migrations/20181031064550_create_group_to_group.php +++ b/app/Database/Migrations/20181031064550_create_group_to_group.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Database/Migrations/20181031064714_create_perms.php b/app/Database/Migrations/20181031064714_create_perms.php index eeaccf5..65a74a2 100644 --- a/app/Database/Migrations/20181031064714_create_perms.php +++ b/app/Database/Migrations/20181031064714_create_perms.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -53,6 +53,11 @@ class Migration_create_perms extends Migration ], 'created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP', 'updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP', + 'deleted' => [ + 'type' => 'TINYINT', + 'constraint' => 1, + 'default' => 0, + ], ]); $this->forge->addKey('id', true); $this->forge->createTable($config->dbTablePerms, true); diff --git a/app/Database/Migrations/20181031065111_create_perm_to_user.php b/app/Database/Migrations/20181031065111_create_perm_to_user.php index 75e7c0f..edabe1b 100644 --- a/app/Database/Migrations/20181031065111_create_perm_to_user.php +++ b/app/Database/Migrations/20181031065111_create_perm_to_user.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -48,6 +48,11 @@ class Migration_create_perm_to_user extends Migration 'constraint' => 11, 'unsigned' => true, ], + 'state' => [ + 'type' => 'TINYINT', + 'constraint' => 1, + 'default' => 1, + ], ]); $this->forge->addKey(['perm_id', 'user_id'], true); $this->forge->createTable($config->dbTablePermToUser, true); diff --git a/app/Database/Migrations/20181031065240_create_perm_to_group.php b/app/Database/Migrations/20181031065240_create_perm_to_group.php index 99b813a..46a81b2 100644 --- a/app/Database/Migrations/20181031065240_create_perm_to_group.php +++ b/app/Database/Migrations/20181031065240_create_perm_to_group.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -48,6 +48,11 @@ class Migration_create_perm_to_group extends Migration 'constraint' => 11, 'unsigned' => true, ], + 'state' => [ + 'type' => 'TINYINT', + 'constraint' => 1, + 'default' => 1, + ], ]); $this->forge->addKey(['perm_id', 'user_id'], true); $this->forge->createTable($config->dbTablePermToGroup, true); diff --git a/app/Database/Migrations/20181031072542_create_default_groups.php b/app/Database/Migrations/20181031072542_create_default_groups.php index 0e266cf..11d2f9d 100644 --- a/app/Database/Migrations/20181031072542_create_default_groups.php +++ b/app/Database/Migrations/20181031072542_create_default_groups.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -39,15 +39,15 @@ class Migration_create_default_groups extends Migration $config = new AauthConfig(); $data = [ [ - 'name' => $config->adminGroup, + 'name' => $config->groupAdmin, 'definition' => 'Administators', ], [ - 'name' => $config->defaultGroup, + 'name' => $config->groupDefault, 'definition' => 'Users', ], [ - 'name' => $config->publicGroup, + 'name' => $config->groupPublic, 'definition' => 'Guests', ], ]; diff --git a/app/Database/Migrations/20181031072914_create_default_users.php b/app/Database/Migrations/20181031072914_create_default_users.php index 6c89dfa..27be67f 100644 --- a/app/Database/Migrations/20181031072914_create_default_users.php +++ b/app/Database/Migrations/20181031072914_create_default_users.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Helpers/aauth_helper.php b/app/Helpers/aauth_helper.php index c4336e8..c9127b0 100644 --- a/app/Helpers/aauth_helper.php +++ b/app/Helpers/aauth_helper.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Language/de/Aauth.php b/app/Language/de/Aauth.php index 61680a4..8c20526 100644 --- a/app/Language/de/Aauth.php +++ b/app/Language/de/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Dein Account wurde bisher nicht bestätigt. Bitte prüfe deine E-Mails und bestätige deine Registrierung.', 'loginFailedEmail' => 'E-Mail-Adresse oder Passwort falsch.', - 'loginFailedUsername' => 'Benutzername oder Passwort falsch.', + 'loginFailedUsername' => 'Benutzername oder Passwort falsch.', 'loginFailedAll' => 'E-Mail-Adresse, Benutzername oder Passwort falsch.', 'loginAttemptsExceeded' => 'Du hast die maximale Anzahl Login versuche erreicht, dein Account wurde gesperrt.', diff --git a/app/Language/en/Aauth.php b/app/Language/en/Aauth.php index 146a92f..77fe890 100644 --- a/app/Language/en/Aauth.php +++ b/app/Language/en/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Your account has not been verified. Please check your email and verify your account.', 'loginFailedEmail' => 'Email Address and Password do not match.', - 'loginFailedUsername' => 'Username and Password do not match.', + 'loginFailedUsername' => 'Username and Password do not match.', 'loginFailedAll' => 'Email, Username or Password do not match.', 'loginAttemptsExceeded' => 'You have exceeded your login attempts, your account has now been locked.', diff --git a/app/Language/en/Account.php b/app/Language/en/Account.php index a47bf98..ecfece3 100644 --- a/app/Language/en/Account.php +++ b/app/Language/en/Account.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth diff --git a/app/Language/en/Admin.php b/app/Language/en/Admin.php index ee726ee..0e30ccd 100644 --- a/app/Language/en/Admin.php +++ b/app/Language/en/Admin.php @@ -4,8 +4,8 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, - * access management, public access etc.. + * Despite ease of use, it has also very advanced features like grouping, + * access management, public access etc. * * @package CodeIgniter-Aauth * @author Magefly Team diff --git a/app/Language/es/Aauth.php b/app/Language/es/Aauth.php index 080d742..bee8c40 100644 --- a/app/Language/es/Aauth.php +++ b/app/Language/es/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Tu cuenta aún no ha sido verificada, por favor revisa tu correo electrónico y verifica tu cuenta.', 'loginFailedEmail' => 'El Correo electrónico y contraseña no coinciden.', - 'loginFailedUsername' => 'El Nombre de usuario y contraseña no coinciden.', + 'loginFailedUsername' => 'El Nombre de usuario y contraseña no coinciden.', 'loginFailedAll' => 'El Correo electrónico, nombre de usuario y contraseña no coinciden.', 'loginAttemptsExceeded' => 'Has excedido el número de intentos de inicio de sesión, tu cuenta ha sido bloqueada.', diff --git a/app/Language/fa/Aauth.php b/app/Language/fa/Aauth.php index d9ecc59..b50e369 100644 --- a/app/Language/fa/Aauth.php +++ b/app/Language/fa/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'حساب کاربری شما تایید نشده است. لطفا ایمیل خود را برای تایید حسا کاربری بررسی کنید.', 'loginFailedEmail' => 'ایمیل و کلمه عبور همخوانی ندارند.', - 'loginFailedUsername' => 'نام کاربری و کلمه عبور همخوانی ندارند.', + 'loginFailedUsername' => 'نام کاربری و کلمه عبور همخوانی ندارند.', 'loginFailedAll' => 'ایمیل یا نام کاربری با کلمه عبور همخوانی ندارد.', 'loginAttemptsExceeded' => 'شما بیش از حد مجاز برای ورود به سایت تلاش کردید. حساب کاربری شما موقتا غیر فعال شد.', diff --git a/app/Language/fr/Aauth.php b/app/Language/fr/Aauth.php index f16422b..06c0313 100644 --- a/app/Language/fr/Aauth.php +++ b/app/Language/fr/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Votre compte n\'a pas été confirmé. Merci de vérifier vos email et de confirmer votre compte.', 'loginFailedEmail' => 'L\'adresse email et le mot de passe ne correspondent pas.', - 'loginFailedUsername' => 'Le nom d\'utilisateur et le mot de passe ne correspondent pas.', + 'loginFailedUsername' => 'Le nom d\'utilisateur et le mot de passe ne correspondent pas.', 'loginFailedAll' => 'L\'adresse email, le nom d\'utilisateur ou le mot de passe ne correspondent pas.', 'loginAttemptsExceeded' => 'Vous avez dépassé le nombre de tentatives de connexion autorisées, votre compte a été bloqué.', diff --git a/app/Language/id/Aauth.php b/app/Language/id/Aauth.php index d45b92d..d3a7eae 100644 --- a/app/Language/id/Aauth.php +++ b/app/Language/id/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Akun anda belum diverifikasi. Silakan cek email anda dan verifikasi akun anda.', 'loginFailedEmail' => 'Email dan sandi yang anda masukkan tidak cocok.', - 'loginFailedUsername' => 'Username dan sandi yang Anda masukkan tidak cocok.', + 'loginFailedUsername' => 'Username dan sandi yang Anda masukkan tidak cocok.', 'loginFailedAll' => 'Email, username dan sandi yang Anda masukkan tidak cocok.', 'loginAttemptsExceeded' => 'Anda telah melebihi upaya login anda, akun anda telah diblokir.', diff --git a/app/Language/ru/Aauth.php b/app/Language/ru/Aauth.php index a53601d..8b1031a 100644 --- a/app/Language/ru/Aauth.php +++ b/app/Language/ru/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Ваш акккаунт не подтвержден. Проверьте ваш ящик e-mail и подтвердите аккаунт.', 'loginFailedEmail' => 'Неверный email или пароль.', - 'loginFailedUsername' => 'Неверное имя пользователя или пароль.', + 'loginFailedUsername' => 'Неверное имя пользователя или пароль.', 'loginFailedAll' => 'Неверный E-mail, имя пользователя или пароль.', 'loginAttemptsExceeded' => 'Количество попыток входа превышено, ваш аккаунт временно заблокирован.', diff --git a/app/Language/sv/Aauth.php b/app/Language/sv/Aauth.php index 6e42da2..e31beb5 100644 --- a/app/Language/sv/Aauth.php +++ b/app/Language/sv/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -44,7 +44,7 @@ return [ 'notVerified' => 'Ditt konto är inte bekräftat. Var vänlig kolla din e-post och bekräfta ditt konto.', 'loginFailedEmail' => 'E-postadressen och lösenordet stämmer inte överens.', - 'loginFailedUsername' => 'Användarnamnet och lösenordet stämmer inte överens.', + 'loginFailedUsername' => 'Användarnamnet och lösenordet stämmer inte överens.', 'loginFailedAll' => 'E-postadress, användarnamn och lösenord stämmer inte överens.', 'loginAttemptsExceeded' => 'Du har förbrukat dina försök att logga in, ditt konto har blivit låst.', diff --git a/app/Language/zh-CN/Aauth.php b/app/Language/zh-CN/Aauth.php index f52a532..0e4f8a7 100644 --- a/app/Language/zh-CN/Aauth.php +++ b/app/Language/zh-CN/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -46,7 +46,7 @@ return [ 'notVerified' => '您的帐户尚未验证,请检查信箱并验证帐户。', 'loginFailedEmail' => '电邮地址和密码不符', - 'loginFailedUsername' => '用户名和密码不符', + 'loginFailedUsername' => '用户名和密码不符', 'loginFailedAll' => '电邮地址、用户名和或密码不符', 'loginAttemptsExceeded' => '您已达到登入尝试限制数,您的帐户已被锁住。', diff --git a/app/Language/zh-TW/Aauth.php b/app/Language/zh-TW/Aauth.php index 8d55cba..6330e36 100644 --- a/app/Language/zh-TW/Aauth.php +++ b/app/Language/zh-TW/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -46,7 +46,7 @@ return [ 'notVerified' => '您的帳號尚未驗證,請檢查信箱並驗證帳號。', 'loginFailedEmail' => '電郵地址和密碼不符', - 'loginFailedUsername' => '用戶名和密碼不符', + 'loginFailedUsername' => '用戶名和密碼不符', 'loginFailedAll' => '電郵地址、用戶名和或密碼不符', 'loginAttemptsExceeded' => '您已達到登入嘗試限制數,您的帳號已被鎖住。', diff --git a/app/Libraries/Aauth.php b/app/Libraries/Aauth.php index d2d9cbe..03fe7e1 100644 --- a/app/Libraries/Aauth.php +++ b/app/Libraries/Aauth.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -18,6 +18,12 @@ namespace App\Libraries; use \App\Models\Aauth\UserModel; +use \App\Models\Aauth\GroupModel; +use \App\Models\Aauth\PermModel; +use \App\Models\Aauth\GroupToGroupModel; +use \App\Models\Aauth\GroupToUserModel; +use \App\Models\Aauth\PermToGroupModel; +use \App\Models\Aauth\PermToUserModel; use \App\Models\Aauth\LoginAttemptModel; use \App\Models\Aauth\LoginTokenModel; use \App\Models\Aauth\UserVariableModel; @@ -110,9 +116,9 @@ class Aauth $this->session = $session; } - //-------------------------------------------------------------------------- + //-------------------------------------------------------------------- // Login Functions - //-------------------------------------------------------------------------- + //-------------------------------------------------------------------- /** * Login user @@ -331,24 +337,24 @@ class Aauth $userModel->where('id', $userId); $userModel->where('banned', 0); - if ($user = $userModel->get()->getFirstRow()) + if (! $user = $userModel->get()->getFirstRow()) { - $this->session->set('user', [ - 'id' => $user->id, - 'username' => $user->username, - 'email' => $user->email, - 'loggedIn' => true, - ]); - - return true; + return false; } - return false; + $this->session->set('user', [ + 'id' => $user->id, + 'username' => $user->username, + 'email' => $user->email, + 'loggedIn' => true, + ]); + + return true; } - //-------------------------------------------------------------------------- + //-------------------------------------------------------------------- // Access Functions - //-------------------------------------------------------------------------- + //-------------------------------------------------------------------- /** * Check user login @@ -402,6 +408,187 @@ class Aauth return false; } + /** + * Is member + * + * @param integer|string $groupPar Group id or name to check + * @param integer $userId User id, if not given current user + * + * @return boolean + */ + public function isMember($groupPar, int $userId = null) + { + $userModel = new UserModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + $groupToUserModel = new GroupToUserModel(); + + $groupId = $this->getGroupId($groupPar); + + return $groupToUserModel->exists($groupId, $userId); + } + + /** + * Is admin + * + * @param integer $userId User id to check, if it is not given checks current user + * + * @return boolean + */ + public function isAdmin(int $userId = null) + { + $userModel = new UserModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + return $this->isMember($this->config->groupAdmin, $userId); + } + + /** + * Is user allowed + * + * Check if user allowed to do specified action, admin always allowed + * first checks user permissions then check group permissions + * + * @param integer|string $permPar Permission id or name to check + * @param integer|null $userId User id to check, or if false checks current user + * + * @return boolean + */ + public function isAllowed($permPar, int $userId = null) + { + // if($this->CI->session->userdata('totp_required')){ + // $this->error($this->CI->lang->line('aauth_error_totp_verification_required')); + // redirect($this->config_vars['totp_two_step_login_redirect']); + // } + + $userModel = new UserModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + if (! $userModel->existsById($userId)) + { + return false; + } + else if ($this->isAdmin($userId)) + { + return true; + } + else + { + if (! $permId = $this->getPermId($permPar)) + { + return false; + } + + $permToUserModel = new PermToUserModel(); + + if ($permToUserModel->allowed($permId, $userId)) + { + return true; + } + else + { + $groupAllowed = false; + + foreach ($this->listUserGroups($userId) as $group) + { + if ($this->isGroupAllowed($permId, $group['id'])) + { + $groupAllowed = true; + break; + } + } + + return $groupAllowed; + } + } + } + + /** + * Is Group allowed + * + * Check if group is allowed to do specified action, admin always allowed + * + * @param integer $permPar Permission id or name to check + * @param integer|string $groupPar Group id or name to check, or if false checks all user groups + * + * @return boolean + */ + public function isGroupAllowed($permPar, $groupPar = null) + { + if (! $permId = $this->getPermId($permPar)) + { + return false; + } + + if ($groupPar) + { + if (strcasecmp($groupPar, $this->config->groupAdmin) === 0) + { + return true; + } + + $permToGroupModel = new PermToGroupModel(); + $groupId = $this->getGroupId($groupPar); + $groupAllowed = false; + + if ($subgroups = $this->getSubgroups($groupId)) + { + foreach ($subgroups as $group) + { + if (! $groupAllowed) + { + if ($this->isGroupAllowed($permId, $group['subgroup_id'])) + { + $groupAllowed = true; + } + } + } + } + + if ($groupAllowed || $permToGroupModel->allowed($permId, $groupId)) + { + return true; + } + else if (! $groupAllowed) + { + return false; + } + } + else + { + if ($this->isAdmin() || $this->isGroupAllowed($permId, $this->config->groupPublic)) + { + return true; + } + else if (! $this->isLoggedIn()) + { + return false; + } + + foreach ($this->listUserGroups() as $group) + { + if ($this->isGroupAllowed($permId, $group['id'])) + { + return true; + } + } + } + + return false; + } + //-------------------------------------------------------------------- // User Functions //-------------------------------------------------------------------- @@ -455,9 +642,9 @@ class Aauth * Updates existing user details * * @param integer $userId User id to update - * @param string|boolean $email User's email address, or FALSE if not to be updated - * @param string|boolean $password User's password, or FALSE if not to be updated - * @param string|boolean $username User's name, or FALSE if not to be updated + * @param string|boolean $email User's email address, or false if not to be updated + * @param string|boolean $password User's password, or false if not to be updated + * @param string|boolean $username User's name, or false if not to be updated * * @return boolean */ @@ -493,16 +680,16 @@ class Aauth $data['username'] = $username; } - if ($userModel->update($userId, $data)) + if (! $userModel->update($userId, $data)) { - $this->info(lang('Aauth.infoUpdateSuccess')); + $this->error(array_values($userModel->errors())); - return true; + return false; } - $this->error(array_values($userModel->errors())); + $this->info(lang('Aauth.infoUpdateSuccess')); - return false; + return true; } /** @@ -544,7 +731,7 @@ class Aauth $user = $userModel->limit($limit, $offset); $userModel->select('id, email, username, banned, created_at, updated_at, last_activity, last_ip_address, last_login'); - // eanbool $group_par = null, + // eanbool $groupPar = null, if (is_null($includeBanneds)) { @@ -576,7 +763,7 @@ class Aauth $userModel = new UserModel(); $userModel->select('id, email, username, banned, created_at, updated_at, last_activity, last_ip_address, last_login'); - // eanbool $group_par = null, + // eanbool $groupPar = null, if (is_null($includeBanneds)) { @@ -643,17 +830,17 @@ class Aauth 'system' => 1, ]; - if ($verificationCodeStored = $userVariableModel->where($userVariable)->first()) + if (! $verificationCodeStored = $userVariableModel->where($userVariable)->first()) { - $userVariableModel->delete($verificationCodeStored['user_id'], 'verification_code', true); - $this->info(lang('Aauth.infoVerification')); + $this->error(lang('Aauth.invalidVerficationCode')); - return true; + return false; } - $this->error(lang('Aauth.invalidVerficationCode')); + $userVariableModel->delete($verificationCodeStored['user_id'], 'verification_code', true); + $this->info(lang('Aauth.infoVerification')); - return false; + return true; } /** @@ -661,13 +848,13 @@ class Aauth * * Get user information * - * @param integer|boolean $userId User id to get or FALSE for current user + * @param integer|boolean $userId User id to get or false for current user * @param boolean $withVariables Whether to get user variables * @param boolean $inclSystem Whether to get system user variables * * @return object|boolean User information or false if user not found */ - public function getUser($userId = null, bool $withVariables = false, bool $inclSystem = false) + public function getUser(int $userId = null, bool $withVariables = false, bool $inclSystem = false) { $userModel = new UserModel(); $userVariableModel = new UserVariableModel(); @@ -676,25 +863,25 @@ class Aauth if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } - if ($user = $userModel->find($userId)) + if (! $user = $userModel->find($userId)) { - if ($withVariables) - { - $variables = $userVariableModel->select('data_key, data_value' . ($inclSystem ? ', system' : '')); - $variables = $variables->findAll($userId, $inclSystem); - - $user['variables'] = $variables; - } + $this->error(lang('Aauth.notFoundUser')); - return $user; + return false; } - $this->error(lang('Aauth.notFoundUser')); + if ($withVariables) + { + $variables = $userVariableModel->select('data_key, data_value' . ($inclSystem ? ', system' : '')); + $variables = $variables->findAll($userId, $inclSystem); - return false; + $user['variables'] = $variables; + } + + return $user; } /** @@ -706,7 +893,7 @@ class Aauth * * @return object|boolean User information or false if user not found */ - public function getUserId($email = null) + public function getUserId(string $email = null) { $userModel = new UserModel(); @@ -719,12 +906,12 @@ class Aauth $where = ['email' => $email]; } - if ($user = $userModel->where($where)->first()) + if (! $user = $userModel->where($where)->first()) { - return $user['id']; + return false; } - return false; + return $user['id']; } /** @@ -740,7 +927,7 @@ class Aauth if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } if (! $userModel->existsById($userId)) @@ -764,7 +951,7 @@ class Aauth if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } if (! $userModel->existsById($userId)) @@ -790,7 +977,7 @@ class Aauth if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } if (! $userModel->existsById($userId)) @@ -815,39 +1002,38 @@ class Aauth public function remindPassword(string $email) { $userModel = new UserModel(); - if ($user = $userModel->where('email', $email)->first()) + + if (! $user = $userModel->where('email', $email)->first()) { - $userVariableModel = new UserVariableModel(); - $emailService = \Config\Services::email(); - $resetCode = sha1(strtotime('now')); - $userVariableModel->save($user['id'], 'verification_code', $resetCode, true); + $this->error(lang('Aauth.notFoundUser')); - $messageData['code'] = $resetCode; - $messageData['link'] = site_url($this->config->linkResetPassword . '/' . $resetCode); + return false; + } - $emailService->initialize(isset($this->config->emailConfig) ? $this->config->emailConfig : []); - $emailService->setFrom($this->config->emailFrom, $this->config->emailFromName); - $emailService->setTo($user['email']); - $emailService->setSubject(lang('Aauth.subjectReset')); - $emailService->setMessage(view('Aauth/RemindPassword', $messageData)); + $userVariableModel = new UserVariableModel(); + $emailService = \Config\Services::email(); + $resetCode = sha1(strtotime('now')); + $userVariableModel->save($user['id'], 'verification_code', $resetCode, true); - if ($email = $emailService->send()) - { - $this->info(lang('Aauth.infoRemindSuccess')); + $messageData['code'] = $resetCode; + $messageData['link'] = site_url($this->config->linkResetPassword . '/' . $resetCode); - return $email; - } - else - { - $this->error(explode('
', $emailService->printDebugger([]))); + $emailService->initialize(isset($this->config->emailConfig) ? $this->config->emailConfig : []); + $emailService->setFrom($this->config->emailFrom, $this->config->emailFromName); + $emailService->setTo($user['email']); + $emailService->setSubject(lang('Aauth.subjectReset')); + $emailService->setMessage(view('Aauth/RemindPassword', $messageData)); - return false; - } + if (! $email = $emailService->send()) + { + $this->error(explode('
', $emailService->printDebugger([]))); + + return false; } - $this->error(lang('Aauth.notFoundUser')); + $this->info(lang('Aauth.infoRemindSuccess')); - return false; + return $email; } /** @@ -868,58 +1054,61 @@ class Aauth 'system' => 1, ]; - if ($userVariable = $userVariableModel->where($variable)->first()) + if (! $userVariable = $userVariableModel->where($variable)->first()) { - helper('text'); - $userModel = new UserModel(); - $password = random_string('alnum', $this->config->passwordMin); + $this->error(lang('Aauth.invalidVerficationCode')); - if ($user = $userModel->find($userVariable['user_id'])) - { - $emailService = \Config\Services::email(); + return false; + } - $data['id'] = $user['id']; - $data['password'] = $password; + helper('text'); + $userModel = new UserModel(); + $password = random_string('alnum', $this->config->passwordMin); - $userModel->update($user['id'], $data); - $userVariableModel->delete($user['id'], 'verification_code', true); + if (! $user = $userModel->find($userVariable['user_id'])) + { + $this->error(lang('Aauth.notFoundUser')); - if ($this->config->totpEnabled && $this->config->totpResetPassword) - { - $userVariableModel->delete($user['id'], 'totp_secret', true); - } + return false; + } - $messageData['password'] = $password; + $emailService = \Config\Services::email(); - $emailService->initialize(isset($this->config->emailConfig) ? $this->config->emailConfig : []); - $emailService->setFrom($this->config->emailFrom, $this->config->emailFromName); - $emailService->setTo($user['email']); - $emailService->setSubject(lang('Aauth.subjectResetSuccess')); - $emailService->setMessage(view('Aauth/ResetPassword', $messageData)); + $data['id'] = $user['id']; + $data['password'] = $password; - if ($email = $emailService->send()) - { - $this->info(lang('Aauth.infoResetSuccess')); + $userModel->update($user['id'], $data); + $userVariableModel->delete($user['id'], 'verification_code', true); - return $email; - } - else - { - $this->error(explode('
', $emailService->printDebugger([]))); + if ($this->config->totpEnabled && $this->config->totpResetPassword) + { + $userVariableModel->delete($user['id'], 'totp_secret', true); + } - return false; - } - } + $messageData['password'] = $password; + + $emailService->initialize(isset($this->config->emailConfig) ? $this->config->emailConfig : []); + $emailService->setFrom($this->config->emailFrom, $this->config->emailFromName); + $emailService->setTo($user['email']); + $emailService->setSubject(lang('Aauth.subjectResetSuccess')); + $emailService->setMessage(view('Aauth/ResetPassword', $messageData)); + + if (! $email = $emailService->send()) + { + $this->error(explode('
', $emailService->printDebugger([]))); + + return false; } - $this->error(lang('Aauth.invalidVerficationCode')); + $this->info(lang('Aauth.infoResetSuccess')); - return false; + return $email; } /** * Set User Variable as key value - * if variable not set before, it will ve set + * + * if variable not set before, it will be set * if set, overwrites the value * * @param string $key @@ -932,12 +1121,12 @@ class Aauth { if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } $userModel = new UserModel(); - if (! $userModel->existsById($userId)) + if (! @$userModel->existsById($userId)) { return false; } @@ -959,7 +1148,7 @@ class Aauth { if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } $userModel = new UserModel(); @@ -980,13 +1169,13 @@ class Aauth * @param string $key Variable Key * @param integer $userId User id, can be null to use session user * - * @return boolean|string FALSE if var is not set, the value of var if set + * @return boolean|string false if var is not set, the value of var if set */ public function getUserVar(string $key, int $userId = null) { if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } $userModel = new UserModel(); @@ -998,26 +1187,28 @@ class Aauth $userVariableModel = new UserVariableModel(); - if ($variable = $userVariableModel->find($user['id'], 'verification_code', true)) + if (! $variable = $userVariableModel->find($userId, $key)) { - return $variable; + return false; } - return false; + return $variable; } /** * Get User Variables by user id + * * Return array with all user keys & variables * - * @param integer $user_id ; if not given current user - * @return boolean|array , FALSE if var is not set, the value of var if set + * @param integer $userId User id, can be null to use session user + * + * @return boolean|array , false if var is not set, the value of var if set */ public function getUserVars(int $userId = null) { if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } $userModel = new UserModel(); @@ -1029,21 +1220,23 @@ class Aauth $userVariableModel = new UserVariableModel(); - return $userVariableModel->findAll(); + return $userVariableModel->findAll($userId); } /** - * List User Variable Keys by UserID - * Return array of variable keys or FALSE + * List User Variable Keys by UserId + * + * Return array of variable keys or false + * + * @param integer $userId User id, can be null to use session user * - * @param integer $user_id ; if not given current user * @return boolean|array */ - public function list_user_var_keys($user_id = false) + public function listUserVarKeys(int $userId = null) { if (! $userId) { - $userId = $this->session->user['id']; + $userId = (int) @$this->session->user['id']; } $userModel = new UserModel(); @@ -1056,73 +1249,1010 @@ class Aauth $userVariableModel = new UserVariableModel(); $userVariableModel->select('data_key as key'); - return $userVariableModel->findAll(); + return $userVariableModel->findAll($userId); } - //-------------------------------------------------------------------------- - // Error Functions - //-------------------------------------------------------------------------- + + //-------------------------------------------------------------------- + // Group Functions + //-------------------------------------------------------------------- /** - * Error - * - * Add message to error array and set flash data + * Create group * - * @param string|array $message Message to add to array - * @param boolean $flashdata Whether to add $message to session flashdata + * @param string $groupName New group name + * @param string $definition Description of the group * - * @return void + * @return integer|boolean Group id or false on fail */ - public function error($message, bool $flashdata = null) + public function createGroup(string $name, string $definition = '') { - if (is_array($message)) - { - $this->errors = array_merge($this->errors, $message); - } - else - { - $this->errors[] = $message; - } + $groupModel = new GroupModel(); - if ($flashdata) + $data['name'] = $name; + $data['definition'] = $definition; + + if (! $groupId = $groupModel->insert($data)) { - if (is_array($message)) - { - $this->flashErrors = array_merge($this->flashErrors, $message); - } - else - { - $this->flashErrors[] = $message; - } + $this->error(array_values($groupModel->errors())); - $this->session->setFlashdata('errors', $this->flashErrors); + return false; } + + return $groupId; } /** - * Keep Errors - * - * Keeps the flashdata errors for one more page refresh. Optionally adds the default errors into the - * flashdata list. This should be called last in your controller, and with care as it could continue - * to revive all errors and not let them expire as intended. - * Benefitial when using Ajax Requests + * Update group * - * @param boolean $includeNonFlash Wheter to store basic errors as flashdata + * @param string|integer $groupPar Group id or name + * @param string $name New group name + * @param string $definition New group definition * - * @return void + * @return boolean Update success/failure */ - public function keepErrors(bool $includeNonFlash = null) + public function updateGroup($groupPar, string $name = null, string $definition = null) { - if ($includeNonFlash) + $groupModel = new GroupModel(); + + if (is_null($name) && is_null($definition)) { - $flashErrorsOld = $this->session->getFlashdata('errors'); - $this->flashErrors = array_merge((is_array($flashErrorsOld) ? $flashErrorsOld : []), $this->errors); - $this->session->setFlashdata('errors', $this->flashErrors); + return false; } - else + else if (! $groupId = $this->getGroupId($groupPar)) { - $this->session->keepFlashdata('errors'); + $this->error(lang('Aauth.notFoundGroup')); + + return false; } - } + + $data['id'] = $groupId; + + if (! is_null($name)) + { + $data['name'] = $name; + } + + if (! is_null($definition)) + { + $data['definition'] = $definition; + } + + if (! $groupModel->update($groupId, $data)) + { + $this->error(array_values($groupModel->errors())); + + return false; + } + + return true; + } + + /** + * Delete group + * + * @param string|integer $groupPar Group id or name + * + * @return boolean Delete success/failure + */ + public function deleteGroup($groupPar) + { + $groupModel = new GroupModel(); + $groupToGroupModel = new GroupToGroupModel(); + $groupToUserModel = new GroupToUserModel(); + $permToGroupModel = new PermToGroupModel(); + + if (! $groupId = $this->getGroupId($groupPar)) + { + $this->error(lang('Aauth.notFoundGroup')); + + return false; + } + + $groupModel->transStart(); + $groupToGroupModel->deleteAllByGroupId($groupId); + $groupToGroupModel->deleteAllBySubgroupId($groupId); + $groupToUserModel->deleteAllByGroupId($groupId); + $permToGroupModel->deleteAllByGroupId($groupId); + $groupModel->delete($groupId); + $groupModel->transComplete(); + + if ($groupModel->transStatus() === false) + { + $groupModel->transRollback(); + + return false; + } + else + { + $groupModel->transCommit(); + // $this->precacheGroups(); + + return true; + } + } + + /** + * Add member to group + * + * @param integer $userId User id to add to group + * @param integer|string $groupPar Group id or name to add user to + * + * @return boolean Add success/failure + */ + public function addMember($groupPar, int $userId) + { + $userModel = new UserModel(); + $groupToUserModel = new GroupToUserModel(); + + if (! $groupId = $this->getGroupId($groupPar)) + { + $this->error(lang('Aauth.notFoundGroup')); + + return false; + } + else if (! $userModel->existsById($userId)) + { + $this->error(lang('Aauth.notFoundUser')); + + return false; + } + else if ($groupToUserModel->exists($groupId, $userId)) + { + $this->info(lang('Aauth.alreadyMemberGroup')); + + return true; + } + + return $groupToUserModel->insert($groupId, $userId); + } + + /** + * Remove member from group + * + * @param integer $userId User id to remove from group + * @param integer|string $groupPar Group id or name to remove user from + * + * @return boolean Remove success/failure + */ + public function removeMember($groupPar, int $userId) + { + $groupToUserModel = new GroupToUserModel(); + + $groupId = $this->getGroupId($groupPar); + + return $groupToUserModel->delete($groupId, $userId); + } + + /** + * Add subgroup to group + * + * @param integer $userId User id to add to group + * @param integer|string $groupPar Group id or name to add user to + * + * @return boolean Add success/failure + */ + public function addSubgroup($groupPar, $subgroupPar) + { + $groupModel = new GroupModel(); + $groupToGroupModel = new GroupToGroupModel(); + + if (! $groupId = $this->getGroupId($groupPar)) + { + $this->error(lang('Aauth.notFoundGroup')); + + return false; + } + else if (! $subgroupId = $this->getGroupId($subgroupPar)) + { + $this->error(lang('Aauth.notFoundSubgroup')); + + return false; + } + else if ($groupToGroupModel->exists($groupId, $subgroupId)) + { + $this->info(lang('Aauth.alreadyMemberSubgroup')); + + return true; + } + + if ($groupGroups = $groupToGroupModel->findAllByGroupId($groupId)) + { + foreach ($groupGroups as $item) + { + if ($item['subgroup_id'] === $subgroupId) + { + return false; + } + } + } + + if ($subgroupGroups = $groupToGroupModel->findAllByGroupId($subgroupId)) + { + foreach ($subgroupGroups as $item) + { + if ($item['subgroup_id'] === $groupId) + { + return false; + } + } + } + + return $groupToGroupModel->insert($groupId, $subgroupId); + } + + /** + * Remove subgroup from group + * + * @param integer|string $groupPar Group id or name to remove + * @param integer|string $subgroupPar Sub-Group id or name to remove + * + * @return boolean Remove success/failure + */ + public function removeSubgroup($groupPar, $subgroupPar) + { + $groupToGroupModel = new GroupToGroupModel(); + $groupId = $this->getGroupId($groupPar); + $subgroupId = $this->getGroupId($subgroupPar); + + return $groupToGroupModel->delete($groupId, $subgroupId); + } + + /** + * Get subgroups + * + * @param integer|string $groupPar Group id or name to get + * + * @return object Array of subgroup_id's + */ + public function getSubgroups($groupPar) + { + $groupModel = new GroupModel(); + + if (! $groupId = $this->getGroupId($groupPar)) + { + return false; + } + + $groupToGroupModel = new GroupToGroupModel(); + + return $groupToGroupModel->findAllByGroupId($groupId); + } + + /** + * Remove member from all groups + * + * @param integer $userId User id to remove from all groups + * + * @return boolean Remove success/failure + */ + public function removeMemberFromAll(int $userId) + { + $groupToUserModel = new GroupToUserModel(); + + return $groupToUserModel->deleteAllByUserId($userId); + } + + /** + * List all groups + * + * @return object Array of groups + */ + public function listGroups() + { + $groupModel = new GroupModel(); + + return $groupModel->findAll(); + } + + /** + * List groups with paginate + * + * Return groups as an object array + * + * @param integer $limit Limit of users to be returned + * @param string $orderBy Order by MYSQL string (e.g. 'name ASC', 'email DESC') + * + * @return array Array of groups + */ + public function listGroupsPaginated(int $limit = 10, string $orderBy = null) + { + $groupModel = new GroupModel(); + + $groupModel->select('id, name, definition'); + + if (! is_null($orderBy)) + { + $groupModel->orderBy($orderBy); + } + + return [ + 'groups' => $groupModel->paginate($limit), + 'pager' => $groupModel->pager, + ]; + } + + /** + * Get group name + * + * @param integer $groupId Group id to get + * + * @return string Group name + */ + public function getGroupName($groupId) + { + $groupModel = new GroupModel(); + + if (! $group = $groupModel->find($groupId)) + { + return false; + } + + return $group['name']; + } + + /** + * Get group id + * + * @param integer|string $groupPar Group id or name to get + * + * @return integer Group id + */ + public function getGroupId($groupPar) + { + $groupModel = new GroupModel(); + + if (is_numeric($groupPar)) + { + if (! $group = $groupModel->asArray()->find($groupPar)) + { + return false; + } + } + else + { + if (! $group = $groupModel->asArray()->getByName($groupPar)) + { + return false; + } + } + + return $group['id']; + + // $key = str_replace(' ', '', trim(strtolower($groupPar))); + // if (isset($this->cache_group_id[$key])) + // { + // return $this->cache_group_id[$key]; + // } + } + + /** + * Get group + * + * @param integer|string $groupPar Group id or name to get + * + * @return integer Group id + */ + public function getGroup($groupPar) + { + $groupModel = new GroupModel(); + + if (! $groupId = $this->getGroupId($groupPar)) + { + return false; + } + + return $groupModel->asArray()->find($groupId); + } + + /** + * List user groups + * + * @param integer|null $userId User id to get or false for current user + * + * @return integer Group id + */ + public function listUserGroups(int $userId = null) + { + $userModel = new UserModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + if (! $userModel->existsById($userId)) + { + return false; + } + + $groupModel = new GroupModel(); + + $groupModel->select('id, name, definition'); + $groupModel->join($this->config->dbTableGroupToUser, $this->config->dbTableGroups . '.id = ' . $this->config->dbTableGroupToUser . '.group_id'); + $groupModel->where($this->config->dbTableGroupToUser . '.user_id', $userId); + + return $groupModel->get()->getResult('array'); + } + + /** + * List user groups with paginate + * + * Return users as an object array + * + * @param integer|null $userId User id to get or false for current user + * @param integer $limit Limit of users to be returned + * @param string $orderBy Order by MYSQL string (e.g. 'name ASC', 'email DESC') + * + * @return array Array of users + */ + public function listUserGroupsPaginated(int $userId = null, int $limit = 10, string $orderBy = null) + { + $userModel = new UserModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + if (! $userModel->existsById($userId)) + { + return false; + } + + $groupModel = new GroupModel(); + + $groupModel->select('id, name, definition'); + $groupModel->join($this->config->dbTableGroupToUser, $this->config->dbTableGroups . '.id = ' . $this->config->dbTableGroupToUser . '.group_id'); + $groupModel->where($this->config->dbTableGroupToUser . '.user_id', $userId); + + if (! is_null($orderBy)) + { + $groupModel->orderBy($orderBy); + } + + return [ + 'groups' => $groupModel->paginate($limit), + 'pager' => $groupModel->pager, + ]; + } + + //-------------------------------------------------------------------- + // Perm Functions + //-------------------------------------------------------------------- + + /** + * Create permission + * + * Creates a new permission type + * + * @param string $name New permission name + * @param string $definition Permission description + * + * @return integer|boolean Permission id or false on fail + */ + public function createPerm(string $name, string $definition = '') + { + $permModel = new PermModel(); + + $data['name'] = $name; + $data['definition'] = $definition; + + if (! $permId = $permModel->insert($data)) + { + $this->error(array_values($permModel->errors())); + + return false; + } + + // $this->precache_perms(); + + return $permId; + } + + /** + * Update permission + * + * Updates permission name and description + * + * @param integer|string $permPar Permission id or permission name + * @param string $name New permission name + * @param string $definition Permission description + * + * @return boolean Update success/failure + */ + public function updatePerm($permPar, string $name = null, string $definition = null) + { + $permModel = new PermModel(); + + if (is_null($name) && is_null($definition)) + { + return false; + } + else if (! $permId = $this->getPermId($permPar)) + { + $this->error(lang('Aauth.notFoundPerm')); + + return false; + } + + $data['id'] = $permId; + + if (! is_null($name)) + { + $data['name'] = $name; + } + + if (! is_null($definition)) + { + $data['definition'] = $definition; + } + + if (! $permModel->update($permId, $data)) + { + $this->error(array_values($permModel->errors())); + + return false; + } + + return true; + } + + /** + * Delete permission + * + * Delete a permission from database. WARNING Can't be undone + * + * @param integer|string $permPar Permission id or perm name + * + * @return boolean Delete success/failure + */ + public function deletePerm($permPar) + { + $permModel = new PermModel(); + $permToGroupModel = new PermToGroupModel(); + $permToUserModel = new PermToUserModel(); + + if (! $permId = $this->getPermId($permPar)) + { + $this->error(lang('Aauth.notFoundPerm')); + + return false; + } + + $permModel->transStart(); + $permToGroupModel->deleteAllByPermId($permId); + $permToUserModel->deleteAllByPermId($permId); + $permModel->delete($permId); + $permModel->transComplete(); + + if ($permModel->transStatus() === false) + { + $permModel->transRollback(); + + return false; + } + else + { + $permModel->transCommit(); + // $this->precachePerms(); + + return true; + } + } + + /*$userId User id to allow + * + * @return bool Allow success/failure + */ + public function allowUser($permPar, int $userId) + { + $userModel = new UserModel(); + $permToUserModel = new PermToUserModel(); + + if (! $permId = $this->getPermId($permPar)) + { + $this->error(lang('Aauth.notFoundPerm')); + + return false; + } + else if (! $userModel->existsById($userId)) + { + $this->error(lang('Aauth.notFoundUser')); + + return false; + } + else if ($permToUserModel->allowed($permId, $userId)) + { + return true; + } + + return $permToUserModel->save($permId, $userId, 1); + } + + /*$userId User id to deny + * + * @return bool Deny success/failure + */ + public function denyUser($permPar, int $userId) + { + $userModel = new UserModel(); + $permToUserModel = new PermToUserModel(); + + if (! $permId = $this->getPermId($permPar)) + { + $this->error(lang('Aauth.notFoundPerm')); + + return false; + } + else if (! $userModel->existsById($userId)) + { + $this->error(lang('Aauth.notFoundUser')); + + return false; + } + else if ($permToUserModel->denied($permId, $userId)) + { + return true; + } + + return $permToUserModel->save($permId, $userId, 0); + } + + /** + * Allow Group + * + * Add group to permission + * + * @param integer|string $permPar Permission id or perm name + * @param integer|string $groupPar Group id or name to allow + * + * @return boolean Allow success/failure + */ + public function allowGroup($permPar, $groupPar) + { + $permToGroupModel = new PermToGroupModel(); + + if (! $permId = $this->getPermId($permPar)) + { + $this->error(lang('Aauth.notFoundPerm')); + + return false; + } + if (! $groupId = $this->getGroupId($groupPar)) + { + $this->error(lang('Aauth.notFoundGroup')); + + return false; + } + else if ($permToGroupModel->allowed($permId, $groupId)) + { + return true; + } + + return $permToGroupModel->save($permId, $groupId, 1); + } + + /** + * Deny Group + * + * Remove group from permission + * + * @param integer|string $permPar Permission id or perm name + * @param integer|string $groupPar Group id or name to deny + * + * @return boolean Deny success/failure + */ + public function denyGroup($permPar, $groupPar) + { + $permToGroupModel = new PermToGroupModel(); + + if (! $permId = $this->getPermId($permPar)) + { + $this->error(lang('Aauth.notFoundPerm')); + + return false; + } + if (! $groupId = $this->getGroupId($groupPar)) + { + $this->error(lang('Aauth.notFoundGroup')); + + return false; + } + else if ($permToGroupModel->denied($permId, $groupId)) + { + return true; + } + + return $permToGroupModel->save($permId, $groupId, 0); + } + + /** + * List Permissions + * List all permissions + * + * @return object Array of permissions + */ + public function listPerms() + { + $permModel = new PermModel(); + + return $permModel->findAll(); + } + + /** + * List perms with paginate + * + * Return perms as an object array + * + * @param integer $limit Limit of users to be returned + * @param string $orderBy Order by MYSQL string (e.g. 'name ASC', 'email DESC') + * + * @return array Array of perms + */ + public function listPermsPaginated(int $limit = 10, string $orderBy = null) + { + $permModel = new PermModel(); + + $permModel->select('id, name, definition'); + + if (! is_null($orderBy)) + { + $permModel->orderBy($orderBy); + } + + return [ + 'perms' => $permModel->paginate($limit), + 'pager' => $permModel->pager, + ]; + } + + /** + * Get permission id + * + * @param integer|string $permPar Permission id or name to get + * + * @return integer Permission id or NULL if perm does not exist + */ + public function getPermId($permPar) + { + $permModel = new PermModel(); + + if (is_numeric($permPar)) + { + if (! $perm = $permModel->asArray()->find($permPar)) + { + return false; + } + } + else + { + if (! $perm = $permModel->asArray()->getByName($permPar)) + { + return false; + } + } + + // if (isset($this->cache_perm_id[$key])) + // { + // return $this->cache_perm_id[$key]; + // } + + return $perm['id']; + } + + /** + * Get permission + * Get permission from permisison name or id + * + * @param integer|string $permPar Permission id or name to get + * @return integer Permission id or NULL if perm does not exist + */ + public function getPerm($permPar) + { + $permModel = new PermModel(); + + if (! $permId = $this->getPermId($permPar)) + { + return false; + } + + return $permModel->asArray()->find($permId); + } + + /** + * List group permissions + * + * @param integer|string $groupPar Group id or name to get + * + * @return integer Group id + */ + public function listGroupPerms($groupPar) + { + if (! $groupId = $this->getGroupId($groupPar)) + { + return false; + } + + $permModel = new PermModel(); + + $permModel->select('id, name, definition, state'); + $permModel->join($this->config->dbTablePermToGroup, $this->config->dbTablePerms . '.id = ' . $this->config->dbTablePermToGroup . '.perm_id'); + $permModel->where($this->config->dbTablePermToGroup . '.group_id', $groupId); + + return $permModel->get()->getResult('array'); + } + + /** + * List users with paginate + * + * Return users as an object array + * + * @param integer $limit Limit of users to be returned + * @param integer $offset Offset for limited number of users + * @param boolean $includeBanneds Include banned users + * @param string $orderBy Order by MYSQL string (e.g. 'name ASC', 'email DESC') + * + * @return array Array of users + */ + public function listGroupPermsPaginated(int $groupId, int $limit = 10, string $orderBy = null) + { + $permModel = new PermModel(); + + $permModel->select('id, name, definition, state'); + $permModel->join($this->config->dbTablePermToGroup, $this->config->dbTablePerms . '.id = ' . $this->config->dbTablePermToGroup . '.perm_id'); + $permModel->where($this->config->dbTablePermToGroup . '.group_id', $groupId); + + if (! is_null($orderBy)) + { + $permModel->orderBy($orderBy); + } + + return [ + 'perms' => $permModel->paginate($limit), + 'pager' => $permModel->pager, + ]; + } + + /** + * List user permissions + * + * @param integer|string $groupPar Group id or name to get + * + * @return integer Group id + */ + public function listUserPerms(int $userId = null) + { + $userModel = new UserModel(); + $groupModel = new GroupModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + if (! $userModel->existsById($userId)) + { + return false; + } + + $permModel = new PermModel(); + + $permModel->select('id, name, definition, state'); + $permModel->join($this->config->dbTablePermToUser, $this->config->dbTablePerms . '.id = ' . $this->config->dbTablePermToUser . '.perm_id'); + $permModel->where($this->config->dbTablePermToUser . '.user_id', $userId); + + return $permModel->get()->getResult('array'); + } + + /** + * List users with paginate + * + * Return users as an object array + * + * @param integer $limit Limit of users to be returned + * @param integer $offset Offset for limited number of users + * @param boolean $includeBanneds Include banned users + * @param string $orderBy Order by MYSQL string (e.g. 'name ASC', 'email DESC') + * + * @return array Array of users + */ + public function listUserPermsPaginated(int $userId = null, int $limit = 10, string $orderBy = null) + { + $userModel = new UserModel(); + $groupModel = new GroupModel(); + + if (! $userId) + { + $userId = (int) @$this->session->user['id']; + } + + if (! $userModel->existsById($userId)) + { + return false; + } + + $permModel = new PermModel(); + + $permModel->select('id, name, definition, state'); + $permModel->join($this->config->dbTablePermToUser, $this->config->dbTablePerms . '.id = ' . $this->config->dbTablePermToUser . '.perm_id'); + $permModel->where($this->config->dbTablePermToUser . '.user_id', $userId); + + if (! is_null($orderBy)) + { + $permModel->orderBy($orderBy); + } + + return [ + 'perms' => $permModel->paginate($limit), + 'pager' => $permModel->pager, + ]; + } + + //-------------------------------------------------------------------- + // Error Functions + //-------------------------------------------------------------------- + + /** + * Error + * + * Add message to error array and set flash data + * + * @param string|array $message Message to add to array + * @param boolean $flashdata Whether to add $message to session flashdata + * + * @return void + */ + public function error($message, bool $flashdata = null) + { + if (is_array($message)) + { + $this->errors = array_merge($this->errors, $message); + } + else + { + $this->errors[] = $message; + } + + if ($flashdata) + { + if (is_array($message)) + { + $this->flashErrors = array_merge($this->flashErrors, $message); + } + else + { + $this->flashErrors[] = $message; + } + + $this->session->setFlashdata('errors', $this->flashErrors); + } + } + + /** + * Keep Errors + * + * Keeps the flashdata errors for one more page refresh. Optionally adds the default errors into the + * flashdata list. This should be called last in your controller, and with care as it could continue + * to revive all errors and not let them expire as intended. + * Benefitial when using Ajax Requests + * + * @param boolean $includeNonFlash Wheter to store basic errors as flashdata + * + * @return void + */ + public function keepErrors(bool $includeNonFlash = null) + { + if ($includeNonFlash) + { + $flashErrorsOld = $this->session->getFlashdata('errors'); + $this->flashErrors = array_merge((is_array($flashErrorsOld) ? $flashErrorsOld : []), $this->errors); + $this->session->setFlashdata('errors', $this->flashErrors); + } + else + { + $this->session->keepFlashdata('errors'); + } + } /** * Get Errors Array @@ -1172,9 +2302,9 @@ class Aauth $this->session->remove('errors'); } - //-------------------------------------------------------------------------- + //-------------------------------------------------------------------- // Info Functions - //-------------------------------------------------------------------------- + //-------------------------------------------------------------------- /** * Info @@ -1182,7 +2312,7 @@ class Aauth * Add message to info array and set flash data * * @param string|array $message Message to add to infos array - * @param boolean $flashdata Whether add $message to CI flashdata (deflault: FALSE) + * @param boolean $flashdata Whether add $message to CI flashdata (deflault: false) * * @return void */ diff --git a/app/Models/Aauth/GroupModel.php b/app/Models/Aauth/GroupModel.php index 154c231..2791df0 100644 --- a/app/Models/Aauth/GroupModel.php +++ b/app/Models/Aauth/GroupModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -29,6 +29,15 @@ use Config\Aauth as AauthConfig; */ class GroupModel extends Model { + /** + * If this model should use "softDeletes" and + * simply set a flag when rows are deleted, or + * do hard deletes. + * + * @var boolean + */ + protected $useSoftDeletes = true; + /** * If true, will set created_at, and updated_at * values during insert and update routines. @@ -62,10 +71,56 @@ class GroupModel extends Model $this->validationMessages = [ 'name' => [ - 'required' => lang('Aauth.requiredPermName'), - 'is_unique' => lang('Aauth.existsAlreadyPerm'), + 'required' => lang('Aauth.requiredGroupName'), + 'is_unique' => lang('Aauth.existsAlreadyGroup'), ], ]; } + /** + * Checks if group exist by group id + * + * @param integer $groupId Group id + * + * @return boolean + */ + public function existsById(int $groupId) + { + $builder = $this->builder(); + + if ($this->tempUseSoftDeletes === true) + { + $builder->where($this->deletedField, 0); + } + + $builder->where($this->primaryKey, $groupId); + return ($builder->countAllResults() ? true : false); + } + + /** + * Get group by group name + * + * @param string $groupName Group name + * + * @return boolean + */ + public function getByName(string $groupName) + { + $builder = $this->builder(); + + if ($this->tempUseSoftDeletes === true) + { + $builder->where($this->deletedField, 0); + } + + $builder->where('name', $groupName); + + if (! $group = $builder->get()->getFirstRow($this->tempReturnType)) + { + return false; + } + + return $group; + } + } diff --git a/app/Models/Aauth/GroupToGroupModel.php b/app/Models/Aauth/GroupToGroupModel.php index 8fbf103..09e83ac 100644 --- a/app/Models/Aauth/GroupToGroupModel.php +++ b/app/Models/Aauth/GroupToGroupModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -136,6 +136,7 @@ class GroupToGroupModel $builder->where('group_id', $groupId); $builder->where('subgroup_id', $subgroupId); + return ($builder->countAllResults() ? true : false); } @@ -145,7 +146,7 @@ class GroupToGroupModel * @param integer $groupId Group Id * @param integer $subgroupId Subgroup Id * - * @return BaseBuilder + * @return boolean */ public function insert(int $groupId, int $subgroupId) { @@ -154,7 +155,9 @@ class GroupToGroupModel $data['group_id'] = $groupId; $data['subgroup_id'] = $subgroupId; - return $builder->insert($data); + $builder->insert($data); + + return true; } /** @@ -163,15 +166,16 @@ class GroupToGroupModel * @param integer $groupId Group Id * @param integer $subgroupId Subgroup Id * - * @return BaseBuilder + * @return boolean */ public function delete(int $groupId, int $subgroupId) { $builder = $this->builder(); $builder->where('group_id', $groupId); $builder->where('subgroup_id', $subgroupId); + $builder->delete(); - return $builder->delete(); + return true; } /** @@ -179,14 +183,15 @@ class GroupToGroupModel * * @param integer $groupId Group Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByGroupId(int $groupId) { $builder = $this->builder(); $builder->where('group_id', $groupId); + $builder->delete(); - return $builder->delete(); + return true; } /** @@ -194,14 +199,15 @@ class GroupToGroupModel * * @param integer $subgroupId Subgroup Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllBySubgroupId(int $subgroupId) { $builder = $this->builder(); $builder->where('subgroup_id', $subgroupId); + $builder->delete(); - return $builder->delete(); + return true; } /** diff --git a/app/Models/Aauth/GroupToUserModel.php b/app/Models/Aauth/GroupToUserModel.php index 189be2a..e7ede33 100644 --- a/app/Models/Aauth/GroupToUserModel.php +++ b/app/Models/Aauth/GroupToUserModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -145,7 +145,7 @@ class GroupToUserModel * @param integer $groupId Group Id * @param integer $userId User Id * - * @return BaseBuilder + * @return boolean */ public function insert(int $groupId, int $userId) { @@ -154,7 +154,9 @@ class GroupToUserModel $data['group_id'] = $groupId; $data['user_id'] = $userId; - return $builder->insert($data); + $builder->insert($data); + + return true; } /** @@ -163,15 +165,16 @@ class GroupToUserModel * @param integer $groupId Group Id * @param integer $userId User Id * - * @return BaseBuilder + * @return boolean */ public function delete(int $groupId, int $userId) { $builder = $this->builder(); $builder->where('group_id', $groupId); $builder->where('user_id', $userId); + $builder->delete(); - return $builder->delete(); + return true; } /** @@ -179,14 +182,15 @@ class GroupToUserModel * * @param integer $groupId Group Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByGroupId(int $groupId) { $builder = $this->builder(); $builder->where('group_id', $groupId); + $builder->delete(); - return $builder->delete(); + return true; } /** @@ -194,14 +198,15 @@ class GroupToUserModel * * @param integer $userId User Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByUserId(int $userId) { $builder = $this->builder(); $builder->where('user_id', $userId); + $builder->delete(); - return $builder->delete(); + return true; } /** diff --git a/app/Models/Aauth/LoginAttemptModel.php b/app/Models/Aauth/LoginAttemptModel.php index 45218bd..bb930db 100644 --- a/app/Models/Aauth/LoginAttemptModel.php +++ b/app/Models/Aauth/LoginAttemptModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -166,7 +166,7 @@ class LoginAttemptModel * * Delete login attempt based on time and ip address * - * @return BaseBuilder + * @return boolean */ public function delete() { @@ -174,7 +174,9 @@ class LoginAttemptModel $builder->where('ip_address', $this->request->getIPAddress()); $builder->where('updated_at >=', date('Y-m-d H:i:s', strtotime('-' . $this->config->loginAttemptLimitTimePeriod))); - return $builder->delete(); + $builder->delete(); + + return true; } /** @@ -182,7 +184,7 @@ class LoginAttemptModel * * @param string $table Table name * - * @return BaseBuilder + * @return boolean */ protected function builder(string $table = null) { diff --git a/app/Models/Aauth/LoginTokenModel.php b/app/Models/Aauth/LoginTokenModel.php index e75ce51..e10504b 100644 --- a/app/Models/Aauth/LoginTokenModel.php +++ b/app/Models/Aauth/LoginTokenModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -111,7 +111,7 @@ class LoginTokenModel * * @param array $data Array with data * - * @return BaseBuilder + * @return boolean */ public function insert(array $data) { @@ -121,7 +121,9 @@ class LoginTokenModel $data['expires_at'] = date('Y-m-d H:i:s', strtotime($this->config->loginRemember)); $data['updated_at'] = date('Y-m-d H:i:s'); - return $builder->insert($data); + $builder->insert($data); + + return true; } /** @@ -147,15 +149,16 @@ class LoginTokenModel * * @param integer $userId User id * - * @return BaseBuilder + * @return boolean */ public function deleteExpired(int $userId) { $builder = $this->builder(); $builder->where('user_id', $userId); $builder->where('expires_at <', date('Y-m-d H:i:s')); + $builder->delete(); - return $builder->delete(); + return true; } /** diff --git a/app/Models/Aauth/PermModel.php b/app/Models/Aauth/PermModel.php index d007573..f89de7e 100644 --- a/app/Models/Aauth/PermModel.php +++ b/app/Models/Aauth/PermModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -29,6 +29,15 @@ use Config\Aauth as AauthConfig; */ class PermModel extends Model { + /** + * If this model should use "softDeletes" and + * simply set a flag when rows are deleted, or + * do hard deletes. + * + * @var boolean + */ + protected $useSoftDeletes = true; + /** * If true, will set created_at, and updated_at * values during insert and update routines. @@ -68,4 +77,49 @@ class PermModel extends Model ]; } + /** + * Checks if perm exist by perm id + * + * @param integer $permId Perm id + * + * @return boolean + */ + public function existsById(int $permId) + { + $builder = $this->builder(); + + if ($this->tempUseSoftDeletes === true) + { + $builder->where($this->deletedField, 0); + } + + $builder->where($this->primaryKey, $permId); + return ($builder->countAllResults() ? true : false); + } + + /** + * Get perm by perm name + * + * @param string $name Perm name + * + * @return boolean + */ + public function getByName(string $name) + { + $builder = $this->builder(); + + if ($this->tempUseSoftDeletes === true) + { + $builder->where($this->deletedField, 0); + } + + $builder->where('name', $name); + + if (! $perm = $builder->get()->getFirstRow($this->tempReturnType)) + { + return false; + } + + return $perm; + } } diff --git a/app/Models/Aauth/PermToGroupModel.php b/app/Models/Aauth/PermToGroupModel.php index 1f96e15..8040bc4 100644 --- a/app/Models/Aauth/PermToGroupModel.php +++ b/app/Models/Aauth/PermToGroupModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -100,7 +100,7 @@ class PermToGroupModel public function findAllByGroupId(int $groupId) { $builder = $this->builder(); - $builder->select('perm_id'); + $builder->select('perm_id, state'); $builder->where('group_id', $groupId); return $builder->get()->getResult('array'); @@ -116,62 +116,81 @@ class PermToGroupModel public function findAllByPermId(int $permId) { $builder = $this->builder(); - $builder->select('group_id'); + $builder->select('group_id, state'); $builder->where('perm_id', $permId); return $builder->get()->getResult('array'); } /** - * Check if exists by Perm Id and Group Id + * Check if Perm Id is allowed by Group Id * * @param integer $permId Perm Id * @param integer $groupId Group Id * * @return boolean */ - public function exists(int $permId, int $groupId) + public function allowed(int $permId, int $groupId) { $builder = $this->builder(); $builder->where('perm_id', $permId); $builder->where('group_id', $groupId); + $builder->where('state', 1); return ($builder->countAllResults() ? true : false); } /** - * Insert + * Check if Perm Id is allowed by Group Id * * @param integer $permId Perm Id * @param integer $groupId Group Id * - * @return BaseBuilder + * @return boolean */ - public function insert(int $permId, int $groupId) + public function denied(int $permId, int $groupId) { $builder = $this->builder(); - $data['perm_id'] = $permId; - $data['group_id'] = $groupId; - - return $builder->insert($data); + $builder->where('perm_id', $permId); + $builder->where('group_id', $groupId); + $builder->where('state', 0); + return ($builder->countAllResults() ? true : false); } /** - * Delete by Perm Id and Group Id + * Save + * + * Inserts or Updates Perm to Group * * @param integer $permId Perm Id * @param integer $groupId Group Id + * @param integer $state State Int (0 deny, 1 allow) * - * @return BaseBuilder + * @return boolean */ - public function delete(int $permId, int $groupId) + public function save(int $permId, int $groupId, int $state = 1) { $builder = $this->builder(); $builder->where('perm_id', $permId); $builder->where('group_id', $groupId); - return $builder->delete(); + if (! $row = $builder->get()->getFirstRow()) + { + $data['perm_id'] = $permId; + $data['group_id'] = $groupId; + $data['state'] = $state; + + $builder->insert($data); + } + else + { + $data['state'] = $state; + + $builder->update($data, ['perm_id' => $permId, 'group_id' => $groupId]); + } + + return true; } /** @@ -179,14 +198,15 @@ class PermToGroupModel * * @param integer $permId Perm Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByPermId(int $permId) { $builder = $this->builder(); $builder->where('perm_id', $permId); + $builder->delete(); - return $builder->delete(); + return true; } /** @@ -194,14 +214,15 @@ class PermToGroupModel * * @param integer $groupId Group Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByGroupId(int $groupId) { $builder = $this->builder(); $builder->where('group_id', $groupId); + $builder->delete(); - return $builder->delete(); + return true; } /** diff --git a/app/Models/Aauth/PermToUserModel.php b/app/Models/Aauth/PermToUserModel.php index 4506177..f43b8f0 100644 --- a/app/Models/Aauth/PermToUserModel.php +++ b/app/Models/Aauth/PermToUserModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -100,7 +100,7 @@ class PermToUserModel public function findAllByUserId(int $userId) { $builder = $this->builder(); - $builder->select('perm_id'); + $builder->select('perm_id, state'); $builder->where('user_id', $userId); return $builder->get()->getResult('array'); @@ -116,62 +116,81 @@ class PermToUserModel public function findAllByPermId(int $permId) { $builder = $this->builder(); - $builder->select('user_id'); + $builder->select('user_id, state'); $builder->where('perm_id', $permId); return $builder->get()->getResult('array'); } /** - * Check if exists by Perm Id and User Id + * Check if Perm Id is allowed by User Id * * @param integer $permId Perm Id * @param integer $userId User Id * * @return boolean */ - public function exists(int $permId, int $userId) + public function allowed(int $permId, int $userId) { $builder = $this->builder(); $builder->where('perm_id', $permId); $builder->where('user_id', $userId); + $builder->where('state', 1); return ($builder->countAllResults() ? true : false); } /** - * Insert + * Check if Perm Id is allowed by User Id * * @param integer $permId Perm Id * @param integer $userId User Id * - * @return BaseBuilder + * @return boolean */ - public function insert(int $permId, int $userId) + public function denied(int $permId, int $userId) { $builder = $this->builder(); - $data['perm_id'] = $permId; - $data['user_id'] = $userId; - - return $builder->insert($data); + $builder->where('perm_id', $permId); + $builder->where('user_id', $userId); + $builder->where('state', 0); + return ($builder->countAllResults() ? true : false); } /** - * Delete by Perm Id and User Id + * Save + * + * Inserts or Updates Perm to User * * @param integer $permId Perm Id * @param integer $userId User Id + * @param integer $state State Int (0 deny, 1 allow) * - * @return BaseBuilder + * @return boolean */ - public function delete(int $permId, int $userId) + public function save(int $permId, int $userId, int $state = 1) { $builder = $this->builder(); $builder->where('perm_id', $permId); $builder->where('user_id', $userId); - return $builder->delete(); + if (! $row = $builder->get()->getFirstRow()) + { + $data['perm_id'] = $permId; + $data['user_id'] = $userId; + $data['state'] = $state; + + $builder->insert($data); + } + else + { + $data['state'] = $state; + + $builder->update($data, ['perm_id' => $permId, 'user_id' => $userId]); + } + + return true; } /** @@ -179,14 +198,15 @@ class PermToUserModel * * @param integer $permId Perm Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByPermId(int $permId) { $builder = $this->builder(); $builder->where('perm_id', $permId); + $builder->delete(); - return $builder->delete(); + return true; } /** @@ -194,14 +214,15 @@ class PermToUserModel * * @param integer $userId User Id * - * @return BaseBuilder + * @return boolean */ public function deleteAllByUserId(int $userId) { $builder = $this->builder(); $builder->where('user_id', $userId); + $builder->delete(); - return $builder->delete(); + return true; } /** diff --git a/app/Models/Aauth/UserModel.php b/app/Models/Aauth/UserModel.php index 1396774..34fb097 100644 --- a/app/Models/Aauth/UserModel.php +++ b/app/Models/Aauth/UserModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -130,7 +130,6 @@ class UserModel extends Model /** * Update - * */ public function update($id = null, $data = null) { @@ -140,6 +139,7 @@ class UserModel extends Model return parent::update($id, $data); } + /** * Update last login by User ID * @@ -210,7 +210,7 @@ class UserModel extends Model $builder->where($this->primaryKey, $userId); $builder->where('banned', 1); - if ($user = $builder->get()->getFirstRow()) + if ($builder->get()->getFirstRow()) { return true; } @@ -269,18 +269,18 @@ class UserModel extends Model { if (empty($username)) { - return FALSE; + return false; } $builder = $this->builder(); - if ($this->tempUseSoftDeletes === TRUE) + if ($this->tempUseSoftDeletes === true) { $builder->where($this->deletedField, 0); } $builder->where('username', $username); - return ($builder->countAllResults() ? TRUE : FALSE); + return ($builder->countAllResults() ? true : false); } /** diff --git a/app/Models/Aauth/UserVariableModel.php b/app/Models/Aauth/UserVariableModel.php index 7defd88..4b2c637 100644 --- a/app/Models/Aauth/UserVariableModel.php +++ b/app/Models/Aauth/UserVariableModel.php @@ -4,7 +4,7 @@ * * Aauth is a User Authorization Library for CodeIgniter 4.x, which aims to make * easy some essential jobs such as login, permissions and access operations. - * Despite ease of use, it has also very advanced features like groupping, + * Despite ease of use, it has also very advanced features like grouping, * access management, public access etc.. * * @package CodeIgniter-Aauth @@ -190,8 +190,8 @@ class UserVariableModel * @param string $dataKey Key of variable * @param string $dataValue Value of variable * @param boolean $system Whether system variable - - * @return BaseBuilder + * + * @return boolean */ public function insert(int $userId, string $dataKey, string $dataValue, bool $system = null) { @@ -204,7 +204,9 @@ class UserVariableModel $data['created_at'] = date('Y-m-d H:i:s'); $data['updated_at'] = date('Y-m-d H:i:s'); - return $builder->insert($data); + $builder->insert($data); + + return true; } /** @@ -237,7 +239,7 @@ class UserVariableModel * @param string $dataKey Key of variable * @param boolean $system Whether system variable * - * @return BaseBuilder + * @return boolean */ public function delete(int $userId, string $dataKey, bool $system = null) { @@ -245,8 +247,25 @@ class UserVariableModel $builder->where('user_id', $userId); $builder->where('data_key', $dataKey); $builder->where('system', ($system ? 1 : 0)); + $builder->delete(); + + return true; + } + + /** + * Delete all User Variables by User ID + * + * @param integer $userId User id + * + * @return boolean + */ + public function deleteAllByUserId(int $userId) + { + $builder = $this->builder(); + $builder->where('user_id', $userId); + $builder->delete(); - return $builder->delete(); + return true; } //-------------------------------------------------------------------- diff --git a/tests/Aauth/Database/GroupModelTest.php b/tests/Aauth/Database/GroupModelTest.php index 5f40ea4..d79f646 100644 --- a/tests/Aauth/Database/GroupModelTest.php +++ b/tests/Aauth/Database/GroupModelTest.php @@ -20,9 +20,15 @@ class GroupModelTest extends CIDatabaseTestCase //-------------------------------------------------------------------- - public function testDummy() + public function testExistsById() { - $groups = $this->model->findAll(); - $this->assertCount(3, $groups); + $this->assertTrue($this->model->existsById(1)); + $this->assertFalse($this->model->existsById(99)); + } + + public function testGetByName() + { + $this->assertEquals(1, $this->model->getByName('admin')['id']); + $this->assertFalse($this->model->getByName('test_group')); } } diff --git a/tests/Aauth/Database/GroupToGroupModelTest.php b/tests/Aauth/Database/GroupToGroupModelTest.php index c1f165b..e64a5a9 100644 --- a/tests/Aauth/Database/GroupToGroupModelTest.php +++ b/tests/Aauth/Database/GroupToGroupModelTest.php @@ -33,39 +33,35 @@ class GroupToGroupModelTest extends CIDatabaseTestCase public function testExists() { - $groupToGroup = $this->model->exists(99, 99); - $this->assertFalse($groupToGroup); + $this->assertFalse($this->model->exists(99, 99)); $this->hasInDatabase($this->config->dbTableGroupToGroup, [ 'group_id' => 99, 'subgroup_id' => 99, ]); - $groupToGroup = $this->model->exists(99, 99); - $this->assertTrue($groupToGroup); + $this->assertTrue($this->model->exists(99, 99)); } public function testFindAllBySubgroupId() { - $groupsToGroup = $this->model->findAllBySubgroupId(99); - $this->assertCount(0, $groupsToGroup); + $this->assertCount(0, $this->model->findAllBySubgroupId(99)); + $this->hasInDatabase($this->config->dbTableGroupToGroup, [ 'group_id' => 99, 'subgroup_id' => 99, ]); - $groupsToGroup = $this->model->findAllBySubgroupId(99); - $this->assertCount(1, $groupsToGroup); + $this->assertCount(1, $this->model->findAllBySubgroupId(99)); } public function testFindAllByGroupId() { - $groupToGroups = $this->model->findAllByGroupId(99); - $this->assertCount(0, $groupToGroups); + $this->assertCount(0, $this->model->findAllByGroupId(99)); + $this->hasInDatabase($this->config->dbTableGroupToGroup, [ 'group_id' => 99, 'subgroup_id' => 99, ]); - $groupToGroups = $this->model->findAllByGroupId(99); - $this->assertCount(1, $groupToGroups); + $this->assertCount(1, $this->model->findAllByGroupId(99)); } public function testDelete() diff --git a/tests/Aauth/Database/GroupToUserModelTest.php b/tests/Aauth/Database/GroupToUserModelTest.php index a8f5363..cb40e8c 100644 --- a/tests/Aauth/Database/GroupToUserModelTest.php +++ b/tests/Aauth/Database/GroupToUserModelTest.php @@ -33,39 +33,35 @@ class GroupToUserModelTest extends CIDatabaseTestCase public function testExists() { - $groupToUser = $this->model->exists(99, 99); - $this->assertFalse($groupToUser); + $this->assertFalse($this->model->exists(99, 99)); $this->hasInDatabase($this->config->dbTableGroupToUser, [ 'group_id' => 99, 'user_id' => 99, ]); - $groupToUser = $this->model->exists(99, 99); - $this->assertTrue($groupToUser); + $this->assertTrue($this->model->exists(99, 99)); } public function testFindAllByUserId() { - $groupToUsers = $this->model->findAllByUserId(99); - $this->assertCount(0, $groupToUsers); + $this->assertCount(0, $this->model->findAllByUserId(99)); + $this->hasInDatabase($this->config->dbTableGroupToUser, [ 'group_id' => 99, 'user_id' => 99, ]); - $groupToUsers = $this->model->findAllByUserId(99); - $this->assertCount(1, $groupToUsers); + $this->assertCount(1, $this->model->findAllByUserId(99)); } public function testFindAllByGroupId() { - $groupToUsers = $this->model->findAllByGroupId(99); - $this->assertCount(0, $groupToUsers); + $this->assertCount(0, $this->model->findAllByGroupId(99)); + $this->hasInDatabase($this->config->dbTableGroupToUser, [ 'group_id' => 99, 'user_id' => 99, ]); - $groupToUsers = $this->model->findAllByGroupId(99); - $this->assertCount(1, $groupToUsers); + $this->assertCount(1, $this->model->findAllByGroupId(99)); } public function testDelete() diff --git a/tests/Aauth/Database/LoginAttemptModelTest.php b/tests/Aauth/Database/LoginAttemptModelTest.php index 2e3e07e..bfe4b2c 100644 --- a/tests/Aauth/Database/LoginAttemptModelTest.php +++ b/tests/Aauth/Database/LoginAttemptModelTest.php @@ -29,12 +29,10 @@ class LoginAttemptModelTest extends CIDatabaseTestCase public function testSave() { $this->assertTrue($this->model->save()); - $loginAttempt = $this->model->find(); - $this->assertEquals(1, $loginAttempt); + $this->assertEquals(1, $this->model->find()); $this->assertTrue($this->model->save()); - $loginAttempt = $this->model->find(); - $this->assertEquals(2, $loginAttempt); + $this->assertEquals(2, $this->model->find()); $this->model->save(); $this->model->save(); @@ -49,18 +47,16 @@ class LoginAttemptModelTest extends CIDatabaseTestCase public function testDelete() { $this->model->save(); - $loginAttempt = $this->model->find(); - $this->assertEquals(1, $loginAttempt); + $this->assertEquals(1, $this->model->find()); + $this->model->delete(); - $loginAttempt = $this->model->find(); - $this->assertEquals(0, $loginAttempt); + $this->assertEquals(0, $this->model->find()); } public function testConfigDBGroup() { $this->model = new LoginAttemptModel(); $this->model->save(); - $groupsToGroup = $this->model->find(); - $this->assertEquals(1, $groupsToGroup); + $this->assertEquals(1, $this->model->find()); } } diff --git a/tests/Aauth/Database/LoginTokenModelTest.php b/tests/Aauth/Database/LoginTokenModelTest.php index 917bc09..dd7a352 100644 --- a/tests/Aauth/Database/LoginTokenModelTest.php +++ b/tests/Aauth/Database/LoginTokenModelTest.php @@ -31,21 +31,18 @@ class LoginTokenModelTest extends CIDatabaseTestCase { $this->model->insert(['user_id' => 99, 'random_hash' => 'random_hash9999']); $oldLoginTokens = $this->model->findAllByUserId(99); - $oldLoginToken = $oldLoginTokens[0]; - sleep(5); - $this->model->update($oldLoginToken['id']); + sleep(2); + $this->model->update($oldLoginTokens[0]['id']); $loginTokens = $this->model->findAllByUserId(99); - $loginToken = $loginTokens[0]; - $this->assertNotEquals($oldLoginToken['expires_at'], $loginToken['expires_at']); + $this->assertNotEquals($oldLoginTokens[0]['expires_at'], $loginTokens[0]['expires_at']); } public function testDeleteExpired() { $this->model->insert(['user_id' => 99, 'random_hash' => 'random_hash9999']); - sleep(5); + sleep(2); $this->model->deleteExpired(99); - $loginTokens = $this->model->findAllByUserId(99); - $this->assertCount(0, $loginTokens); + $this->assertCount(0, $this->model->findAllByUserId(99)); } public function testConfigDBGroup() diff --git a/tests/Aauth/Database/PermModelTest.php b/tests/Aauth/Database/PermModelTest.php index 1a8b9ab..7b7f582 100644 --- a/tests/Aauth/Database/PermModelTest.php +++ b/tests/Aauth/Database/PermModelTest.php @@ -1,5 +1,6 @@ model = new PermModel($this->db); + $this->model = new PermModel($this->db); + $this->config = new AauthConfig(); } //-------------------------------------------------------------------- - public function testDummy() + public function testExistsById() { - $perms = $this->model->findAll(); - $this->assertCount(0, $perms); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->assertTrue($this->model->existsById(1)); + $this->assertFalse($this->model->existsById(99)); + } + + public function testGetByName() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + + $this->assertEquals(1, $this->model->getByName('testPerm1')['id']); + $this->assertFalse($this->model->getByName('testPerm99')); } } diff --git a/tests/Aauth/Database/PermToGroupModelTest.php b/tests/Aauth/Database/PermToGroupModelTest.php index f8a2441..1f2f652 100644 --- a/tests/Aauth/Database/PermToGroupModelTest.php +++ b/tests/Aauth/Database/PermToGroupModelTest.php @@ -21,26 +21,45 @@ class PermToGroupModelTest extends CIDatabaseTestCase } //-------------------------------------------------------------------- - public function testInsert() + public function testSave() { - $permToGroup = $this->model->insert(99, 99); + $this->model->save(99, 99, 1); $this->seeInDatabase($this->config->dbTablePermToGroup, [ 'perm_id' => 99, 'group_id' => 99, + 'state' => 1, ]); + + $this->model->save(99, 99, 0); + $this->seeInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 99, + 'group_id' => 99, + 'state' => 0, + ]); + } + + public function testAllowed() + { + $this->assertFalse($this->model->allowed(99, 99)); + + $this->hasInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 99, + 'group_id' => 99, + 'state' => 1, + ]); + $this->assertTrue($this->model->allowed(99, 99)); } - public function testExists() + public function testDenied() { - $permToGroup = $this->model->exists(99, 99); - $this->assertFalse($permToGroup); + $this->assertFalse($this->model->denied(99, 99)); $this->hasInDatabase($this->config->dbTablePermToGroup, [ 'perm_id' => 99, 'group_id' => 99, + 'state' => 0, ]); - $permToGroup = $this->model->exists(99, 99); - $this->assertTrue($permToGroup); + $this->assertTrue($this->model->denied(99, 99)); } public function testFindAllByGroupId() @@ -67,21 +86,6 @@ class PermToGroupModelTest extends CIDatabaseTestCase $this->assertCount(1, $permToGroups); } - public function testDelete() - { - $this->hasInDatabase($this->config->dbTablePermToGroup, [ - 'perm_id' => 99, - 'group_id' => 99, - ]); - $criteria = [ - 'perm_id' => 99, - 'group_id' => 99, - ]; - $this->seeNumRecords(1, $this->config->dbTablePermToGroup, $criteria); - $this->model->delete(99, 99); - $this->seeNumRecords(0, $this->config->dbTablePermToGroup, $criteria); - } - public function testDeleteAllByPermId() { $this->hasInDatabase($this->config->dbTablePermToGroup, [ diff --git a/tests/Aauth/Database/PermToUserModelTest.php b/tests/Aauth/Database/PermToUserModelTest.php index 6db00d3..21edd09 100644 --- a/tests/Aauth/Database/PermToUserModelTest.php +++ b/tests/Aauth/Database/PermToUserModelTest.php @@ -21,26 +21,45 @@ class PermToUserModelTest extends CIDatabaseTestCase } //-------------------------------------------------------------------- - public function testInsert() + public function testSave() { - $permToUser = $this->model->insert(99, 99); + $this->model->save(99, 99, 1); $this->seeInDatabase($this->config->dbTablePermToUser, [ 'perm_id' => 99, 'user_id' => 99, + 'state' => 1, ]); + + $this->model->save(99, 99, 0); + $this->seeInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 99, + 'user_id' => 99, + 'state' => 0, + ]); + } + + public function testAllowed() + { + $this->assertFalse($this->model->allowed(99, 99)); + + $this->hasInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 99, + 'user_id' => 99, + 'state' => 1, + ]); + $this->assertTrue($this->model->allowed(99, 99)); } - public function testExists() + public function testDenied() { - $permToUser = $this->model->exists(99, 99); - $this->assertFalse($permToUser); + $this->assertFalse($this->model->denied(99, 99)); $this->hasInDatabase($this->config->dbTablePermToUser, [ 'perm_id' => 99, 'user_id' => 99, + 'state' => 0, ]); - $permToUser = $this->model->exists(99, 99); - $this->assertTrue($permToUser); + $this->assertTrue($this->model->denied(99, 99)); } public function testFindAllByUserId() @@ -67,21 +86,6 @@ class PermToUserModelTest extends CIDatabaseTestCase $this->assertCount(1, $permToUsers); } - public function testDelete() - { - $this->hasInDatabase($this->config->dbTablePermToUser, [ - 'perm_id' => 99, - 'user_id' => 99, - ]); - $criteria = [ - 'perm_id' => 99, - 'user_id' => 99, - ]; - $this->seeNumRecords(1, $this->config->dbTablePermToUser, $criteria); - $this->model->delete(99, 99); - $this->seeNumRecords(0, $this->config->dbTablePermToUser, $criteria); - } - public function testDeleteAllByPermId() { $this->hasInDatabase($this->config->dbTablePermToUser, [ diff --git a/tests/Aauth/Database/UserModelTest.php b/tests/Aauth/Database/UserModelTest.php index d451f69..51db285 100644 --- a/tests/Aauth/Database/UserModelTest.php +++ b/tests/Aauth/Database/UserModelTest.php @@ -31,14 +31,15 @@ class UserModelTest extends CIDatabaseTestCase { $this->model->updateLastLogin(1); $user = $this->model->asArray()->find(1); - $this->assertTrue((strtotime('-5 seconds') < strtotime($user['last_login']) && strtotime('+5 seconds') > strtotime($user['last_login'])) && strtotime('-5 seconds') < strtotime($user['last_activity']) && strtotime('+5 seconds') > strtotime($user['last_activity'])); + $this->assertCloseEnough(strtotime('now'), strtotime($user['last_login']), '', 5); + $this->assertCloseEnough(strtotime('now'), strtotime($user['last_activity']), '', 5); } public function testUpdateLastActivity() { $this->model->updateLastActivity(1); $user = $this->model->asArray()->find(1); - $this->assertTrue(strtotime('-5 seconds') < strtotime($user['last_activity']) && strtotime('+5 seconds') > strtotime($user['last_activity'])); + $this->assertCloseEnough(strtotime('now'), strtotime($user['last_activity']), '', 5); } public function testUpdateBanned() @@ -75,7 +76,8 @@ class UserModelTest extends CIDatabaseTestCase $userOld = $this->model->asArray()->find(1); $this->model->update(1, ['id' => 1, 'password' => 'password123456']); $userNew = $this->model->asArray()->find(1); - $this->assertTrue($userOld['password'] !== $userNew['password'] && $userNew['password'] !== 'password123456'); + $this->assertNotEquals($userOld['password'], $userNew['password']); + $this->assertNotEquals('password123456', $userNew['password']); $userOld = $this->model->asArray()->find(1); $this->model->update(1, ['id' => 1, 'username' => 'admin']); @@ -85,11 +87,11 @@ class UserModelTest extends CIDatabaseTestCase public function testLoginUseUsernameDummy() { - $config = new AauthConfig(); + $config = new AauthConfig(); + $config->loginUseUsername = true; $this->model = new UserModel($this->db, null, $config); - $newUser = $this->model->insert(['email' => 'test@test.local', 'password' => 'password123456']); - $this->assertFalse($newUser); + $this->assertFalse($this->model->insert(['email' => 'test@test.local', 'password' => 'password123456'])); } } diff --git a/tests/Aauth/Database/UserVariableModelTest.php b/tests/Aauth/Database/UserVariableModelTest.php index aa50a8a..9662cf1 100644 --- a/tests/Aauth/Database/UserVariableModelTest.php +++ b/tests/Aauth/Database/UserVariableModelTest.php @@ -79,6 +79,21 @@ class UserVariableModelTest extends CIDatabaseTestCase $this->seeNumRecords(0, $this->config->dbTableUserVariables, $criteria); } + public function testDeleteAllByUserId() + { + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 99, + 'data_key' => 'test', + 'data_value' => 'TRUE', + ]); + $criteria = [ + 'user_id' => 99, + ]; + $this->seeNumRecords(1, $this->config->dbTableUserVariables, $criteria); + $this->model->deleteAllByUserId(99); + $this->seeNumRecords(0, $this->config->dbTableUserVariables, $criteria); + } + public function testAsArrayFirst() { $this->hasInDatabase($this->config->dbTableUserVariables, [ diff --git a/tests/Aauth/Libraries/Aauth/AccessTest.php b/tests/Aauth/Libraries/Aauth/AccessTest.php new file mode 100644 index 0000000..7131c19 --- /dev/null +++ b/tests/Aauth/Libraries/Aauth/AccessTest.php @@ -0,0 +1,242 @@ +response = service('response'); + $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent()); + Services::injectMock('request', $this->request); + + $this->library = new Aauth(null, true); + $_COOKIE = []; + $_SESSION = []; + } + + public function tearDown() + { + } + + protected function getInstance($options = []) + { + $defaults = [ + 'sessionDriver' => 'CodeIgniter\Session\Handlers\FileHandler', + 'sessionCookieName' => 'ci_session', + 'sessionExpiration' => 7200, + 'sessionSavePath' => 'null', + 'sessionMatchIP' => false, + 'sessionTimeToUpdate' => 300, + 'sessionRegenerateDestroy' => false, + 'cookieDomain' => '', + 'cookiePrefix' => '', + 'cookiePath' => '/', + 'cookieSecure' => false, + ]; + + $config = (object)$defaults; + + $session = new MockSession(new FileHandler($config, Services::request()->getIPAddress()), $config); + $session->setLogger(new TestLogger(new Logger())); + $session->start(); + + return $session; + } + + //-------------------------------------------------------------------- + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testIsLoggedIn() + { + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'loggedIn' => true, + ]); + $this->assertTrue($this->library->isLoggedIn()); + $session->remove('user'); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testIsMember() + { + $config = new AauthConfig(); + $this->assertTrue($this->library->isMember($config->groupDefault, 1)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + $this->assertTrue($this->library->isMember($config->groupDefault)); + $session->remove('user'); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testIsAdmin() + { + $this->assertTrue($this->library->isAdmin(1)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + $this->assertTrue($this->library->isAdmin()); + $session->remove('user'); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testIsAllowed() + { + $config = new AauthConfig(); + $this->hasInDatabase($config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + + $this->assertTrue($this->library->isAllowed('testPerm1', 1)); + $this->assertFalse($this->library->isAllowed('testPerm1', 2)); + + $this->hasInDatabase($config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 2, + ]); + $this->assertTrue($this->library->isAllowed('testPerm1', 2)); + + $this->hasInDatabase($config->dbTablePermToUser, [ + 'perm_id' => 1, + 'user_id' => 2, + ]); + $this->assertTrue($this->library->isAllowed('testPerm1', 2)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + $this->assertTrue($this->library->isAllowed('testPerm1')); + $session->remove('user'); + + $this->assertFalse($this->library->isAllowed('testPerm99', 2)); + $this->assertFalse($this->library->isAllowed('testPerm1', 99)); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testIsGroupAllowed() + { + $config = new AauthConfig(); + $this->hasInDatabase($config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + + $this->assertTrue($this->library->isGroupAllowed('testPerm1', $config->groupAdmin)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + + $session->set('user', [ + 'id' => 2, + 'loggedIn' => true, + ]); + $this->assertFalse($this->library->isGroupAllowed('testPerm1')); + $session->remove('user'); + + $this->hasInDatabase($config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 2, + ]); + $this->assertTrue($this->library->isGroupAllowed('testPerm1', 2)); + + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + $this->assertTrue($this->library->isGroupAllowed('testPerm1')); + $session->remove('user'); + + $session->set('user', [ + 'id' => 2, + 'loggedIn' => true, + ]); + $this->assertTrue($this->library->isGroupAllowed('testPerm1')); + $session->remove('user'); + + $this->assertFalse($this->library->isGroupAllowed('testPerm1')); + $this->assertFalse($this->library->isGroupAllowed('testPerm1', 3)); + $this->assertFalse($this->library->isGroupAllowed('testPerm99', 2)); + $this->assertFalse($this->library->isGroupAllowed('testPerm1', 99)); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testIsGroupAllowedSubgroup() + { + $config = new AauthConfig(); + $this->hasInDatabase($config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroups1', + 'definition' => 'Test Group 1', + ]); + + $this->hasInDatabase($config->dbTableGroupToGroup, [ + 'group_id' => 2, + 'subgroup_id' => 4, + ]); + $this->hasInDatabase($config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 4, + ]); + $this->assertTrue($this->library->isGroupAllowed('testPerm1', 2)); + } +} diff --git a/tests/Aauth/Libraries/Aauth/ErrorsTest.php b/tests/Aauth/Libraries/Aauth/ErrorsTest.php index 5311b97..5328e2d 100644 --- a/tests/Aauth/Libraries/Aauth/ErrorsTest.php +++ b/tests/Aauth/Libraries/Aauth/ErrorsTest.php @@ -7,10 +7,6 @@ use Tests\Support\Session\MockSession; use CodeIgniter\Session\Handlers\FileHandler; use App\Libraries\Aauth; -/** - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - */ class ErrorsTest extends \CIUnitTestCase { public function setUp() @@ -78,6 +74,10 @@ class ErrorsTest extends \CIUnitTestCase $this->expectOutputString('test message 1
test message 2'); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testClearErrors() { $session = $this->getInstance(); @@ -89,6 +89,10 @@ class ErrorsTest extends \CIUnitTestCase $this->assertNull($session->getFlashdata('errors')); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testErrorsFlash() { $session = $this->getInstance(); @@ -104,6 +108,10 @@ class ErrorsTest extends \CIUnitTestCase $this->assertEquals(['test message 1', 'test message 2'], $session->getFlashdata('errors')); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testKeepErrors() { $session = $this->getInstance(); diff --git a/tests/Aauth/Libraries/Aauth/GroupTest.php b/tests/Aauth/Libraries/Aauth/GroupTest.php new file mode 100644 index 0000000..e4a357b --- /dev/null +++ b/tests/Aauth/Libraries/Aauth/GroupTest.php @@ -0,0 +1,342 @@ +response = service('response'); + $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent()); + Services::injectMock('request', $this->request); + + $this->config = new AauthConfig(); + $this->library = new Aauth(null, true); + $_COOKIE = []; + $_SESSION = []; + } + + public function tearDown() + { + } + + protected function getInstance($options = []) + { + $defaults = [ + 'sessionDriver' => 'CodeIgniter\Session\Handlers\FileHandler', + 'sessionCookieName' => 'ci_session', + 'sessionExpiration' => 7200, + 'sessionSavePath' => 'null', + 'sessionMatchIP' => false, + 'sessionTimeToUpdate' => 300, + 'sessionRegenerateDestroy' => false, + 'cookieDomain' => '', + 'cookiePrefix' => '', + 'cookiePath' => '/', + 'cookieSecure' => false, + ]; + + $config = (object)$defaults; + + $session = new MockSession(new FileHandler($config, Services::request()->getIPAddress()), $config); + $session->setLogger(new TestLogger(new Logger())); + $session->start(); + + return $session; + } + + //-------------------------------------------------------------------- + + public function testCreateGroup() + { + $this->library->createGroup('testGroup1', 'Test Group 1'); + $this->seeInDatabase($this->config->dbTableGroups, [ + 'name' => 'testGroup1', + 'definition' => 'Test Group 1', + ]); + + $this->assertFalse($this->library->createGroup('admin')); + $this->assertEquals(lang('Aauth.existsAlreadyGroup'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->createGroup('')); + $this->assertEquals(lang('Aauth.requiredGroupName'), $this->library->getErrorsArray()[0]); + } + + public function testUpdateGroup() + { + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroup1', + 'definition' => 'Test Group 1', + ]); + $this->library->updateGroup('testGroup1', 'testGroup1N', 'Test Group 1 New'); + $this->seeInDatabase($this->config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroup1N', + 'definition' => 'Test Group 1 New', + ]); + + $this->assertFalse($this->library->updateGroup($this->config->groupAdmin, $this->config->groupDefault)); + $this->assertEquals(lang('Aauth.existsAlreadyGroup'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->updateGroup($this->config->groupAdmin)); + $this->assertCount(0, $this->library->getErrorsArray()); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->updateGroup(99, '')); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->updateGroup('testGroup99 ', '')); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + } + + public function testDeleteGroup() + { + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroup1', + 'definition' => 'Test Group 1', + ]); + $this->assertTrue($this->library->deleteGroup('testGroup1')); + $this->dontSeeInDatabase($this->config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroup1N', + 'definition' => 'Test Group 1 New', + ]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->deleteGroup(99, '')); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->deleteGroup('testGroup99 ', '')); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + } + + public function testAddMember() + { + $this->assertTrue($this->library->addMember(1, 2)); + $this->seeInDatabase($this->config->dbTableGroupToUser, [ + 'group_id' => 1, + 'user_id' => 2, + ]); + + $this->library = new Aauth(null, true); + $this->assertTrue($this->library->addMember(2, 2)); + $this->assertEquals(lang('Aauth.alreadyMemberGroup'), $this->library->getInfosArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->addMember(99, 2)); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->addMember(2, 99)); + $this->assertEquals(lang('Aauth.notFoundUser'), $this->library->getErrorsArray()[0]); + } + + public function testRemoveMember() + { + $this->assertTrue($this->library->removeMember(1, 1)); + $this->dontSeeInDatabase($this->config->dbTableGroupToUser, [ + 'group_id' => 1, + 'user_id' => 1, + ]); + } + + public function testAddSubgroup() + { + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroup1', + 'definition' => 'Test Group 1', + ]); + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 5, + 'name' => 'testGroup2', + 'definition' => 'Test Group 2', + ]); + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 6, + 'name' => 'testGroup3', + 'definition' => 'Test Group 3', + ]); + + $this->library = new Aauth(null, true); + $this->assertTrue($this->library->addSubgroup('testGroup1', 'testGroup2')); + $this->assertTrue($this->library->addSubgroup('testGroup1', 'testGroup3')); + $this->assertFalse($this->library->addSubgroup('testGroup2', 'testGroup1')); + + $this->library = new Aauth(null, true); + $this->assertTrue($this->library->addSubgroup(4, 5)); + $this->assertEquals(lang('Aauth.alreadyMemberSubgroup'), $this->library->getInfosArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->addSubgroup(99, 1)); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->addSubgroup(1, 99)); + $this->assertEquals(lang('Aauth.notFoundSubgroup'), $this->library->getErrorsArray()[0]); + } + + public function testRemoveSubgroup() + { + $this->hasInDatabase($this->config->dbTableGroupToGroup, [ + 'group_id' => 1, + 'subgroup_id' => 2, + ]); + $this->assertTrue($this->library->removeSubgroup(1, 2)); + $this->dontSeeInDatabase($this->config->dbTableGroupToGroup, [ + 'group_id' => 1, + 'subgroup_id' => 2, + ]); + } + + public function testRemoveMemberFromAll() + { + $this->assertTrue($this->library->removeMemberFromAll(1)); + $this->dontSeeInDatabase($this->config->dbTableGroupToUser, [ + 'group_id' => 1, + 'user_id' => 1, + ]); + $this->dontSeeInDatabase($this->config->dbTableGroupToUser, [ + 'group_id' => 2, + 'user_id' => 1, + ]); + } + + public function testListGroups() + { + $groups = $this->library->listGroups(); + $this->assertCount(3, $groups); + $this->assertEquals($this->config->groupAdmin, $groups[0]['name']); + $this->assertEquals($this->config->groupDefault, $groups[1]['name']); + } + + public function testListGroupsPaginated() + { + $groups = $this->library->listGroupsPaginated(); + $this->assertTrue(isset($groups['pager'])); + $this->assertCount(3, $groups['groups']); + $this->assertEquals($this->config->groupAdmin, $groups['groups'][0]['name']); + $this->assertEquals($this->config->groupDefault, $groups['groups'][1]['name']); + + $groupsOrderBy = $this->library->listGroupsPaginated(10, 'id DESC'); + $this->assertEquals($this->config->groupPublic, $groupsOrderBy['groups'][0]['name']); + $this->assertEquals($this->config->groupDefault, $groupsOrderBy['groups'][1]['name']); + } + + public function testListUserGroups() + { + $groups = $this->library->listUserGroups(1); + $this->assertCount(2, $groups); + $this->assertEquals($this->config->groupAdmin, $groups[0]['name']); + $this->assertEquals($this->config->groupDefault, $groups[1]['name']); + + $this->assertFalse($this->library->listUserGroups(99)); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testListUserGroupsPaginated() + { + $groups = $this->library->listUserGroupsPaginated(1); + $this->assertTrue(isset($groups['pager'])); + $this->assertCount(2, $groups['groups']); + $this->assertEquals($this->config->groupAdmin, $groups['groups'][0]['name']); + $this->assertEquals($this->config->groupDefault, $groups['groups'][1]['name']); + + $groupsOrderBy = $this->library->listUserGroupsPaginated(1, 10, 'id DESC'); + $this->assertEquals($this->config->groupDefault, $groupsOrderBy['groups'][0]['name']); + $this->assertEquals($this->config->groupAdmin, $groupsOrderBy['groups'][1]['name']); + + $this->assertFalse($this->library->listUserGroupsPaginated(99)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + $groups = $this->library->listUserGroupsPaginated(); + $this->assertCount(2, $groups['groups']); + } + + public function testGetGroupName() + { + $this->assertEquals($this->config->groupAdmin, $this->library->getGroupName(1)); + $this->assertFalse($this->library->getGroupName(99)); + } + + public function testGetGroupId() + { + $this->assertEquals(1, $this->library->getGroupId($this->config->groupAdmin)); + $this->assertEquals(1, $this->library->getGroupId(1)); + $this->assertFalse($this->library->getGroupId('testGroup99')); + } + + public function testGetGroup() + { + $group = $this->library->getGroup($this->config->groupAdmin); + $this->assertEquals(1, $group['id']); + $group = $this->library->getGroup(1); + $this->assertEquals($this->config->groupAdmin, $group['name']); + $this->assertFalse($this->library->getGroup('testGroup99')); + $this->assertFalse($this->library->getGroup(99)); + } + + public function testGetSubgroups() + { + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 4, + 'name' => 'testGroup1', + 'definition' => 'Test Group 1', + ]); + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 5, + 'name' => 'testGroup2', + 'definition' => 'Test Group 2', + ]); + $this->hasInDatabase($this->config->dbTableGroups, [ + 'id' => 6, + 'name' => 'testGroup3', + 'definition' => 'Test Group 3', + ]); + + $this->library = new Aauth(null, true); + $this->assertTrue($this->library->addSubgroup('testGroup1', 'testGroup2')); + $this->assertTrue($this->library->addSubgroup('testGroup1', 'testGroup3')); + + $subgroups = $this->library->getSubgroups(4); + $this->assertCount(2, $subgroups); + $this->assertEquals([['subgroup_id' => '5'], ['subgroup_id' => '6']], $subgroups); + $this->assertFalse($this->library->getSubgroups('testGroup99')); + $this->assertFalse($this->library->getSubgroups(99)); + } +} diff --git a/tests/Aauth/Libraries/Aauth/InfosTest.php b/tests/Aauth/Libraries/Aauth/InfosTest.php index b490ec4..bd31e16 100644 --- a/tests/Aauth/Libraries/Aauth/InfosTest.php +++ b/tests/Aauth/Libraries/Aauth/InfosTest.php @@ -7,10 +7,6 @@ use Tests\Support\Session\MockSession; use CodeIgniter\Session\Handlers\FileHandler; use App\Libraries\Aauth; -/** - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - */ class InfosTest extends \CIUnitTestCase { public function setUp() @@ -78,6 +74,10 @@ class InfosTest extends \CIUnitTestCase $this->expectOutputString('test message 1
test message 2'); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testClearInfos() { $session = $this->getInstance(); @@ -89,6 +89,10 @@ class InfosTest extends \CIUnitTestCase $this->assertNull($session->getFlashdata('infos')); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testInfosFlash() { $session = $this->getInstance(); @@ -104,6 +108,10 @@ class InfosTest extends \CIUnitTestCase $this->assertEquals(['test message 1', 'test message 2'], $session->getFlashdata('infos')); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testKeepInfos() { $session = $this->getInstance(); diff --git a/tests/Aauth/Libraries/Aauth/LoginTest.php b/tests/Aauth/Libraries/Aauth/LoginTest.php index 6bf971d..5e5b3f3 100644 --- a/tests/Aauth/Libraries/Aauth/LoginTest.php +++ b/tests/Aauth/Libraries/Aauth/LoginTest.php @@ -32,14 +32,14 @@ class LoginTest extends CIDatabaseTestCase { parent::setUp(); - Services::injectMock('response', new MockResponse(new App())); - $this->response = service('response'); + Services::injectMock('response', new MockResponse(new App())); + $this->response = service('response'); $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent()); - Services::injectMock('request', $this->request); + Services::injectMock('request', $this->request); - $this->library = new Aauth(null, true); - $_COOKIE = []; - $_SESSION = []; + $this->library = new Aauth(null, true); + $_COOKIE = []; + $_SESSION = []; } public function tearDown() @@ -133,17 +133,6 @@ class LoginTest extends CIDatabaseTestCase $this->assertEquals(lang('Aauth.loginAttemptsExceeded'), $this->library->getErrorsArray()[0]); } - public function testIsLoggedIn() - { - $session = $this->getInstance(); - $this->library = new Aauth(null, $session); - $session->set('user', [ - 'loggedIn' => true, - ]); - $this->assertTrue($this->library->isLoggedIn()); - $session->remove('user'); - } - public function testIsLoggedInCookie() { helper('text'); @@ -165,7 +154,7 @@ class LoginTest extends CIDatabaseTestCase $this->library->logout(); } - public function testIsLoggedInCookieInvalidUser($value='') + public function testIsLoggedInCookieInvalidUser($value = '') { helper('text'); $session = $this->getInstance(); @@ -186,7 +175,7 @@ class LoginTest extends CIDatabaseTestCase unset($_COOKIE['remember']); } - public function testIsLoggedInCookieInvalidCookie($value='') + public function testIsLoggedInCookieInvalidCookie($value = '') { helper('text'); $session = $this->getInstance(); @@ -201,7 +190,7 @@ class LoginTest extends CIDatabaseTestCase unset($_COOKIE['remember']); } - public function testIsLoggedInCookieExpired($value='') + public function testIsLoggedInCookieExpired($value = '') { helper('text'); $session = $this->getInstance(); diff --git a/tests/Aauth/Libraries/Aauth/PermTest.php b/tests/Aauth/Libraries/Aauth/PermTest.php new file mode 100644 index 0000000..476ba8b --- /dev/null +++ b/tests/Aauth/Libraries/Aauth/PermTest.php @@ -0,0 +1,451 @@ +library = new Aauth(null, true); + $this->config = new AauthConfig(); + $_COOKIE = []; + $_SESSION = []; + } + + public function tearDown() + { + } + + protected function getInstance($options = []) + { + $defaults = [ + 'sessionDriver' => 'CodeIgniter\Session\Handlers\FileHandler', + 'sessionCookieName' => 'ci_session', + 'sessionExpiration' => 7200, + 'sessionSavePath' => 'null', + 'sessionMatchIP' => false, + 'sessionTimeToUpdate' => 300, + 'sessionRegenerateDestroy' => false, + 'cookieDomain' => '', + 'cookiePrefix' => '', + 'cookiePath' => '/', + 'cookieSecure' => false, + ]; + + $config = (object)$defaults; + + $session = new MockSession(new FileHandler($config, Services::request()->getIPAddress()), $config); + $session->setLogger(new TestLogger(new Logger())); + $session->start(); + + return $session; + } + + //-------------------------------------------------------------------- + + public function testCreatePerm() + { + $this->library->createPerm('testPerm1', 'Test Perm 1'); + $this->seeInDatabase($this->config->dbTablePerms, [ + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + + $this->assertFalse($this->library->createPerm('testPerm1')); + $this->assertEquals(lang('Aauth.existsAlreadyPerm'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->createPerm('')); + $this->assertEquals(lang('Aauth.requiredPermName'), $this->library->getErrorsArray()[0]); + } + + public function testUpdatePerm() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 2, + 'name' => 'testPerm2', + 'definition' => 'Test Perm 2', + ]); + $this->library->updatePerm('testPerm1', 'testPerm1N', 'Test Perm 1 New'); + $this->seeInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1N', + 'definition' => 'Test Perm 1 New', + ]); + + $this->assertFalse($this->library->updatePerm('testPerm1N', 'testPerm2')); + $this->assertEquals(lang('Aauth.existsAlreadyPerm'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->updatePerm('testPerm1')); + $this->assertCount(0, $this->library->getErrorsArray()); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->updatePerm(99, '')); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->updatePerm('testPerm99', '')); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + } + + public function testDeletePerm() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->assertTrue($this->library->deletePerm('testPerm1')); + $this->dontSeeInDatabase($this->config->dbTablePerms, [ + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + 'deleted' => 0, + ]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->deletePerm(99)); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->deletePerm('testPerm99')); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + } + + public function testListPerms() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 2, + 'name' => 'testPerm2', + 'definition' => 'Test Perm 2', + ]); + $perms = $this->library->listPerms(); + $this->assertCount(2, $perms); + $this->assertEquals('testPerm1', $perms[0]['name']); + $this->assertEquals('testPerm2', $perms[1]['name']); + } + + public function testListPermsPaginated() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 2, + 'name' => 'testPerm2', + 'definition' => 'Test Perm 2', + ]); + + $perms = $this->library->listPermsPaginated(); + $this->assertTrue(isset($perms['pager'])); + $this->assertCount(2, $perms['perms']); + $this->assertEquals('testPerm1', $perms['perms'][0]['name']); + $this->assertEquals('testPerm2', $perms['perms'][1]['name']); + + $permsOrderBy = $this->library->listPermsPaginated(10, 'id DESC'); + $this->assertEquals('testPerm2', $permsOrderBy['perms'][0]['name']); + $this->assertEquals('testPerm1', $permsOrderBy['perms'][1]['name']); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testListUserPerms() + { + $perms = $this->library->listUserPerms(1); + $this->assertCount(0, $perms); + + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 1, + 'user_id' => 1, + 'state' => 1, + ]); + + $perms = $this->library->listUserPerms(1); + $this->assertCount(1, $perms); + $this->assertEquals('testPerm1', $perms[0]['name']); + + $this->assertFalse($this->library->listUserPerms(99)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + + $perms = $this->library->listUserPerms(); + $this->assertCount(1, $perms); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testListUserPermsPaginated() + { + $perms = $this->library->listUserPermsPaginated(1); + $this->assertCount(0, $perms['perms']); + + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 2, + 'name' => 'testPerm2', + 'definition' => 'Test Perm 2', + ]); + $this->hasInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 1, + 'user_id' => 1, + 'state' => 1, + ]); + $this->hasInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 2, + 'user_id' => 1, + 'state' => 1, + ]); + + $this->assertFalse($this->library->listUserPermsPaginated(99)); + + $perms = $this->library->listUserPermsPaginated(1); + $this->assertTrue(isset($perms['pager'])); + $this->assertCount(2, $perms['perms']); + $this->assertEquals('testPerm1', $perms['perms'][0]['name']); + $this->assertEquals('testPerm2', $perms['perms'][1]['name']); + + $permsOrderBy = $this->library->listUserPermsPaginated(1, 10, 'id DESC'); + $this->assertEquals('testPerm2', $permsOrderBy['perms'][0]['name']); + $this->assertEquals('testPerm1', $permsOrderBy['perms'][1]['name']); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + 'loggedIn' => true, + ]); + $perms = $this->library->listUserPermsPaginated(); + $this->assertCount(2, $perms['perms']); + } + + public function testGetPermId() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + + $this->assertEquals(1, $this->library->getPermId('testPerm1')); + $this->assertEquals(1, $this->library->getPermId(1)); + $this->assertFalse($this->library->getPermId('testPerm99')); + } + + public function testGetPerm() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + + $perm = $this->library->getPerm('testPerm1'); + $this->assertEquals(1, $perm['id']); + $perm = $this->library->getPerm(1); + $this->assertEquals('testPerm1', $perm['name']); + $this->assertFalse($this->library->getPerm('testPerm99')); + $this->assertFalse($this->library->getPerm(99)); + } + + public function testAllowUser() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->assertTrue($this->library->allowUser(1, 1)); + $this->seeInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 1, + 'user_id' => 1, + 'state' => 1, + ]); + + $this->assertTrue($this->library->allowUser(1, 1)); + $this->assertFalse($this->library->allowUser(99, 1)); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->allowUser(1, 99)); + $this->assertEquals(lang('Aauth.notFoundUser'), $this->library->getErrorsArray()[0]); + } + + public function testDenyUser() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->assertTrue($this->library->denyUser(1, 1)); + $this->seeInDatabase($this->config->dbTablePermToUser, [ + 'perm_id' => 1, + 'user_id' => 1, + 'state' => 0, + ]); + + $this->assertTrue($this->library->denyUser(1, 1)); + $this->assertFalse($this->library->denyUser(99, 1)); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->denyUser(1, 99)); + $this->assertEquals(lang('Aauth.notFoundUser'), $this->library->getErrorsArray()[0]); + } + + public function testAllowGroup() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->assertTrue($this->library->allowGroup(1, 1)); + $this->seeInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 1, + 'state' => 1, + ]); + + $this->assertTrue($this->library->allowGroup(1, 1)); + $this->assertFalse($this->library->allowGroup(99, 1)); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->allowGroup(1, 99)); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + } + + public function testDenyGroup() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->assertTrue($this->library->denyGroup(1, 1)); + $this->seeInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 1, + 'state' => 0, + ]); + + $this->assertTrue($this->library->denyGroup(1, 1)); + $this->assertFalse($this->library->denyGroup(99, 1)); + $this->assertEquals(lang('Aauth.notFoundPerm'), $this->library->getErrorsArray()[0]); + $this->library = new Aauth(null, true); + $this->assertFalse($this->library->denyGroup(1, 99)); + $this->assertEquals(lang('Aauth.notFoundGroup'), $this->library->getErrorsArray()[0]); + } + + public function testListGroupPerms() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 2, + 'name' => 'testPerm2', + 'definition' => 'Test Perm 2', + ]); + $this->hasInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 2, + 'state' => 0, + ]); + $this->hasInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 2, + 'group_id' => 2, + 'state' => 1, + ]); + + $groupPerms = $this->library->listGroupPerms($this->config->groupDefault); + + $this->assertCount(2, $groupPerms); + $this->assertEquals('testPerm1', $groupPerms[0]['name']); + $this->assertEquals('0', $groupPerms[0]['state']); + $this->assertEquals('testPerm2', $groupPerms[1]['name']); + $this->assertEquals('1', $groupPerms[1]['state']); + + $this->assertFalse($this->library->listGroupPerms(99)); + } + + public function testListGroupPermsPaginated() + { + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 1, + 'name' => 'testPerm1', + 'definition' => 'Test Perm 1', + ]); + $this->hasInDatabase($this->config->dbTablePerms, [ + 'id' => 2, + 'name' => 'testPerm2', + 'definition' => 'Test Perm 2', + ]); + $this->hasInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 1, + 'group_id' => 2, + 'state' => 0, + ]); + $this->hasInDatabase($this->config->dbTablePermToGroup, [ + 'perm_id' => 2, + 'group_id' => 2, + 'state' => 1, + ]); + + $groupPerms = $this->library->listGroupPermsPaginated(2); + $this->assertTrue(isset($groupPerms['pager'])); + $this->assertCount(2, $groupPerms['perms']); + $this->assertEquals('testPerm1', $groupPerms['perms'][0]['name']); + $this->assertEquals('0', $groupPerms['perms'][0]['state']); + $this->assertEquals('testPerm2', $groupPerms['perms'][1]['name']); + $this->assertEquals('1', $groupPerms['perms'][1]['state']); + + $groupPermsOrderBy = $this->library->listGroupPermsPaginated(2, 10, 'id DESC'); + $this->assertEquals('testPerm2', $groupPermsOrderBy['perms'][0]['name']); + $this->assertEquals('testPerm1', $groupPermsOrderBy['perms'][1]['name']); + } +} diff --git a/tests/Aauth/Libraries/Aauth/UserTest.php b/tests/Aauth/Libraries/Aauth/UserTest.php index f471d91..913caf9 100644 --- a/tests/Aauth/Libraries/Aauth/UserTest.php +++ b/tests/Aauth/Libraries/Aauth/UserTest.php @@ -10,10 +10,6 @@ use CodeIgniter\Test\CIDatabaseTestCase; use App\Libraries\Aauth; use App\Models\Aauth\UserVariableModel; -/** - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - */ class UserTest extends CIDatabaseTestCase { protected $refresh = true; @@ -167,6 +163,19 @@ class UserTest extends CIDatabaseTestCase $this->assertEquals('admin', $usersOrderBy[1]['username']); } + public function testListUsersPaginated() + { + $users = $this->library->listUsersPaginated(); + $this->assertTrue(isset($users['pager'])); + $this->assertCount(2, $users['users']); + $this->assertEquals('admin', $users['users'][0]['username']); + $this->assertEquals('user', $users['users'][1]['username']); + + $usersOrderBy = $this->library->listUsersPaginated(10, null, 'id DESC'); + $this->assertEquals('user', $usersOrderBy['users'][0]['username']); + $this->assertEquals('admin', $usersOrderBy['users'][1]['username']); + } + public function testVerifyUser() { $userVariableModel = new UserVariableModel(); @@ -179,6 +188,10 @@ class UserTest extends CIDatabaseTestCase $this->assertEquals(lang('Aauth.infoVerification'), $this->library->getInfosArray()[0]); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testGetUser() { $user = $this->library->getUser(1); @@ -201,6 +214,10 @@ class UserTest extends CIDatabaseTestCase $this->assertEquals(lang('Aauth.notFoundUser'), $this->library->getErrorsArray()[0]); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testGetUserId() { $userIdEmail = $this->library->getUserId('admin@example.com'); @@ -250,6 +267,10 @@ class UserTest extends CIDatabaseTestCase $this->assertEquals(lang('Aauth.notFoundUser'), $this->library->getErrorsArray()[0]); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ public function testBanUnbanUserSession() { $session = $this->getInstance(); diff --git a/tests/Aauth/Libraries/Aauth/UserVariablesTest.php b/tests/Aauth/Libraries/Aauth/UserVariablesTest.php new file mode 100644 index 0000000..30c2ff5 --- /dev/null +++ b/tests/Aauth/Libraries/Aauth/UserVariablesTest.php @@ -0,0 +1,187 @@ +library = new Aauth(null, true); + $this->config = new AauthConfig(); + $_COOKIE = []; + $_SESSION = []; + } + + public function tearDown() + { + } + + protected function getInstance($options = []) + { + $defaults = [ + 'sessionDriver' => 'CodeIgniter\Session\Handlers\FileHandler', + 'sessionCookieName' => 'ci_session', + 'sessionExpiration' => 7200, + 'sessionSavePath' => 'null', + 'sessionMatchIP' => false, + 'sessionTimeToUpdate' => 300, + 'sessionRegenerateDestroy' => false, + 'cookieDomain' => '', + 'cookiePrefix' => '', + 'cookiePath' => '/', + 'cookieSecure' => false, + ]; + + $config = (object)$defaults; + + $session = new MockSession(new FileHandler($config, Services::request()->getIPAddress()), $config); + $session->setLogger(new TestLogger(new Logger())); + $session->start(); + + return $session; + } + + //-------------------------------------------------------------------- + + public function testSetUserVar() + { + $this->assertTrue($this->library->setUserVar('test_var', 'test', 1)); + $this->seeInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var', + 'data_value' => 'test', + ]); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + ]); + + $this->assertTrue($this->library->setUserVar('test_var', 'test2')); + $this->seeInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var', + 'data_value' => 'test2', + ]); + + $this->assertFalse($this->library->setUserVar('test_var', 'test', 99)); + } + + public function testUnsetUserVar() + { + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var', + 'data_value' => 'test', + ]); + + $this->assertTrue($this->library->unsetUserVar('test_var', 1)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + ]); + + $this->assertTrue($this->library->unsetUserVar('test_var')); + + $this->assertFalse($this->library->unsetUserVar('test_var', 99)); + } + + public function testGetUserVar() + { + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var', + 'data_value' => 'test', + ]); + + $this->assertEquals('test', $this->library->getUserVar('test_var', 1)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + ]); + + $this->assertEquals('test', $this->library->getUserVar('test_var')); + + $this->assertFalse($this->library->getUserVar('test_var_99', 1)); + + $this->assertFalse($this->library->getUserVar('test_var', 99)); + } + + public function testGetUserVars() + { + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var', + 'data_value' => 'test', + ]); + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var2', + 'data_value' => 'test2', + ]); + + $this->assertCount(2, $this->library->getUserVars(1)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + ]); + + $this->assertCount(2, $this->library->getUserVars()); + + $this->assertFalse($this->library->getUserVars(99)); + } + + public function testListUserVarKeys() + { + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var', + 'data_value' => 'test', + ]); + $this->hasInDatabase($this->config->dbTableUserVariables, [ + 'user_id' => 1, + 'data_key' => 'test_var2', + 'data_value' => 'test2', + ]); + + $this->assertCount(2, $this->library->listUserVarKeys(1)); + $this->assertEquals([['key' => 'test_var'], ['key' => 'test_var2']], $this->library->listUserVarKeys(1)); + + $session = $this->getInstance(); + $this->library = new Aauth(null, $session); + $session->set('user', [ + 'id' => 1, + ]); + + $this->assertCount(2, $this->library->listUserVarKeys()); + + $this->assertFalse($this->library->listUserVarKeys(99)); + } +}