66
77use CodeIgniter \Shield \Authentication \HMAC \HmacEncrypter ;
88use CodeIgniter \Shield \Commands \Exceptions \BadInputException ;
9+ use CodeIgniter \Shield \Exceptions \RuntimeException ;
910use CodeIgniter \Shield \Models \UserIdentityModel ;
1011use Exception ;
1112use ReflectionException ;
@@ -99,15 +100,29 @@ public function run(array $params): int
99100 */
100101 public function encrypt (): void
101102 {
102- $ uIdModel = new UserIdentityModel ();
103- $ encrypter = $ this ->encrypter ;
103+ $ uIdModel = new UserIdentityModel ();
104+ $ uIdModelSub = new UserIdentityModel (); // For saving.
105+ $ encrypter = $ this ->encrypter ;
104106
105- $ uIdModel ->where ('type ' , 'hmac_sha256 ' )->chunk (
107+ $ that = $ this ;
108+
109+ $ uIdModel ->where ('type ' , 'hmac_sha256 ' )->orderBy ('id ' )->chunk (
106110 100 ,
107- static function ($ identity ) use ($ uIdModel , $ encrypter ): void {
108- $ identity ->secret2 = $ encrypter ->encrypt ($ identity ->secret2 );
111+ static function ($ identity ) use ($ uIdModelSub , $ encrypter , $ that ): void {
112+ if ($ encrypter ->isEncrypted ($ identity ->secret2 )) {
113+ $ that ->write ('id: ' . $ identity ->id . ', already encrypted, skipped. ' );
114+
115+ return ;
116+ }
117+
118+ try {
119+ $ identity ->secret2 = $ encrypter ->encrypt ($ identity ->secret2 );
120+ $ uIdModelSub ->save ($ identity );
109121
110- $ uIdModel ->save ($ identity );
122+ $ that ->write ('id: ' . $ identity ->id . ', encrypted. ' );
123+ } catch (RuntimeException $ e ) {
124+ $ that ->error ('id: ' . $ identity ->id . ', ' . $ e ->getMessage ());
125+ }
111126 }
112127 );
113128 }
@@ -119,15 +134,25 @@ static function ($identity) use ($uIdModel, $encrypter): void {
119134 */
120135 public function decrypt (): void
121136 {
122- $ uIdModel = new UserIdentityModel ();
123- $ encrypter = $ this ->encrypter ;
137+ $ uIdModel = new UserIdentityModel ();
138+ $ uIdModelSub = new UserIdentityModel (); // For saving.
139+ $ encrypter = $ this ->encrypter ;
140+
141+ $ that = $ this ;
124142
125143 $ uIdModel ->where ('type ' , 'hmac_sha256 ' )->chunk (
126144 100 ,
127- static function ($ identity ) use ($ uIdModel , $ encrypter ): void {
145+ static function ($ identity ) use ($ uIdModelSub , $ encrypter , $ that ): void {
146+ if (! $ encrypter ->isEncrypted ($ identity ->secret2 )) {
147+ $ that ->write ('id: ' . $ identity ->id . ', not encrypted, skipped. ' );
148+
149+ return ;
150+ }
151+
128152 $ identity ->secret2 = $ encrypter ->decrypt ($ identity ->secret2 );
153+ $ uIdModelSub ->save ($ identity );
129154
130- $ uIdModel -> save ( $ identity );
155+ $ that -> write ( ' id: ' . $ identity-> id . ' , decrypted. ' );
131156 }
132157 );
133158 }
0 commit comments