|
| 1 | +import { existsSync } from 'node:fs'; |
| 2 | +import { copyFile, readFile, rename, unlink, writeFile } from 'node:fs/promises'; |
| 3 | + |
| 4 | +export const setupSso = async () => { |
| 5 | + const path = '/usr/local/emhttp/plugins/dynamix/include/.login.php'; |
| 6 | + |
| 7 | + // Define the new PHP function to insert |
| 8 | + const newFunction = ` |
| 9 | +function verifyUsernamePasswordAndSSO(string $username, string $password): bool { |
| 10 | + if ($username != "root") return false; |
| 11 | +
|
| 12 | + $output = exec("/usr/bin/getent shadow $username"); |
| 13 | + if ($output === false) return false; |
| 14 | + $credentials = explode(":", $output); |
| 15 | + $valid = password_verify($password, $credentials[1]); |
| 16 | + if ($valid) { |
| 17 | + return true; |
| 18 | + } |
| 19 | + // We may have an SSO token, attempt validation |
| 20 | + if (strlen($password) > 800) { |
| 21 | + $safePassword = escapeshellarg($password); |
| 22 | + $response = exec("/usr/local/bin/unraid-api sso validate-token $safePassword", $output, $code); |
| 23 | + my_logger("SSO Login Response: $response"); |
| 24 | + if ($code === 0 && $response && strpos($response, '"valid":true') !== false) { |
| 25 | + return true; |
| 26 | + } |
| 27 | + } |
| 28 | + return false; |
| 29 | +}`; |
| 30 | + |
| 31 | + const tagToInject = '<?php include "$docroot/plugins/dynamix.my.servers/include/sso-login.php"; ?>'; |
| 32 | + |
| 33 | + // Backup the original file if exists |
| 34 | + if (existsSync(path + '.bak')) { |
| 35 | + await copyFile(path + '.bak', path); |
| 36 | + await unlink(path + '.bak'); |
| 37 | + } |
| 38 | + |
| 39 | + // Read the file content |
| 40 | + let fileContent = await readFile(path, 'utf-8'); |
| 41 | + |
| 42 | + // Backup the original content |
| 43 | + await writeFile(path + '.bak', fileContent); |
| 44 | + |
| 45 | + // Add new function after the opening PHP tag (<?php) |
| 46 | + fileContent = fileContent.replace(/<\?php\s*(\r?\n|\r)*/, `<?php\n\n${newFunction}\n`); |
| 47 | + |
| 48 | + // Replace the old function call with the new function name |
| 49 | + const functionCallPattern = /!verifyUsernamePassword\(\$username, \$password\)/g; |
| 50 | + fileContent = fileContent.replace( |
| 51 | + functionCallPattern, |
| 52 | + '!verifyUsernamePasswordAndSSO($username, $password)' |
| 53 | + ); |
| 54 | + |
| 55 | + // Inject the PHP include tag before the closing </body> tag |
| 56 | + fileContent = fileContent.replace(/<\/body>/i, `${tagToInject}\n</body>`); |
| 57 | + |
| 58 | + // Write the updated content back to the file |
| 59 | + await writeFile(path, fileContent); |
| 60 | + |
| 61 | + console.log('Function replaced successfully.'); |
| 62 | +}; |
0 commit comments