|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace CodeIgniter\Shield\Database\Migrations; |
| 6 | + |
| 7 | +use CodeIgniter\Database\Forge; |
| 8 | +use CodeIgniter\Database\Migration; |
| 9 | +use CodeIgniter\Encryption\EncrypterInterface; |
| 10 | +use CodeIgniter\Shield\Config\Auth; |
| 11 | +use CodeIgniter\Shield\Config\AuthToken; |
| 12 | +use CodeIgniter\Shield\Models\UserIdentityModel; |
| 13 | +use Config\Encryption; |
| 14 | +use Config\Services; |
| 15 | + |
| 16 | +class EncryptHmacKeys extends Migration |
| 17 | +{ |
| 18 | + /** |
| 19 | + * Encryptor Interface object |
| 20 | + */ |
| 21 | + private EncrypterInterface $encryptor; |
| 22 | + |
| 23 | + public function __construct(?Forge $forge = null) |
| 24 | + { |
| 25 | + /** @var Auth $authConfig */ |
| 26 | + $authConfig = config('Auth'); |
| 27 | + |
| 28 | + if ($authConfig->DBGroup !== null) { |
| 29 | + $this->DBGroup = $authConfig->DBGroup; |
| 30 | + } |
| 31 | + |
| 32 | + parent::__construct($forge); |
| 33 | + |
| 34 | + /** @var AuthToken $authTokenConfig */ |
| 35 | + $authTokenConfig = config('AuthToken'); |
| 36 | + $config = new Encryption(); |
| 37 | + |
| 38 | + $config->key = $authTokenConfig->hmacEncryptionKey; |
| 39 | + $config->driver = $authTokenConfig->hmacEncryptionDriver; |
| 40 | + $config->digest = $authTokenConfig->hmacEncryptionDigest; |
| 41 | + |
| 42 | + // decrypt secret key so signature can be validated |
| 43 | + $this->encryptor = Services::encrypter($config); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * {@inheritDoc} |
| 48 | + */ |
| 49 | + public function up(): void |
| 50 | + { |
| 51 | + $uIdModel = new UserIdentityModel(); |
| 52 | + |
| 53 | + $updateList = []; |
| 54 | + $hmacIdentities = $uIdModel->where('type', 'hmac_sha256')->findAll(); |
| 55 | + |
| 56 | + foreach ($hmacIdentities as $identity) { |
| 57 | + $identity->secret2 = bin2hex($this->encryptor->encrypt($identity->secret2)); |
| 58 | + |
| 59 | + $updateList[] = [ |
| 60 | + 'id' => $identity->id, |
| 61 | + 'secret2' => $identity->secret2, |
| 62 | + ]; |
| 63 | + } |
| 64 | + |
| 65 | + if ($updateList !== []) { |
| 66 | + $uIdModel->updateBatch($updateList, 'id'); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * {@inheritDoc} |
| 72 | + */ |
| 73 | + public function down(): void |
| 74 | + { |
| 75 | + $uIdModel = new UserIdentityModel(); |
| 76 | + |
| 77 | + $updateList = []; |
| 78 | + $hmacIdentities = $uIdModel->where('type', 'hmac_sha256')->findAll(); |
| 79 | + |
| 80 | + foreach ($hmacIdentities as $identity) { |
| 81 | + $identity->secret2 = $this->encryptor->decrypt(hex2bin($identity->secret2)); |
| 82 | + |
| 83 | + $updateList[] = [ |
| 84 | + 'id' => $identity->id, |
| 85 | + 'secret2' => $identity->secret2, |
| 86 | + ]; |
| 87 | + } |
| 88 | + |
| 89 | + if ($updateList !== []) { |
| 90 | + $uIdModel->updateBatch($updateList, 'id'); |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments