homepage.js/scripts/generate_key.js

52 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-02-18 15:34:39 +01:00
const crypto = require('crypto');
const path = require('path');
const args = require('args-parser')(process.argv);
const fs = require('fs');
2023-02-18 16:03:27 +01:00
const base64 = require('js-base64');
2023-02-18 15:34:39 +01:00
2023-02-18 16:29:32 +01:00
let key = crypto.randomFillSync(Buffer.alloc(32)).toString('base64');
2023-02-18 15:34:39 +01:00
let dotenv = path.resolve('.env');
if (args['help']) {
2023-02-18 16:03:27 +01:00
console.log(path.basename(__filename) + ' [--key-only] [--env|-e] [--set-key] [--dry-run] [--stdout|-s]');
2023-02-18 15:34:39 +01:00
console.log('\n' +
' --help: Display this help\n' +
' --key-only: Generate key only and put it in stdout\n' +
' --env -e: Specify an env file\n' +
' --set-key: Specify your key\n' +
2023-02-18 16:03:27 +01:00
' --dry-run: Don\'t write anything, just do the thing\n' +
' --stdout -s: Don\'t write to file, write to stdout instead'
2023-02-18 15:34:39 +01:00
)
}
if (args['key-only']) {
console.log(key);
process.exit(0);
}
if (args['env'] || args['e']) {
dotenv = args['env'] ? args['env'] : args['e'];
}
if (args['set-key']) {
key = args['set-key'];
}
const file = fs.readFileSync(dotenv).toString('utf8');
let lines = file.split('\n');
for (let i = 0; i != lines.length; i++) {
let line = lines[i];
if (line.startsWith('APP_KEY=')) {
lines[i] = 'APP_KEY=' + key;
}
}
const newfile = lines.join('\n');
2023-02-18 16:03:27 +01:00
const w_stdout = args['stdout'] || args['s'];
2023-02-18 15:34:39 +01:00
if (!args['dry-run']) {
2023-02-18 16:03:27 +01:00
if (w_stdout) console.log(newfile);
else
fs.writeFileSync(dotenv, newfile);
2023-02-18 15:34:39 +01:00
}