blob: 77a8d9daa2ae5c7d0c27a47c1e65210ac320293a [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
23@Service()
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050024export class Accounts {
25 private readonly filename = 'accounts.json';
26 private accounts: Record<string, string>;
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050027
28 constructor() {
29 let buffer: Buffer;
30
31 try {
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050032 buffer = readFileSync(this.filename);
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050033 } catch (e) {
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050034 buffer = Buffer.from('{}');
35 }
36
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050037 this.accounts = JSON.parse(buffer.toString());
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050038 }
39
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050040 get(username: string): string | undefined {
41 return this.accounts[username];
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050042 }
43
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050044 set(username: string, password: string): void {
45 this.accounts[username] = password;
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050046 }
47
Misha Krieger-Raynauldb933fbb2022-11-15 15:11:09 -050048 async save(): Promise<void> {
49 await writeFile(this.filename, JSON.stringify(this.accounts, null, 2) + '\n');
Michelle Sepkap Sime6967fb92022-11-08 08:39:36 -050050 }
51}