better code: simplify false middleware
Massimo Melina committed
Mar 13, 2023 at 16:00 UTC
e33844999bf0352acccc480a2d2dc65db864a896
2 files changed
+15
-17
src/middlewares.ts
+2
-2
@@ -121,7 +121,7 @@ export const serveGuiAndSharedFiles: Koa.Middleware = async (ctx, next) => {
121
if (isFolder && !path.endsWith('/'))
122
return ctx.redirect(ctx.state.revProxyPath + ctx.originalUrl + '/')
123
if (canRead && !isFolder)
124
- return node.source ? serveFileNode(node)(ctx,next)
124
+ return node.source ? serveFileNode(ctx, node)
125
: next()
126
if (!canRead) {
127
ctx.status = cantReadStatusCode(node)
@@ -140,7 +140,7 @@ export const serveGuiAndSharedFiles: Koa.Middleware = async (ctx, next) => {
140
if (node.default) {
141
const def = await urlToNode(path + node.default, ctx)
142
return !def ? next()
143
- : hasPermission(def, 'can_read', ctx) ? serveFileNode(def)(ctx, next)
143
+ : hasPermission(def, 'can_read', ctx) ? serveFileNode(ctx, def)
144
: ctx.status = cantReadStatusCode(def)
145
}
146
return serveFrontendFiles(ctx, next)
src/serveFile.ts
+13
-15
@@ -21,28 +21,26 @@ import { promisify } from 'util'
21
22
const allowedReferer = defineConfig('allowed_referer', '')
23
24
-export function serveFileNode(node: VfsNode) : Koa.Middleware {
24
+export function serveFileNode(ctx: Koa.Context, node: VfsNode) {
25
const { source, mime } = node
26
const name = getNodeName(node)
27
const mimeString = typeof mime === 'string' ? mime
28
: _.find(mime, (val,mask) => isMatch(name, mask))
29
- return (ctx, next) => {
30
- const allowed = allowedReferer.get()
31
- if (allowed) {
32
- const ref = /\/\/([^:/]+)/.exec(ctx.get('referer'))?.[1] // extract host from url
33
- if (ref && ref !== host() // automatic accept if referer is basically the hosting domain
34
- && !isMatch(ref, allowed))
35
- return ctx.status = HTTP_FORBIDDEN
29
+ const allowed = allowedReferer.get()
30
+ if (allowed) {
31
+ const ref = /\/\/([^:/]+)/.exec(ctx.get('referer'))?.[1] // extract host from url
32
+ if (ref && ref !== host() // automatic accept if referer is basically the hosting domain
33
+ && !isMatch(ref, allowed))
34
+ return ctx.status = HTTP_FORBIDDEN
35
37
- function host() {
38
- const s = ctx.get('host')
39
- return s[0] === '[' ? s.slice(1, s.indexOf(']')) : s?.split(':')[0]
40
- }
36
+ function host() {
37
+ const s = ctx.get('host')
38
+ return s[0] === '[' ? s.slice(1, s.indexOf(']')) : s?.split(':')[0]
39
}
42
-
43
- ctx.vfsNode = node // useful to tell service files from files shared by the user
44
- return serveFile(ctx, source||'', mimeString)
40
}
41
+
42
+ ctx.vfsNode = node // useful to tell service files from files shared by the user
43
+ return serveFile(ctx, source||'', mimeString)
44
}
45
46
const mimeCfg = defineConfig<Record<string,string>>('mime', { '*': 'auto' })