pathProxy.ts 1.7 KB
Newer Older
1 2
import { Request, Response } from "express"
import * as path from "path"
A
Asher 已提交
3
import qs from "qs"
A
Asher 已提交
4
import { HttpCode, HttpError } from "../../common/http"
A
Asher 已提交
5
import { normalize } from "../../common/util"
A
Asher 已提交
6
import { authenticated, ensureAuthenticated, redirect } from "../http"
7 8
import { proxy as _proxy } from "../proxy"
import { WebsocketRequest } from "../wsRouter"
A
Asher 已提交
9

10
const getProxyTarget = (req: Request, passthroughPath?: boolean): string => {
11 12
  if (passthroughPath) {
    return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
A
Asher 已提交
13
  }
14 15
  const query = qs.stringify(req.query)
  return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
A
Asher 已提交
16
}
A
Asher 已提交
17

18 19 20 21 22 23 24
export function proxy(
  req: Request,
  res: Response,
  opts?: {
    passthroughPath?: boolean
  },
): void {
A
Asher 已提交
25
  if (!authenticated(req)) {
A
Asher 已提交
26
    // If visiting the root (/:port only) redirect to the login page.
A
Asher 已提交
27
    if (!req.params[0] || req.params[0] === "/") {
A
Asher 已提交
28
      const to = normalize(`${req.baseUrl}${req.path}`)
A
Asher 已提交
29
      return redirect(req, res, "login", {
A
Asher 已提交
30
        to: to !== "/" ? to : undefined,
A
Asher 已提交
31
      })
A
Asher 已提交
32
    }
A
Asher 已提交
33
    throw new HttpError("Unauthorized", HttpCode.Unauthorized)
A
Asher 已提交
34
  }
A
Asher 已提交
35

36
  if (!opts?.passthroughPath) {
37
    // Absolute redirects need to be based on the subpath when rewriting.
38 39
    // See proxy.ts.
    ;(req as any).base = req.path.split(path.sep).slice(0, 3).join(path.sep)
40
  }
A
Asher 已提交
41

42
  _proxy.web(req, res, {
A
Asher 已提交
43
    ignorePath: true,
44
    target: getProxyTarget(req, opts?.passthroughPath),
A
Asher 已提交
45
  })
46
}
A
Asher 已提交
47

48 49 50 51 52 53 54 55
export function wsProxy(
  req: WebsocketRequest,
  opts?: {
    passthroughPath?: boolean
  },
): void {
  ensureAuthenticated(req)
  _proxy.ws(req, req.ws, req.head, {
A
Asher 已提交
56
    ignorePath: true,
57
    target: getProxyTarget(req, opts?.passthroughPath),
A
Asher 已提交
58
  })
59
}