blob: 1d3df0549665b10f0eee9a863ff30408db08b838 [file] [log] [blame]
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -05001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
18import { readFileSync } from 'node:fs';
19import { writeFile } from 'node:fs/promises';
20
21import { Service } from 'typedi';
22
Issam E. Maghnib05ad992022-11-20 23:50:48 +000023interface AccountsFormat {
24 local: Record<string, string>;
25 jams: Record<string, string>;
26}
27
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050028@Service()
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050029export class Accounts {
30 private readonly filename = 'accounts.json';
Issam E. Maghnib05ad992022-11-20 23:50:48 +000031 private accounts: AccountsFormat;
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050032
33 constructor() {
34 let buffer: Buffer;
35
36 try {
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050037 buffer = readFileSync(this.filename);
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050038 } catch (e) {
Issam E. Maghni5bc33a32022-11-22 21:36:19 +000039 buffer = Buffer.from('{"local":{},"jams":{}}');
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050040 }
41
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050042 this.accounts = JSON.parse(buffer.toString());
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050043 }
44
Issam E. Maghnib05ad992022-11-20 23:50:48 +000045 get(username: string, isJams = false): string | undefined {
46 return this.accounts[isJams ? 'jams' : 'local'][username];
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050047 }
48
Issam E. Maghnib05ad992022-11-20 23:50:48 +000049 set(username: string, password: string, isJams = false): void {
50 this.accounts[isJams ? 'jams' : 'local'][username] = password;
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050051 }
52
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050053 async save(): Promise<void> {
54 await writeFile(this.filename, JSON.stringify(this.accounts, null, 2) + '\n');
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050055 }
56}