Blame Raw
· · · 65 lines (1.9 KB)
0 contributors
1import fs from 'node:fs';
2import yaml from 'yaml';
3import storage from 'node-persist';
4import {
5 initUserStorage,
6 getPasswordSalt,
7 getPasswordHash,
8 toKey,
9} from './users.js';
10
11/**
12 * Initializes the storage with the data root specified in the config file.
13 * @param {string} configPath - The path to the config file.
14 */
15async function initStorage(configPath) {
16 const config = yaml.parse(fs.readFileSync(configPath, 'utf8'));
17 const dataRoot = config.dataRoot;
18
19 if (!dataRoot) {
20 console.error('No "dataRoot" setting found in config.yaml file.');
21 process.exit(1);
22 }
23
24 await initUserStorage(dataRoot);
25}
26
27/**
28 * Recovers a user account by enabling it and optionally setting a new password.
29 * @param {string} configPath - The path to the config file.
30 * @param {string} userAccount - The username of the account to recover.
31 * @param {string} [userPassword] - The new password for the account. If not provided, sets an empty password.
32 */
33export async function recoverPassword(configPath, userAccount, userPassword) {
34 await initStorage(configPath);
35
36 /**
37 * @type {import('./users').User}
38 */
39 const user = await storage.get(toKey(userAccount));
40
41 if (!user) {
42 console.error(`User "${userAccount}" not found.`);
43 process.exit(1);
44 }
45
46 if (!user.enabled) {
47 console.log('User is disabled. Enabling...');
48 user.enabled = true;
49 }
50
51 if (userPassword) {
52 console.log('Setting new password...');
53 const salt = getPasswordSalt();
54 const passwordHash = getPasswordHash(userPassword, salt);
55 user.password = passwordHash;
56 user.salt = salt;
57 } else {
58 console.log('Setting an empty password...');
59 user.password = '';
60 user.salt = '';
61 }
62
63 await storage.setItem(toKey(userAccount), user);
64 console.log('User recovered. A program will exit now.');
65}