|
| 1 | +<?php |
| 2 | + |
| 3 | +use Illuminate\Support\Facades\DB; |
| 4 | +use Illuminate\Support\Facades\Crypt; |
| 5 | +use Illuminate\Support\Facades\Schema; |
| 6 | +use Illuminate\Database\Schema\Blueprint; |
| 7 | +use Illuminate\Database\Migrations\Migration; |
| 8 | +use Illuminate\Contracts\Encryption\DecryptException; |
| 9 | + |
| 10 | +class MigratePubPrivFormatToSingleKey extends Migration |
| 11 | +{ |
| 12 | + /** |
| 13 | + * Run the migrations. |
| 14 | + */ |
| 15 | + public function up() |
| 16 | + { |
| 17 | + DB::transaction(function () { |
| 18 | + DB::table('api_keys')->get()->each(function ($item) { |
| 19 | + try { |
| 20 | + $decrypted = Crypt::decrypt($item->secret); |
| 21 | + } catch (DecryptException $exception) { |
| 22 | + $decrypted = str_random(32); |
| 23 | + } finally { |
| 24 | + DB::table('api_keys')->where('id', $item->id)->update([ |
| 25 | + 'secret' => $decrypted, |
| 26 | + ]); |
| 27 | + } |
| 28 | + }); |
| 29 | + }); |
| 30 | + |
| 31 | + Schema::table('api_keys', function (Blueprint $table) { |
| 32 | + $table->dropColumn('public'); |
| 33 | + $table->string('secret', 32)->change(); |
| 34 | + }); |
| 35 | + |
| 36 | + DB::statement('ALTER TABLE `api_keys` CHANGE `secret` `token` CHAR(32) NOT NULL, ADD UNIQUE INDEX `api_keys_token_unique` (`token`(32))'); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Reverse the migrations. |
| 41 | + */ |
| 42 | + public function down() |
| 43 | + { |
| 44 | + DB::statement('ALTER TABLE `api_keys` CHANGE `token` `secret` TEXT, DROP INDEX `api_keys_token_unique`'); |
| 45 | + |
| 46 | + Schema::table('api_keys', function (Blueprint $table) { |
| 47 | + $table->char('public', 16)->after('user_id'); |
| 48 | + }); |
| 49 | + |
| 50 | + DB::transaction(function () { |
| 51 | + DB::table('api_keys')->get()->each(function ($item) { |
| 52 | + DB::table('api_keys')->where('id', $item->id)->update([ |
| 53 | + 'public' => str_random(16), |
| 54 | + 'secret' => Crypt::encrypt($item->secret), |
| 55 | + ]); |
| 56 | + }); |
| 57 | + }); |
| 58 | + } |
| 59 | +} |
0 commit comments