Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
530a33c
feat: add `$authTables` for customize shield table names
datamweb Feb 6, 2023
75136b5
add: include `Constants.php` file for load
datamweb Feb 6, 2023
aaaf255
add: `Constants.php` file for easy access in all files.
datamweb Feb 6, 2023
f6129f3
replace `users` with `SHIELD_TABLES['users']`
datamweb Feb 6, 2023
df26dde
replaced `auth_identities` with `SHIELD_TABLES['auth_identities']`
datamweb Feb 6, 2023
44136b2
replaced `auth_logins` with `SHIELD_TABLES['auth_logins']`
datamweb Feb 6, 2023
94f06ed
replaced `auth_token_logins` with `SHIELD_TABLES['auth_token_logins']`
datamweb Feb 6, 2023
60476e5
replaced `auth_remember_tokens` with `SHIELD_TABLES['auth_remember_to…
datamweb Feb 6, 2023
e261da3
replaced `auth_groups_users` with `SHIELD_TABLES['auth_groups_users']`
datamweb Feb 6, 2023
6d836c7
replaced `auth_permissions_users` with `SHIELD_TABLES['auth_permissio…
datamweb Feb 6, 2023
7fef82e
fix: rector error
datamweb Feb 6, 2023
433f196
style: run cs-fix
datamweb Feb 6, 2023
6ed08e7
rename `$authTables` to `$tables` and delete `auth_` from array keys
datamweb Feb 7, 2023
eafae2c
delete `auth_` from `$tables` keys
datamweb Feb 7, 2023
4faff62
fix: use `new()` for pass phpstan error
datamweb Feb 9, 2023
c65c6b5
refactor: remove SHIELD_TABLES
kenjis Feb 10, 2023
1adcb5c
refactor: extract BaseModel
kenjis Feb 11, 2023
b63c27f
refactor: remove $this->tableIdentities
kenjis Feb 11, 2023
2d93da1
test: replace hard coded table names
kenjis Feb 11, 2023
1bdd37c
refactor: use CheckQueryReturnTrait in BaseModel
kenjis Feb 11, 2023
343cfc1
docs: update Registration Validation Rules
kenjis Feb 13, 2023
0aa37da
chore: remove deleted file setting
kenjis Feb 13, 2023
6a4d781
docs: add Custom Table Names
kenjis Feb 13, 2023
1e67351
docs: add note for tablename customization
kenjis Feb 13, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 77 additions & 25 deletions docs/customization.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
10 changes: 9 additions & 1 deletion docs/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
```
Expand Down Expand Up @@ -278,4 +286,4 @@ public $globals = [
]
]
```
The same should apply for the Rate Limiting and Forcing Password Reset.
The same should apply for the Rate Limiting and Forcing Password Reset.
30 changes: 30 additions & 0 deletions src/Config/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>
*/
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
Expand Down
29 changes: 27 additions & 2 deletions src/Controllers/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
*
Expand Down Expand Up @@ -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') ?? [
Expand Down
52 changes: 34 additions & 18 deletions src/Database/Migrations/2020-12-28-223112_create_auth_tables.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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([
Expand All @@ -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([
Expand All @@ -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']);
}

// --------------------------------------------------------------------
Expand All @@ -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();
}
Expand Down
Loading