|
| 1 | +<?php |
| 2 | + |
| 3 | +use Illuminate\Database\Migrations\Migration; |
| 4 | +use Illuminate\Database\Capsule\Manager as Capsule; |
| 5 | + |
| 6 | +import('plugins.generic.thoth.classes.encryption.DataEncryption'); |
| 7 | + |
| 8 | +class PasswordEncryptionMigration extends Migration |
| 9 | +{ |
| 10 | + public function up(): void |
| 11 | + { |
| 12 | + $encrypter = new DataEncryption(); |
| 13 | + if (!$encrypter->secretConfigExists()) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + Capsule::table('plugin_settings') |
| 18 | + ->where('plugin_name', 'thothplugin') |
| 19 | + ->where('setting_name', 'password') |
| 20 | + ->get(['context_id', 'setting_value']) |
| 21 | + ->each(function ($row) use ($encrypter) { |
| 22 | + if (empty($row->setting_value) || $encrypter->textIsEncrypted($row->setting_value)) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + if ($this->isJWT($row->setting_value)) { |
| 27 | + $decodedPayload = $this->decodeJWT($row->setting_value); |
| 28 | + if ($decodedPayload !== null) { |
| 29 | + $row->setting_value = json_decode($decodedPayload); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + $encryptedValue = $encrypter->encryptString($row->setting_value); |
| 34 | + Capsule::table('plugin_settings') |
| 35 | + ->where('plugin_name', 'thothplugin') |
| 36 | + ->where('context_id', $row->context_id) |
| 37 | + ->where('setting_name', 'password') |
| 38 | + ->update(['setting_value' => $encryptedValue]); |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + public function base64URLDecode($data) |
| 43 | + { |
| 44 | + $remainder = strlen($data) % 4; |
| 45 | + if ($remainder) { |
| 46 | + $padlen = 4 - $remainder; |
| 47 | + $data .= str_repeat('=', $padlen); |
| 48 | + } |
| 49 | + $data = strtr($data, '-_', '+/'); |
| 50 | + return base64_decode($data); |
| 51 | + } |
| 52 | + |
| 53 | + public function isJWT(string $token): bool |
| 54 | + { |
| 55 | + $parts = explode('.', $token); |
| 56 | + if (count($parts) !== 3) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + foreach ($parts as $part) { |
| 61 | + if (!preg_match('/^[A-Za-z0-9\-_]+$/', $part)) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + [$header, $payload, $signature] = $parts; |
| 67 | + if ($this->base64URLDecode($header) === false || $this->base64URLDecode($payload) === false) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + return true; |
| 72 | + } |
| 73 | + |
| 74 | + public function decodeJWT($string): ?string |
| 75 | + { |
| 76 | + list($header, $payload, $signature) = explode('.', $string); |
| 77 | + $decodedPayload = $this->base64URLDecode($payload); |
| 78 | + return $decodedPayload ? $decodedPayload : null; |
| 79 | + } |
| 80 | +} |
0 commit comments