rewrite generate key script in python

This commit is contained in:
b1ek 2023-03-17 20:54:21 +10:00
parent e4f08d0778
commit a335d5c14f
Signed by: blek
GPG Key ID: 14546221E3595D0C
3 changed files with 27 additions and 54 deletions

View File

@ -30,5 +30,4 @@ cd to `react/resume` and run `build.sh`.
If you are running in debug mode, run `yarn/npm start`
## Generate the key
Install node modules in following directories: `.`, `./scripts`
Then, cd to root and run `node scripts/generate_key.js`
Cd to root of project and run `scripts/generate_key.py`

View File

@ -1,53 +1,3 @@
const crypto = require('crypto');
const path = require('path');
const args = require('args-parser')(process.argv);
const fs = require('fs');
const base64 = require('js-base64');
const { exec } = require('child_process');
let key = crypto.randomFillSync(Buffer.alloc(32)).toString('base64');
let dotenv = path.resolve('.env');
if (args['help']) {
console.log(path.basename(__filename) + ' [--key-only] [--env|-e] [--set-key] [--dry-run] [--stdout|-s]');
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' +
' --dry-run: Don\'t write anything, just do the thing\n' +
' --stdout -s: Don\'t write to file, write to stdout instead'
);
process.exit(0);
}
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');
const w_stdout = args['stdout'] || args['s'];
if (!args['dry-run']) {
if (w_stdout) console.log(newfile);
else
fs.writeFileSync(dotenv, newfile);
}
exec('generate_key.py');

24
scripts/generate_key.py Executable file
View File

@ -0,0 +1,24 @@
#!/usr/bin/env python3
import os
import secrets
import base64
if (not os.path.exists('.env')):
print('No .env file found. Please create a dotenv to proceed.');
exit(-1);
key_bytes = secrets.token_bytes(32);
dotenv_text = '';
with open('.env', 'tr', encoding='utf-8') as f:
dotenv_text = f.read();
dotenv_lines = dotenv_text.split('\n');
key_line = 0;
for i, line in enumerate(dotenv_lines):
if (line.startswith('APP_KEY=')):
dotenv_lines[i] = 'APP_KEY=' + base64.b64encode(key_bytes).decode('utf-8');
with open('.env', 'tw', encoding='utf-8') as f: print('\n'.join(dotenv_lines), file=f)