better code: centralized logic
Massimo Melina committed
Dec 10, 2023 at 16:52 UTC
d0e113e0bb1bae19d0f571f765a49fef0ac6f6d5
2 files changed
+12
-5
src/adminApis.ts
+2
-2
@@ -21,7 +21,7 @@ import netApis from './api.net'
21
import { getConnections } from './connections'
22
import { apiAssertTypes, debounceAsync, isLocalHost, makeNetMatcher, onOff, tryJson, wait, waitFor } from './misc'
23
import events from './events'
24
-import { accountCanLoginAdmin, accountsConfig, getFromAccount } from './perm'
24
+import { accountCanLoginAdmin, accountsConfig } from './perm'
25
import Koa from 'koa'
26
import { getProxyDetected } from './middlewares'
27
import { writeFile } from 'fs/promises'
@@ -214,7 +214,7 @@ export const title = defineConfig('title', "File server")
214
export function ctxAdminAccess(ctx: Koa.Context) {
215
return !ctx.ips.length // we consider localhost_admin only if no proxy is being used
216
&& localhostAdmin.get() && isLocalHost(ctx)
217
- || getFromAccount(ctx.state.account, a => a.admin)
217
+ || ctx.state.account && accountCanLoginAdmin(ctx.state.account)
218
}
219
220
const frpDebounced = debounceAsync(async () => {
src/middlewares.ts
+10
-3
@@ -15,8 +15,8 @@ import { serveGuiFiles } from './serveGuiFiles'
15
import mount from 'koa-mount'
16
import { Readable } from 'stream'
17
import { applyBlock } from './block'
18
-import { accountCanLogin, getAccount } from './perm'
19
-import { socket2connection, updateConnection, normalizeIp, disconnect } from './connections'
18
+import { Account, accountCanLogin, getAccount } from './perm'
19
+import { socket2connection, updateConnection, normalizeIp, disconnect, Connection } from './connections'
20
import basicAuth from 'basic-auth'
21
import { invalidSessions, srpCheck } from './auth'
22
import { basename, dirname } from 'path'
@@ -218,10 +218,10 @@ export const prepareState: Koa.Middleware = async (ctx, next) => {
218
ctx.session.maxAge = sessionDuration.compiled()
219
}
220
// calculate these once and for all
221
+ const conn = ctx.state.connection = socket2connection(ctx.socket)!
222
const a = ctx.state.account = await urlLogin() || await getHttpAccount() || getAccount(ctx.session?.username, false)
223
if (a && !accountCanLogin(a))
224
ctx.state.account = undefined
224
- const conn = ctx.state.connection = socket2connection(ctx.socket)
225
ctx.state.revProxyPath = ctx.get('x-forwarded-prefix')
226
ctx.state.browsing = undefined
227
if (conn)
@@ -250,6 +250,13 @@ declare module "koa" {
250
interface BaseContext {
251
params: Record<string, any>
252
}
253
+ interface DefaultState {
254
+ account?: Account
255
+ revProxyPath: string
256
+ connection: Connection
257
+ serveApp?: boolean
258
+ browsing?: string
259
+ }
260
}
261
export const paramsDecoder: Koa.Middleware = async (ctx, next) => {
262
ctx.params = ctx.method === 'POST' && ctx.originalUrl.startsWith(API_URI)