2020-10-20 23:05:58 +00:00
|
|
|
import { Request, Router } from "express"
|
|
|
|
import qs from "qs"
|
2020-03-23 18:47:01 +00:00
|
|
|
import { HttpCode, HttpError } from "../../common/http"
|
2020-11-11 00:14:18 +00:00
|
|
|
import { normalize } from "../../common/util"
|
2020-11-05 22:45:58 +00:00
|
|
|
import { authenticated, ensureAuthenticated, redirect } from "../http"
|
2020-10-20 23:05:58 +00:00
|
|
|
import { proxy } from "../proxy"
|
2020-11-05 18:58:37 +00:00
|
|
|
import { Router as WsRouter } from "../wsRouter"
|
2020-03-31 19:56:01 +00:00
|
|
|
|
2020-10-20 23:05:58 +00:00
|
|
|
export const router = Router()
|
2020-03-31 17:59:07 +00:00
|
|
|
|
2020-10-20 23:05:58 +00:00
|
|
|
const getProxyTarget = (req: Request, rewrite: boolean): string => {
|
|
|
|
if (rewrite) {
|
|
|
|
const query = qs.stringify(req.query)
|
2020-10-28 16:29:43 +00:00
|
|
|
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
|
2020-03-23 18:47:01 +00:00
|
|
|
}
|
2020-10-28 16:29:43 +00:00
|
|
|
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
|
2020-10-20 23:05:58 +00:00
|
|
|
}
|
2020-03-23 18:47:01 +00:00
|
|
|
|
2020-10-20 23:05:58 +00:00
|
|
|
router.all("/(:port)(/*)?", (req, res) => {
|
|
|
|
if (!authenticated(req)) {
|
2020-11-11 00:14:18 +00:00
|
|
|
// If visiting the root (/:port only) redirect to the login page.
|
2020-10-20 23:05:58 +00:00
|
|
|
if (!req.params[0] || req.params[0] === "/") {
|
2020-11-11 00:14:18 +00:00
|
|
|
const to = normalize(`${req.baseUrl}${req.path}`)
|
2020-10-20 23:05:58 +00:00
|
|
|
return redirect(req, res, "login", {
|
2020-11-11 00:14:18 +00:00
|
|
|
to: to !== "/" ? to : undefined,
|
2020-10-20 23:05:58 +00:00
|
|
|
})
|
2020-03-23 23:02:31 +00:00
|
|
|
}
|
2020-10-20 23:05:58 +00:00
|
|
|
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
|
2020-03-23 18:47:01 +00:00
|
|
|
}
|
2020-10-20 23:05:58 +00:00
|
|
|
|
|
|
|
// Absolute redirects need to be based on the subpath when rewriting.
|
|
|
|
;(req as any).base = `${req.baseUrl}/${req.params.port}`
|
|
|
|
|
|
|
|
proxy.web(req, res, {
|
|
|
|
ignorePath: true,
|
|
|
|
target: getProxyTarget(req, true),
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2020-11-05 18:58:37 +00:00
|
|
|
export const wsRouter = WsRouter()
|
|
|
|
|
2020-11-05 22:45:58 +00:00
|
|
|
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
|
2020-11-03 22:45:03 +00:00
|
|
|
proxy.ws(req, req.ws, req.head, {
|
2020-10-20 23:05:58 +00:00
|
|
|
ignorePath: true,
|
|
|
|
target: getProxyTarget(req, true),
|
|
|
|
})
|
|
|
|
})
|