initial commit
[squeep-indie-auther] / bin / authUserAdd.js
1 'use strict';
2
3 const argon2 = require('argon2');
4 const readline = require('readline');
5 const stream = require('stream');
6 const DB = require('../src/db');
7 const Logger = require('../src/logger');
8 const Config = require('../config');
9 const config = new Config(process.env.NODE_ENV);
10
11 const logger = new Logger(config);
12 const db = new DB(logger, config);
13
14 const flags = {
15 isPAM: false,
16 };
17 if (process.argv.includes('-P')) {
18 flags.isPAM = true;
19 process.argv.splice(process.argv.indexOf('-P'), 1);
20 }
21
22 const identifier = process.argv[2];
23
24 if (!identifier) {
25 console.log('missing user to add');
26 throw new Error('missing argument');
27 }
28
29 async function readPassword(prompt) {
30 const input = process.stdin;
31 const output = new stream.Writable({
32 write: function (chunk, encoding, callback) {
33 if (!this.muted) {
34 process.stdout.write(chunk, encoding);
35 }
36 callback();
37 },
38 });
39 const rl = readline.createInterface({ input, output, terminal: !!process.stdin.isTTY });
40 rl.setPrompt(prompt);
41 rl.prompt();
42 output.muted = true;
43
44 return new Promise((resolve) => {
45 rl.question('', (answer) => {
46 output.muted = false;
47 rl.close();
48 output.write('\n');
49 resolve(answer);
50 });
51 });
52 }
53
54 (async () => {
55 await db.initialize();
56 let credential;
57 if (flags.isPAM) {
58 credential = '$PAM$';
59 } else {
60 const password = await readPassword('password: ');
61 credential = await argon2.hash(password, { type: argon2.argon2id });
62 }
63 console.log(`\t${identifier}:${credential}`);
64 await db.context(async (dbCtx) => {
65 const result = await db.authenticationUpsert(dbCtx, identifier, credential);
66 console.log(result);
67 });
68 console.log('done');
69 await db._closeConnection();
70 })();