diff --git a/docs/customization.md b/docs/customization.md index e7e2e0d65..6e21b7564 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -1,18 +1,40 @@ # Customizing Shield -- [Customizing Shield](#customizing-shield) - - [Route Configuration](#route-configuration) - - [Custom Redirect URLs](#custom-redirect-urls) - - [Customize Login Redirect](#customize-login-redirect) - - [Customize Register Redirect](#customize-register-redirect) - - [Customize Logout Redirect](#customize-logout-redirect) - - [Extending the Controllers](#extending-the-controllers) - - [Integrating Custom View Libraries](#integrating-custom-view-libraries) - - [Custom Validation Rules](#custom-validation-rules) - - [Registration](#registration) - - [Login](#login) - - [Custom User Provider](#custom-user-provider) - - [Custom Login Identifier](#custom-login-identifier) +- [Customizing Shield](#customizing-shield) + - [Custom Table Names](#custom-table-names) + - [Route Configuration](#route-configuration) + - [Custom Redirect URLs](#custom-redirect-urls) + - [Customize Login Redirect](#customize-login-redirect) + - [Customize Register Redirect](#customize-register-redirect) + - [Customize Logout Redirect](#customize-logout-redirect) + - [Extending the Controllers](#extending-the-controllers) + - [Integrating Custom View Libraries](#integrating-custom-view-libraries) + - [Custom Validation Rules](#custom-validation-rules) + - [Registration](#registration) + - [Login](#login) + - [Custom User Provider](#custom-user-provider) + - [Custom Login Identifier](#custom-login-identifier) + +## Custom Table Names + +If you want to change the default table names, you can change the table names +in **app/Config/Auth.php**. + +```php +public array $tables = [ + 'users' => 'users', + 'identities' => 'auth_identities', + 'logins' => 'auth_logins', + 'token_logins' => 'auth_token_logins', + 'remember_tokens' => 'auth_remember_tokens', + 'groups_users' => 'auth_groups_users', + 'permissions_users' => 'auth_permissions_users', +]; +``` + +Set the table names that you want in the array values. + +> **Note** You must change the table names before running database migrations. ## Route Configuration @@ -149,24 +171,40 @@ Shield has the following rules for registration: ```php [ 'username' => [ - 'label' => 'Auth.username', - 'rules' => 'required|max_length[30]|min_length[3]|regex_match[/\A[a-zA-Z0-9\.]+\z/]|is_unique[users.username]', + 'label' => 'Auth.username', + 'rules' => [ + 'required', + 'max_length[30]', + 'min_length[3]', + 'regex_match[/\A[a-zA-Z0-9\.]+\z/]', + 'is_unique[users.username]', + ], ], 'email' => [ - 'label' => 'Auth.email', - 'rules' => 'required|max_length[254]|valid_email|is_unique[auth_identities.secret]', + 'label' => 'Auth.email', + 'rules' => [ + 'required', + 'max_length[254]', + 'valid_email', + 'is_unique[auth_identities.secret]', + ], ], 'password' => [ - 'label' => 'Auth.password', + 'label' => 'Auth.password', 'rules' => 'required|strong_password', ], 'password_confirm' => [ - 'label' => 'Auth.passwordConfirm', + 'label' => 'Auth.passwordConfirm', 'rules' => 'required|matches[password]', ], ]; ``` +> **Note** If you customize the table names, the table names +> (`users` and `auth_identities`) in the above rules will be automatically +> changed. The rules are implemented in +> `RegisterController::getValidationRules()`. + If you need a different set of rules for registration, you can specify them in your `Validation` configuration (**app/Config/Validation.php**) like: ```php @@ -175,24 +213,38 @@ If you need a different set of rules for registration, you can specify them in y //-------------------------------------------------------------------- public $registration = [ 'username' => [ - 'label' => 'Auth.username', - 'rules' => 'required|max_length[30]|min_length[3]|regex_match[/\A[a-zA-Z0-9\.]+\z/]|is_unique[users.username]', + 'label' => 'Auth.username', + 'rules' => [ + 'required', + 'max_length[30]', + 'min_length[3]', + 'regex_match[/\A[a-zA-Z0-9\.]+\z/]', + 'is_unique[users.username]', + ], ], 'email' => [ - 'label' => 'Auth.email', - 'rules' => 'required|max_length[254]|valid_email|is_unique[auth_identities.secret]', + 'label' => 'Auth.email', + 'rules' => [ + 'required', + 'max_length[254]', + 'valid_email', + 'is_unique[auth_identities.secret]', + ], ], 'password' => [ - 'label' => 'Auth.password', + 'label' => 'Auth.password', 'rules' => 'required|strong_password', ], 'password_confirm' => [ - 'label' => 'Auth.passwordConfirm', + 'label' => 'Auth.passwordConfirm', 'rules' => 'required|matches[password]', ], ]; ``` +> **Note** If you customize the table names, set the correct table names in the +> rules. + ### Login Similar to the process for validation rules in the **Registration** section, you can add rules for the login form to **app/Config/Validation.php** and change the rules. diff --git a/docs/install.md b/docs/install.md index 19ab589c2..3720e6ec9 100644 --- a/docs/install.md +++ b/docs/install.md @@ -74,6 +74,10 @@ Require it with an explicit version constraint allowing its desired stability. php spark shield:setup ``` + > **Note** If you want to customize table names, you must change the table names + > before running database migrations. + > See [Customizing Shield](./customization.md#custom-table-names). + 2. Configure **app/Config/Email.php** to allow Shield to send emails with the [Email Class](https://codeigniter.com/user_guide/libraries/email.html). ```php @@ -145,6 +149,10 @@ your project. 5. **Migration** Run the migrations. + > **Note** If you want to customize table names, you must change the table names + > before running database migrations. + > See [Customizing Shield](./customization.md#custom-table-names). + ```console php spark migrate --all ``` @@ -278,4 +286,4 @@ public $globals = [ ] ] ``` -The same should apply for the Rate Limiting and Forcing Password Reset. \ No newline at end of file +The same should apply for the Rate Limiting and Forcing Password Reset. diff --git a/src/Config/Auth.php b/src/Config/Auth.php index 3f05045c7..57862293a 100644 --- a/src/Config/Auth.php +++ b/src/Config/Auth.php @@ -37,6 +37,36 @@ class Auth extends BaseConfig 'magic-link-email' => '\CodeIgniter\Shield\Views\Email\magic_link_email', ]; + /** + * -------------------------------------------------------------------- + * Customize Name of Shield Tables + * -------------------------------------------------------------------- + * Only change if you want to rename the default Shield table names + * + * It may be necessary to change the names of the tables for + * security reasons, to prevent the conflict of table names, + * the internal policy of the companies or any other reason. + * + * - users Auth Users Table, the users info is stored. + * - auth_identities Auth Identities Table, Used for storage of passwords, access tokens, social login identities, etc. + * - auth_logins Auth Login Attempts, Table records login attempts. + * - auth_token_logins Auth Token Login Attempts Table, Records Bearer Token type login attempts. + * - auth_remember_tokens Auth Remember Tokens (remember-me) Table. + * - auth_groups_users Groups Users Table. + * - auth_permissions_users Users Permissions Table. + * + * @var array + */ + public array $tables = [ + 'users' => 'users', + 'identities' => 'auth_identities', + 'logins' => 'auth_logins', + 'token_logins' => 'auth_token_logins', + 'remember_tokens' => 'auth_remember_tokens', + 'groups_users' => 'auth_groups_users', + 'permissions_users' => 'auth_permissions_users', + ]; + /** * -------------------------------------------------------------------- * Redirect URLs diff --git a/src/Controllers/RegisterController.php b/src/Controllers/RegisterController.php index 784f785bd..041c1d65a 100644 --- a/src/Controllers/RegisterController.php +++ b/src/Controllers/RegisterController.php @@ -7,11 +7,15 @@ use App\Controllers\BaseController; use CodeIgniter\Events\Events; use CodeIgniter\HTTP\RedirectResponse; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Shield\Authentication\Authenticators\Session; +use CodeIgniter\Shield\Config\Auth; use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Exceptions\ValidationException; use CodeIgniter\Shield\Models\UserModel; use CodeIgniter\Shield\Traits\Viewable; +use Psr\Log\LoggerInterface; /** * Class RegisterController @@ -25,6 +29,27 @@ class RegisterController extends BaseController protected $helpers = ['setting']; + /** + * Auth Table names + */ + private array $tables; + + public function initController( + RequestInterface $request, + ResponseInterface $response, + LoggerInterface $logger + ): void { + parent::initController( + $request, + $response, + $logger + ); + + /** @var Auth $authConfig */ + $authConfig = config('Auth'); + $this->tables = $authConfig->tables; + } + /** * Displays the registration form. * @@ -153,11 +178,11 @@ protected function getValidationRules(): array { $registrationUsernameRules = array_merge( config('AuthSession')->usernameValidationRules, - ['is_unique[users.username]'] + [sprintf('is_unique[%s.username]', $this->tables['users'])] ); $registrationEmailRules = array_merge( config('AuthSession')->emailValidationRules, - ['is_unique[auth_identities.secret]'] + [sprintf('is_unique[%s.secret]', $this->tables['identities'])] ); return setting('Validation.registration') ?? [ diff --git a/src/Database/Migrations/2020-12-28-223112_create_auth_tables.php b/src/Database/Migrations/2020-12-28-223112_create_auth_tables.php index f44eb41df..80691cd9b 100644 --- a/src/Database/Migrations/2020-12-28-223112_create_auth_tables.php +++ b/src/Database/Migrations/2020-12-28-223112_create_auth_tables.php @@ -4,10 +4,26 @@ namespace CodeIgniter\Shield\Database\Migrations; +use CodeIgniter\Database\Forge; use CodeIgniter\Database\Migration; +use CodeIgniter\Shield\Config\Auth; class CreateAuthTables extends Migration { + /** + * Auth Table names + */ + private array $tables; + + public function __construct(?Forge $forge = null) + { + parent::__construct($forge); + + /** @var Auth $authConfig */ + $authConfig = config('Auth'); + $this->tables = $authConfig->tables; + } + public function up(): void { // Users Table @@ -24,7 +40,7 @@ public function up(): void ]); $this->forge->addPrimaryKey('id'); $this->forge->addUniqueKey('username'); - $this->forge->createTable('users'); + $this->forge->createTable($this->tables['users']); /* * Auth Identities Table @@ -47,8 +63,8 @@ public function up(): void $this->forge->addPrimaryKey('id'); $this->forge->addUniqueKey(['type', 'secret']); $this->forge->addKey('user_id'); - $this->forge->addForeignKey('user_id', 'users', 'id', '', 'CASCADE'); - $this->forge->createTable('auth_identities'); + $this->forge->addForeignKey('user_id', $this->tables['users'], 'id', '', 'CASCADE'); + $this->forge->createTable($this->tables['identities']); /** * Auth Login Attempts Table @@ -69,7 +85,7 @@ public function up(): void $this->forge->addKey(['id_type', 'identifier']); $this->forge->addKey('user_id'); // NOTE: Do NOT delete the user_id or identifier when the user is deleted for security audits - $this->forge->createTable('auth_logins'); + $this->forge->createTable($this->tables['logins']); /* * Auth Token Login Attempts Table @@ -89,7 +105,7 @@ public function up(): void $this->forge->addKey(['id_type', 'identifier']); $this->forge->addKey('user_id'); // NOTE: Do NOT delete the user_id or identifier when the user is deleted for security audits - $this->forge->createTable('auth_token_logins'); + $this->forge->createTable($this->tables['token_logins']); /* * Auth Remember Tokens (remember-me) Table @@ -106,8 +122,8 @@ public function up(): void ]); $this->forge->addPrimaryKey('id'); $this->forge->addUniqueKey('selector'); - $this->forge->addForeignKey('user_id', 'users', 'id', '', 'CASCADE'); - $this->forge->createTable('auth_remember_tokens'); + $this->forge->addForeignKey('user_id', $this->tables['users'], 'id', '', 'CASCADE'); + $this->forge->createTable($this->tables['remember_tokens']); // Groups Users Table $this->forge->addField([ @@ -117,8 +133,8 @@ public function up(): void 'created_at' => ['type' => 'datetime', 'null' => false], ]); $this->forge->addPrimaryKey('id'); - $this->forge->addForeignKey('user_id', 'users', 'id', '', 'CASCADE'); - $this->forge->createTable('auth_groups_users'); + $this->forge->addForeignKey('user_id', $this->tables['users'], 'id', '', 'CASCADE'); + $this->forge->createTable($this->tables['groups_users']); // Users Permissions Table $this->forge->addField([ @@ -128,8 +144,8 @@ public function up(): void 'created_at' => ['type' => 'datetime', 'null' => false], ]); $this->forge->addPrimaryKey('id'); - $this->forge->addForeignKey('user_id', 'users', 'id', '', 'CASCADE'); - $this->forge->createTable('auth_permissions_users'); + $this->forge->addForeignKey('user_id', $this->tables['users'], 'id', '', 'CASCADE'); + $this->forge->createTable($this->tables['permissions_users']); } // -------------------------------------------------------------------- @@ -138,13 +154,13 @@ public function down(): void { $this->db->disableForeignKeyChecks(); - $this->forge->dropTable('auth_logins', true); - $this->forge->dropTable('auth_token_logins', true); - $this->forge->dropTable('auth_remember_tokens', true); - $this->forge->dropTable('auth_identities', true); - $this->forge->dropTable('auth_groups_users', true); - $this->forge->dropTable('auth_permissions_users', true); - $this->forge->dropTable('users', true); + $this->forge->dropTable($this->tables['logins'], true); + $this->forge->dropTable($this->tables['token_logins'], true); + $this->forge->dropTable($this->tables['remember_tokens'], true); + $this->forge->dropTable($this->tables['identities'], true); + $this->forge->dropTable($this->tables['groups_users'], true); + $this->forge->dropTable($this->tables['permissions_users'], true); + $this->forge->dropTable($this->tables['users'], true); $this->db->enableForeignKeyChecks(); } diff --git a/src/Models/BaseModel.php b/src/Models/BaseModel.php new file mode 100644 index 000000000..b15836da5 --- /dev/null +++ b/src/Models/BaseModel.php @@ -0,0 +1,26 @@ +tables = $authConfig->tables; + } +} diff --git a/src/Models/CheckQueryReturnTrait.php b/src/Models/CheckQueryReturnTrait.php index 777edac1d..2c21441b1 100644 --- a/src/Models/CheckQueryReturnTrait.php +++ b/src/Models/CheckQueryReturnTrait.php @@ -10,12 +10,12 @@ trait CheckQueryReturnTrait { - private ?bool $currentDBDebug = null; + protected ?bool $currentDBDebug = null; /** * @param bool|int|string $return insert() returns insert ID. */ - private function checkQueryReturn($return): void + protected function checkQueryReturn($return): void { $this->restoreDBDebug(); @@ -30,7 +30,7 @@ private function checkQueryReturn($return): void } } - private function checkValidationError(): void + protected function checkValidationError(): void { $validationErrors = $this->getValidationErrors(); @@ -50,14 +50,14 @@ private function checkValidationError(): void * * @return string[] */ - private function getValidationErrors(): array + protected function getValidationErrors(): array { // @TODO When CI v4.3 is released, you don't need this hack. // See https://github.com/codeigniter4/CodeIgniter4/pull/6384 return $this->getValidationPropertyErrors(); } - private function getValidationPropertyErrors(): array + protected function getValidationPropertyErrors(): array { $refClass = new ReflectionObject($this->validation); $refProperty = $refClass->getProperty('errors'); @@ -66,7 +66,7 @@ private function getValidationPropertyErrors(): array return $refProperty->getValue($this->validation); } - private function disableDBDebug(): void + protected function disableDBDebug(): void { if (! $this->db->DBDebug) { // `DBDebug` is false. Do nothing. @@ -79,7 +79,7 @@ private function disableDBDebug(): void $propertyDBDebug->setValue($this->db, false); } - private function restoreDBDebug(): void + protected function restoreDBDebug(): void { if ($this->currentDBDebug === null) { // `DBDebug` has not been changed. Do nothing. @@ -92,7 +92,7 @@ private function restoreDBDebug(): void $this->currentDBDebug = null; } - private function getPropertyDBDebug(): ReflectionProperty + protected function getPropertyDBDebug(): ReflectionProperty { $refClass = new ReflectionObject($this->db); $refProperty = $refClass->getProperty('DBDebug'); diff --git a/src/Models/GroupModel.php b/src/Models/GroupModel.php index 63b426f3c..aa24bea12 100644 --- a/src/Models/GroupModel.php +++ b/src/Models/GroupModel.php @@ -4,14 +4,10 @@ namespace CodeIgniter\Shield\Models; -use CodeIgniter\Model; use CodeIgniter\Shield\Entities\User; -class GroupModel extends Model +class GroupModel extends BaseModel { - use CheckQueryReturnTrait; - - protected $table = 'auth_groups_users'; protected $primaryKey = 'id'; protected $returnType = 'array'; protected $useSoftDeletes = false; @@ -25,6 +21,13 @@ class GroupModel extends Model protected $validationMessages = []; protected $skipValidation = false; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['groups_users']; + } + public function getForUser(User $user): array { $rows = $this->builder() diff --git a/src/Models/LoginModel.php b/src/Models/LoginModel.php index d30981fb0..5cb59491c 100644 --- a/src/Models/LoginModel.php +++ b/src/Models/LoginModel.php @@ -5,17 +5,13 @@ namespace CodeIgniter\Shield\Models; use CodeIgniter\I18n\Time; -use CodeIgniter\Model; use CodeIgniter\Shield\Authentication\Authenticators\Session; use CodeIgniter\Shield\Entities\Login; use CodeIgniter\Shield\Entities\User; use Faker\Generator; -class LoginModel extends Model +class LoginModel extends BaseModel { - use CheckQueryReturnTrait; - - protected $table = 'auth_logins'; protected $primaryKey = 'id'; protected $returnType = Login::class; protected $useSoftDeletes = false; @@ -40,6 +36,13 @@ class LoginModel extends Model protected $validationMessages = []; protected $skipValidation = false; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['logins']; + } + /** * Records login attempt. * diff --git a/src/Models/PermissionModel.php b/src/Models/PermissionModel.php index 1c648623b..a23db8d29 100644 --- a/src/Models/PermissionModel.php +++ b/src/Models/PermissionModel.php @@ -4,14 +4,10 @@ namespace CodeIgniter\Shield\Models; -use CodeIgniter\Model; use CodeIgniter\Shield\Entities\User; -class PermissionModel extends Model +class PermissionModel extends BaseModel { - use CheckQueryReturnTrait; - - protected $table = 'auth_permissions_users'; protected $primaryKey = 'id'; protected $returnType = 'array'; protected $useSoftDeletes = false; @@ -25,6 +21,13 @@ class PermissionModel extends Model protected $validationMessages = []; protected $skipValidation = false; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['permissions_users']; + } + public function getForUser(User $user): array { $rows = $this->builder() diff --git a/src/Models/RememberModel.php b/src/Models/RememberModel.php index ea855cbaa..76b6b11fd 100644 --- a/src/Models/RememberModel.php +++ b/src/Models/RememberModel.php @@ -5,17 +5,13 @@ namespace CodeIgniter\Shield\Models; use CodeIgniter\I18n\Time; -use CodeIgniter\Model; use CodeIgniter\Shield\Entities\User; use DateTime; use Faker\Generator; use stdClass; -class RememberModel extends Model +class RememberModel extends BaseModel { - use CheckQueryReturnTrait; - - protected $table = 'auth_remember_tokens'; protected $primaryKey = 'id'; protected $returnType = 'object'; protected $useSoftDeletes = false; @@ -27,6 +23,13 @@ class RememberModel extends Model ]; protected $useTimestamps = true; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['remember_tokens']; + } + public function fake(Generator &$faker): stdClass { return (object) [ diff --git a/src/Models/TokenLoginModel.php b/src/Models/TokenLoginModel.php index a6234bb38..748bf4ecd 100644 --- a/src/Models/TokenLoginModel.php +++ b/src/Models/TokenLoginModel.php @@ -10,7 +10,12 @@ class TokenLoginModel extends LoginModel { - protected $table = 'auth_token_logins'; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['token_logins']; + } /** * Generate a fake login for testing diff --git a/src/Models/UserIdentityModel.php b/src/Models/UserIdentityModel.php index 1877235a0..ee19be499 100644 --- a/src/Models/UserIdentityModel.php +++ b/src/Models/UserIdentityModel.php @@ -5,7 +5,6 @@ namespace CodeIgniter\Shield\Models; use CodeIgniter\I18n\Time; -use CodeIgniter\Model; use CodeIgniter\Shield\Authentication\Authenticators\AccessTokens; use CodeIgniter\Shield\Authentication\Authenticators\Session; use CodeIgniter\Shield\Authentication\Passwords; @@ -16,11 +15,8 @@ use CodeIgniter\Shield\Exceptions\ValidationException; use Faker\Generator; -class UserIdentityModel extends Model +class UserIdentityModel extends BaseModel { - use CheckQueryReturnTrait; - - protected $table = 'auth_identities'; protected $primaryKey = 'id'; protected $returnType = UserIdentity::class; protected $useSoftDeletes = false; @@ -37,6 +33,13 @@ class UserIdentityModel extends Model ]; protected $useTimestamps = true; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['identities']; + } + /** * Inserts a record * diff --git a/src/Models/UserModel.php b/src/Models/UserModel.php index a1da4cf06..ab5eb49c2 100644 --- a/src/Models/UserModel.php +++ b/src/Models/UserModel.php @@ -6,7 +6,6 @@ use CodeIgniter\Database\Exceptions\DataException; use CodeIgniter\I18n\Time; -use CodeIgniter\Model; use CodeIgniter\Shield\Authentication\Authenticators\Session; use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Entities\UserIdentity; @@ -17,11 +16,8 @@ /** * @phpstan-consistent-constructor */ -class UserModel extends Model +class UserModel extends BaseModel { - use CheckQueryReturnTrait; - - protected $table = 'users'; protected $primaryKey = 'id'; protected $returnType = User::class; protected $useSoftDeletes = true; @@ -49,6 +45,13 @@ class UserModel extends Model */ protected ?User $tempUser = null; + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['users']; + } + /** * Mark the next find* query to include identities * @@ -184,19 +187,19 @@ public function findByCredentials(array $credentials): ?User // any of the credentials used should be case-insensitive foreach ($credentials as $key => $value) { $this->where( - 'LOWER(' . $this->db->protectIdentifiers("users.{$key}") . ')', + 'LOWER(' . $this->db->protectIdentifiers($this->table . ".{$key}") . ')', strtolower($value) ); } if ($email !== null) { $data = $this->select( - 'users.*, auth_identities.secret as email, auth_identities.secret2 as password_hash' + sprintf('%1$s.*, %2$s.secret as email, %2$s.secret2 as password_hash', $this->table, $this->tables['identities']) ) - ->join('auth_identities', 'auth_identities.user_id = users.id') - ->where('auth_identities.type', Session::ID_TYPE_EMAIL_PASSWORD) + ->join($this->tables['identities'], sprintf('%1$s.user_id = %2$s.id', $this->tables['identities'], $this->table)) + ->where($this->tables['identities'] . '.type', Session::ID_TYPE_EMAIL_PASSWORD) ->where( - 'LOWER(' . $this->db->protectIdentifiers('auth_identities.secret') . ')', + 'LOWER(' . $this->db->protectIdentifiers($this->tables['identities'] . '.secret') . ')', strtolower($email) ) ->asArray() diff --git a/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php b/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php index c829295dc..d84e66586 100644 --- a/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php @@ -143,7 +143,7 @@ public function testCheckSuccess(): void $user = fake(UserModel::class); $token = $user->generateAccessToken('foo'); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'type' => 'access_token', 'last_used_at' => null, @@ -173,7 +173,7 @@ public function testAttemptCannotFindUser(): void $this->assertSame(lang('Auth.badToken'), $result->reason()); // A login attempt should have always been recorded - $this->seeInDatabase('auth_token_logins', [ + $this->seeInDatabase($this->tables['token_logins'], [ 'id_type' => AccessTokens::ID_TYPE_ACCESS_TOKEN, 'identifier' => 'abc123', 'success' => 0, @@ -201,7 +201,7 @@ public function testAttemptSuccess(): void $this->assertSame($token->token, $foundUser->currentAccessToken()->token); // A login attempt should have been recorded - $this->seeInDatabase('auth_token_logins', [ + $this->seeInDatabase($this->tables['token_logins'], [ 'id_type' => AccessTokens::ID_TYPE_ACCESS_TOKEN, 'identifier' => $token->raw_token, 'success' => 1, diff --git a/tests/Authentication/Authenticators/SessionAuthenticatorTest.php b/tests/Authentication/Authenticators/SessionAuthenticatorTest.php index 942c9df7e..2a3249f00 100644 --- a/tests/Authentication/Authenticators/SessionAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/SessionAuthenticatorTest.php @@ -14,18 +14,16 @@ use CodeIgniter\Shield\Models\RememberModel; use CodeIgniter\Shield\Models\UserModel; use CodeIgniter\Shield\Result; -use CodeIgniter\Test\DatabaseTestTrait; use CodeIgniter\Test\Mock\MockEvents; use Config\Services; +use Tests\Support\DatabaseTestCase; use Tests\Support\FakeUser; -use Tests\Support\TestCase; /** * @internal */ -final class SessionAuthenticatorTest extends TestCase +final class SessionAuthenticatorTest extends DatabaseTestCase { - use DatabaseTestTrait; use FakeUser; private Session $auth; @@ -47,7 +45,7 @@ protected function setUp(): void $this->events = new MockEvents(); Services::injectMock('events', $this->events); - $this->db->table('auth_identities')->truncate(); + $this->db->table($this->tables['identities'])->truncate(); } public function testLoggedInFalse(): void @@ -148,7 +146,7 @@ public function testLoginNoRemember(): void $this->assertSame($this->user->id, $_SESSION['user']['id']); - $this->dontSeeInDatabase('auth_remember_tokens', [ + $this->dontSeeInDatabase($this->tables['remember_tokens'], [ 'user_id' => $this->user->id, ]); } @@ -161,7 +159,7 @@ public function testLoginWithRemember(): void $this->assertSame($this->user->id, $_SESSION['user']['id']); - $this->seeInDatabase('auth_remember_tokens', [ + $this->seeInDatabase($this->tables['remember_tokens'], [ 'user_id' => $this->user->id, ]); @@ -175,12 +173,12 @@ public function testLogout(): void $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); $this->auth->remember()->login($this->user); - $this->seeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->seeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); $this->auth->logout(); $this->assertArrayNotHasKey('user', $_SESSION); - $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); } public function testLogoutOnlyLogoutCalled(): void @@ -208,7 +206,7 @@ public function testLoginById(): void $this->assertSame($this->user->id, $_SESSION['user']['id']); - $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); } public function testLoginByIdRemember(): void @@ -219,7 +217,7 @@ public function testLoginByIdRemember(): void $this->assertSame($this->user->id, $_SESSION['user']['id']); - $this->seeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->seeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); } public function testForgetCurrentUser(): void @@ -228,22 +226,22 @@ public function testForgetCurrentUser(): void $this->auth->remember()->loginById($this->user->id); $this->assertSame($this->user->id, $_SESSION['user']['id']); - $this->seeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->seeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); $this->auth->forget(); - $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); } public function testForgetAnotherUser(): void { fake(RememberModel::class, ['user_id' => $this->user->id]); - $this->seeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->seeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); $this->auth->forget($this->user); - $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); + $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]); } public function testCheckNoPassword(): void @@ -317,7 +315,7 @@ public function testAttemptCannotFindUser(): void $this->assertSame(lang('Auth.badAttempt'), $result->reason()); // A login attempt should have always been recorded - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => 'johnsmith@example.com', 'success' => 0, ]); @@ -347,7 +345,7 @@ public function testAttemptSuccess(): void $this->assertSame($this->user->id, $_SESSION['user']['id']); // A login attempt should have been recorded - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => $this->user->email, 'success' => 1, ]); @@ -397,7 +395,7 @@ public function testAttemptCaseInsensitive(): void $this->assertSame($this->user->id, $_SESSION['user']['id']); // A login attempt should have been recorded - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => 'foo@example.COM', 'success' => 1, ]); @@ -435,7 +433,7 @@ public function testAttemptUsernameOnly(): void $this->assertSame($user->id, $_SESSION['user']['id']); // A login attempt should have been recorded - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => 'fooROG', 'success' => 1, ]); @@ -473,7 +471,7 @@ public function testAttemptCustomField(): void $this->assertTrue($result->isOK()); - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'id_type' => 'status', 'identifier' => '12345', 'success' => 1, diff --git a/tests/Authentication/HasAccessTokensTest.php b/tests/Authentication/HasAccessTokensTest.php index 4d0025fe4..302e99906 100644 --- a/tests/Authentication/HasAccessTokensTest.php +++ b/tests/Authentication/HasAccessTokensTest.php @@ -22,7 +22,7 @@ protected function setUp(): void parent::setUp(); $this->user = fake(UserModel::class); - $this->db->table('auth_identities')->truncate(); + $this->db->table($this->tables['identities'])->truncate(); } public function testGenerateToken(): void diff --git a/tests/Authentication/MagicLinkTest.php b/tests/Authentication/MagicLinkTest.php index 2be743ac7..63292fae6 100644 --- a/tests/Authentication/MagicLinkTest.php +++ b/tests/Authentication/MagicLinkTest.php @@ -9,17 +9,15 @@ use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Models\UserIdentityModel; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Test\DatabaseTestTrait; use CodeIgniter\Test\FeatureTestTrait; use Config\Services; -use Tests\Support\TestCase; +use Tests\Support\DatabaseTestCase; /** * @internal */ -final class MagicLinkTest extends TestCase +final class MagicLinkTest extends DatabaseTestCase { - use DatabaseTestTrait; use FeatureTestTrait; protected $refresh = true; @@ -81,7 +79,7 @@ public function testMagicLinkSubmitSuccess(): void $result->assertOK(); $result->assertSee(lang('Auth.checkYourEmail')); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'type' => Session::ID_TYPE_MAGIC_LINK, ]); diff --git a/tests/Authorization/AuthorizableTest.php b/tests/Authorization/AuthorizableTest.php index 7f8c2f502..aeeaeb7c7 100644 --- a/tests/Authorization/AuthorizableTest.php +++ b/tests/Authorization/AuthorizableTest.php @@ -8,17 +8,15 @@ use CodeIgniter\Shield\Authorization\AuthorizationException; use CodeIgniter\Shield\Exceptions\LogicException; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Test\DatabaseTestTrait; use Locale; +use Tests\Support\DatabaseTestCase; use Tests\Support\FakeUser; -use Tests\Support\TestCase; /** * @internal */ -final class AuthorizableTest extends TestCase +final class AuthorizableTest extends DatabaseTestCase { - use DatabaseTestTrait; use FakeUser; protected $refresh = true; @@ -29,8 +27,8 @@ protected function setUp(): void parent::setUp(); // Refresh should take care of this.... - db_connect()->table('auth_groups_users')->truncate(); - db_connect()->table('auth_permissions_users')->truncate(); + db_connect()->table($this->tables['groups_users'])->truncate(); + db_connect()->table($this->tables['permissions_users'])->truncate(); } public function testAddGroupWithNoExistingGroups(): void @@ -39,11 +37,11 @@ public function testAddGroupWithNoExistingGroups(): void // Make sure it doesn't record duplicates $this->user->addGroup('admin', 'beta'); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', ]); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'beta', ]); @@ -55,12 +53,12 @@ public function testAddGroupWithNoExistingGroups(): void public function testAddGroupWithExistingGroups(): void { - $this->hasInDatabase('auth_groups_users', [ + $this->hasInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', 'created_at' => Time::now()->toDateTimeString(), ]); - $this->hasInDatabase('auth_groups_users', [ + $this->hasInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'superadmin', 'created_at' => Time::now()->toDateTimeString(), @@ -70,15 +68,15 @@ public function testAddGroupWithExistingGroups(): void // Make sure it doesn't record duplicates $this->user->addGroup('admin', 'beta'); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', ]); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'superadmin', ]); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'beta', ]); @@ -102,14 +100,14 @@ public function testRemoveGroupNoGroups(): void public function testRemoveGroupExistingGroup(): void { - $this->hasInDatabase('auth_groups_users', [ + $this->hasInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', 'created_at' => Time::now()->toDateTimeString(), ]); $otherUser = fake(UserModel::class); - $this->hasInDatabase('auth_groups_users', [ + $this->hasInDatabase($this->tables['groups_users'], [ 'user_id' => $otherUser->id, 'group' => 'admin', 'created_at' => Time::now()->toDateTimeString(), @@ -117,13 +115,13 @@ public function testRemoveGroupExistingGroup(): void $this->user->removeGroup('admin'); $this->assertEmpty($this->user->getGroups()); - $this->dontSeeInDatabase('auth_groups_users', [ + $this->dontSeeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', ]); // Make sure we didn't delete the group from anyone else - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $otherUser->id, 'group' => 'admin', ]); @@ -131,12 +129,12 @@ public function testRemoveGroupExistingGroup(): void public function testSyncGroups(): void { - $this->hasInDatabase('auth_groups_users', [ + $this->hasInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', 'created_at' => Time::now()->toDateTimeString(), ]); - $this->hasInDatabase('auth_groups_users', [ + $this->hasInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'superadmin', 'created_at' => Time::now()->toDateTimeString(), @@ -144,11 +142,11 @@ public function testSyncGroups(): void $this->user->syncGroups('admin', 'beta'); $this->assertSame(['admin', 'beta'], $this->user->getGroups()); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', ]); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'beta', ]); @@ -160,11 +158,11 @@ public function testAddPermissionWithNoExistingPermissions(): void // Make sure it doesn't record duplicates $this->user->addPermission('admin.access', 'beta.access'); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', ]); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'beta.access', ]); @@ -176,12 +174,12 @@ public function testAddPermissionWithNoExistingPermissions(): void public function testAddPermissionWithExistingPermissions(): void { - $this->hasInDatabase('auth_permissions_users', [ + $this->hasInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', 'created_at' => Time::now()->toDateTimeString(), ]); - $this->hasInDatabase('auth_permissions_users', [ + $this->hasInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'users.manage', 'created_at' => Time::now()->toDateTimeString(), @@ -191,15 +189,15 @@ public function testAddPermissionWithExistingPermissions(): void // Make sure it doesn't record duplicates $this->user->addPermission('admin.access', 'beta.access'); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', ]); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'users.manage', ]); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'beta.access', ]); @@ -223,14 +221,14 @@ public function testRemovePermissionNoPermissions(): void public function testRemovePermissionExistingPermissions(): void { - $this->hasInDatabase('auth_permissions_users', [ + $this->hasInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', 'created_at' => Time::now()->toDateTimeString(), ]); $otherUser = fake(UserModel::class); - $this->hasInDatabase('auth_permissions_users', [ + $this->hasInDatabase($this->tables['permissions_users'], [ 'user_id' => $otherUser->id, 'permission' => 'admin.access', 'created_at' => Time::now()->toDateTimeString(), @@ -238,13 +236,13 @@ public function testRemovePermissionExistingPermissions(): void $this->user->removePermission('admin.access'); $this->assertEmpty($this->user->getPermissions()); - $this->dontSeeInDatabase('auth_permissions_users', [ + $this->dontSeeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', ]); // Make sure it didn't delete the other user's permission - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $otherUser->id, 'permission' => 'admin.access', ]); @@ -252,12 +250,12 @@ public function testRemovePermissionExistingPermissions(): void public function testSyncPermissions(): void { - $this->hasInDatabase('auth_permissions_users', [ + $this->hasInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', 'created_at' => Time::now()->toDateTimeString(), ]); - $this->hasInDatabase('auth_permissions_users', [ + $this->hasInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'superadmin.access', 'created_at' => Time::now()->toDateTimeString(), @@ -265,11 +263,11 @@ public function testSyncPermissions(): void $this->user->syncPermissions('admin.access', 'beta.access'); $this->assertSame(['admin.access', 'beta.access'], $this->user->getPermissions()); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'admin.access', ]); - $this->seeInDatabase('auth_permissions_users', [ + $this->seeInDatabase($this->tables['permissions_users'], [ 'user_id' => $this->user->id, 'permission' => 'beta.access', ]); @@ -319,7 +317,7 @@ public function testCreatedAtIfDefaultLocaleSetFaWithAddGroup(): void $this->user->addGroup('admin'); - $this->seeInDatabase('auth_groups_users', [ + $this->seeInDatabase($this->tables['groups_users'], [ 'user_id' => $this->user->id, 'group' => 'admin', 'created_at' => '2017-03-10 00:00:00', diff --git a/tests/Controllers/ActionsTest.php b/tests/Controllers/ActionsTest.php index 77b22dc99..c8530ffe4 100644 --- a/tests/Controllers/ActionsTest.php +++ b/tests/Controllers/ActionsTest.php @@ -14,13 +14,13 @@ use CodeIgniter\Test\DatabaseTestTrait; use CodeIgniter\Test\FeatureTestTrait; use Config\Services; +use Tests\Support\DatabaseTestCase; use Tests\Support\FakeUser; -use Tests\Support\TestCase; /** * @internal */ -final class ActionsTest extends TestCase +final class ActionsTest extends DatabaseTestCase { use DatabaseTestTrait; use FeatureTestTrait; @@ -155,7 +155,7 @@ public function testEmail2FAVerify(): void $this->assertSame(site_url(), $result->getRedirectUrl()); // Identity should have been removed - $this->dontSeeInDatabase('auth_identities', [ + $this->dontSeeInDatabase($this->tables['identities'], [ 'user_id' => $this->user->id, 'type' => Session::ID_TYPE_EMAIL_2FA, ]); @@ -174,7 +174,7 @@ public function testShowEmail2FACreatesIdentity(): void $result->assertOK(); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $this->user->id, 'type' => Session::ID_TYPE_EMAIL_2FA, 'name' => 'login', @@ -259,7 +259,7 @@ public function testEmailActivateVerify(): void $this->assertSame(site_url(), $result->getRedirectUrl()); // Identity should have been removed - $this->dontSeeInDatabase('auth_identities', [ + $this->dontSeeInDatabase($this->tables['identities'], [ 'user_id' => $this->user->id, 'type' => Session::ID_TYPE_EMAIL_2FA, ]); @@ -268,7 +268,7 @@ public function testEmailActivateVerify(): void $result->assertSessionMissing('auth_action'); // User should have been set as active - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $this->user->id, 'active' => 1, ]); diff --git a/tests/Controllers/LoginTest.php b/tests/Controllers/LoginTest.php index 2ffe35341..c27190e01 100644 --- a/tests/Controllers/LoginTest.php +++ b/tests/Controllers/LoginTest.php @@ -8,19 +8,17 @@ use CodeIgniter\Config\Factories; use CodeIgniter\I18n\Time; use CodeIgniter\Shield\Authentication\Actions\Email2FA; -use CodeIgniter\Test\DatabaseTestTrait; use CodeIgniter\Test\FeatureTestTrait; use Config\Services; use Config\Validation; +use Tests\Support\DatabaseTestCase; use Tests\Support\FakeUser; -use Tests\Support\TestCase; /** * @internal */ -final class LoginTest extends TestCase +final class LoginTest extends DatabaseTestCase { - use DatabaseTestTrait; use FeatureTestTrait; use FakeUser; @@ -53,7 +51,7 @@ public function testLoginBadEmail(): void $this->assertSame(site_url('/login'), $result->getRedirectUrl()); // Login should have been recorded successfully - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => 'fooled@example.com', 'user_id' => null, 'success' => 0, @@ -87,7 +85,7 @@ public function testLoginActionEmailSuccess(): void $this->assertSame(site_url(), $result->getRedirectUrl()); // Login should have been recorded successfully - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => 'foo@example.com', 'user_id' => $this->user->id, 'success' => 1, @@ -159,7 +157,7 @@ public function testLoginActionUsernameSuccess(): void $this->assertSame(site_url(), $result->getRedirectUrl()); // Login should have been recorded successfully - $this->seeInDatabase('auth_logins', [ + $this->seeInDatabase($this->tables['logins'], [ 'identifier' => $this->user->username, 'user_id' => $this->user->id, 'success' => 1, diff --git a/tests/Controllers/RegisterTest.php b/tests/Controllers/RegisterTest.php index 3ef6cce9b..3a44098f4 100644 --- a/tests/Controllers/RegisterTest.php +++ b/tests/Controllers/RegisterTest.php @@ -60,7 +60,7 @@ public function testRegisterActionSuccess(): void $this->assertSame(site_url(), $result->getRedirectUrl()); // User saved to DB - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'username' => 'JohnDoe', ]); @@ -68,7 +68,7 @@ public function testRegisterActionSuccess(): void /** @var User $user */ $user = model(UserModel::class)->where('username', 'JohnDoe')->first(); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'type' => Session::ID_TYPE_EMAIL_PASSWORD, 'secret' => 'john.doe@example.com', @@ -141,7 +141,7 @@ public function testRegisterRedirectsToActionIfDefined(): void $result->assertRedirectTo('/auth/a/show'); // Should NOT have activated the user - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'username' => 'foo', 'active' => 0, ]); diff --git a/tests/Unit/UserModelTest.php b/tests/Unit/UserModelTest.php index 65eee5b27..6cb92a0d9 100644 --- a/tests/Unit/UserModelTest.php +++ b/tests/Unit/UserModelTest.php @@ -8,16 +8,13 @@ use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Exceptions\LogicException; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Test\DatabaseTestTrait; -use Tests\Support\TestCase; +use Tests\Support\DatabaseTestCase; /** * @internal */ -final class UserModelTest extends TestCase +final class UserModelTest extends DatabaseTestCase { - use DatabaseTestTrait; - protected $namespace; protected $refresh = true; @@ -35,11 +32,11 @@ public function testSaveInsertUser(): void $users->save($user); $user = $users->findByCredentials(['email' => 'foo@bar.com']); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'foo@bar.com', ]); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $user->id, 'active' => 0, ]); @@ -70,11 +67,11 @@ public function testInsertUserObject(): void $users->insert($user); $user = $users->findByCredentials(['email' => 'foo@bar.com']); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'foo@bar.com', ]); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $user->id, 'active' => 0, ]); @@ -116,11 +113,11 @@ public function testInsertUserArray(): void $id = $users->insert($userArray); - $this->dontSeeInDatabase('auth_identities', [ + $this->dontSeeInDatabase($this->tables['identities'], [ 'user_id' => $id, 'secret' => 'foo@bar.com', ]); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $id, 'active' => 0, ]); @@ -151,11 +148,11 @@ public function testSaveUpdateUserObjectWithUserDataToUpdate(): void $users->save($user); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'bar@bar.com', ]); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $user->id, 'active' => 1, ]); @@ -175,11 +172,11 @@ public function testUpdateUserObjectWithUserDataToUpdate(): void $users->update($user->id, $user); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'bar@bar.com', ]); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $user->id, 'active' => 1, ]); @@ -211,11 +208,11 @@ public function testUpdateUserArrayWithUserDataToUpdate(): void $users->update($user->id, $userArray); - $this->dontSeeInDatabase('auth_identities', [ + $this->dontSeeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'bar@bar.com', ]); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $user->id, 'active' => 1, ]); @@ -233,7 +230,7 @@ public function testSaveUpdateUserObjectWithoutUserDataToUpdate(): void $users->save($user); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'bar@bar.com', ]); @@ -251,7 +248,7 @@ public function testUpdateUserObjectWithoutUserDataToUpdate(): void $users->update(null, $user); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'bar@bar.com', ]); diff --git a/tests/Unit/UserTest.php b/tests/Unit/UserTest.php index 311105db7..b10860ebc 100644 --- a/tests/Unit/UserTest.php +++ b/tests/Unit/UserTest.php @@ -12,16 +12,14 @@ use CodeIgniter\Shield\Models\LoginModel; use CodeIgniter\Shield\Models\UserIdentityModel; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Test\DatabaseTestTrait; +use Tests\Support\DatabaseTestCase; use Tests\Support\FakeUser; -use Tests\Support\TestCase; /** * @internal */ -final class UserTest extends TestCase +final class UserTest extends DatabaseTestCase { - use DatabaseTestTrait; use FakeUser; protected $namespace; @@ -184,7 +182,7 @@ public function testUpdateEmail(): void $user = $users->find($this->user->id); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'foo@bar.com', ]); @@ -225,7 +223,7 @@ public function testUpdatePasswordHash(): void $user = $users->find($this->user->id); - $this->seeInDatabase('auth_identities', [ + $this->seeInDatabase($this->tables['identities'], [ 'user_id' => $user->id, 'secret' => 'foo@bar.com', 'secret2' => $hash, @@ -263,7 +261,7 @@ public function testActivate(): void $this->user->active = false; model(UserModel::class)->save($this->user); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $this->user->id, 'active' => 0, ]); @@ -274,7 +272,7 @@ public function testActivate(): void $this->user = model(UserModel::class)->find($this->user->id); $this->assertTrue($this->user->active); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $this->user->id, 'active' => 1, ]); @@ -285,7 +283,7 @@ public function testDeactivate(): void $this->user->active = true; model(UserModel::class)->save($this->user); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $this->user->id, 'active' => 1, ]); @@ -296,7 +294,7 @@ public function testDeactivate(): void $this->user = model(UserModel::class)->find($this->user->id); $this->assertFalse($this->user->active); - $this->seeInDatabase('users', [ + $this->seeInDatabase($this->tables['users'], [ 'id' => $this->user->id, 'active' => 0, ]); diff --git a/tests/_support/DatabaseTestCase.php b/tests/_support/DatabaseTestCase.php index 2d06f99bb..8e72928af 100644 --- a/tests/_support/DatabaseTestCase.php +++ b/tests/_support/DatabaseTestCase.php @@ -4,6 +4,7 @@ namespace Tests\Support; +use CodeIgniter\Shield\Config\Auth; use CodeIgniter\Test\DatabaseTestTrait; /** @@ -15,9 +16,18 @@ abstract class DatabaseTestCase extends TestCase protected $namespace = '\CodeIgniter\Shield'; + /** + * Auth Table names + */ + protected array $tables; + protected function setUp(): void { parent::setUp(); + + /** @var Auth $authConfig */ + $authConfig = config('Auth'); + $this->tables = $authConfig->tables; } protected function tearDown(): void