better code: don't expose internal var
Massimo Melina committed
Jan 6, 2023 at 15:40 UTC
de2751e0d121066e82c7369cc38e0983d55fd560
2 files changed
+6
-10
src/api.accounts.ts
+4
-4
@@ -6,10 +6,10 @@ import {
6
Account,
7
accountCanLoginAdmin,
8
accountHasPassword,
9
+ accountsConfig,
10
addAccount,
11
delAccount,
12
getAccount,
12
- getAccounts,
13
getCurrentUsername,
14
setAccount
15
} from './perm'
@@ -28,7 +28,7 @@ function prepareAccount(ac: Account | undefined) {
28
const apis: ApiHandlers = {
29
30
get_usernames() {
31
- return { list: Object.keys(getAccounts()) }
31
+ return { list: Object.keys(accountsConfig.get()) }
32
},
33
34
get_account({ username }, ctx) {
@@ -37,11 +37,11 @@ const apis: ApiHandlers = {
37
},
38
39
get_accounts() {
40
- return { list: Object.values(getAccounts()).map(prepareAccount) }
40
+ return { list: Object.values(accountsConfig.get()).map(prepareAccount) }
41
},
42
43
get_admins() {
44
- return { list: Object.values(getAccounts()).map(prepareAccount).filter(ac => ac?.adminActualAccess).map(ac => ac!.username) }
44
+ return { list: _.filter(accountsConfig.get(), accountCanLoginAdmin).map(ac => ac.username) }
45
},
46
47
set_account({ username, changes }) {
src/perm.ts
+2
-6
@@ -22,10 +22,6 @@ interface Accounts { [username:string]: Account }
22
23
let accounts: Accounts = {}
24
25
-export function getAccounts() {
26
- return accounts as Readonly<typeof accounts>
27
-}
28
-
25
export function getCurrentUsername(ctx: Koa.Context): string {
26
return ctx.state.account?.username || ''
27
}
@@ -85,7 +81,7 @@ export async function updateAccount(account: Account, changer?:Changer) {
81
82
const saveAccountsAsap = saveConfigAsap
83
88
-const accountsConfig = defineConfig<Accounts>('accounts', {})
84
+export const accountsConfig = defineConfig<Accounts>('accounts', {})
85
accountsConfig.sub(async v => {
86
// we should validate content here
87
accounts = v // keep local reference
@@ -190,7 +186,7 @@ export function accountCanLogin(account: Account) {
186
}
187
188
export function accountCanLoginAdmin(account: Account) {
193
- return accountCanLogin(account) && getFromAccount(account, a => a.admin)
189
+ return accountCanLogin(account) && Boolean(getFromAccount(account, a => a.admin))
190
}
191
192
export function anyAccountCanLoginAdmin() {