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-10-20 23:05:58 +00:00
|
|
|
import { authenticated, redirect } from "../http"
|
|
|
|
import { proxy } from "../proxy"
|
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)) {
|
|
|
|
// If visiting the root (/proxy/:port and nothing else) redirect to the
|
|
|
|
// login page.
|
|
|
|
if (!req.params[0] || req.params[0] === "/") {
|
|
|
|
return redirect(req, res, "login", {
|
|
|
|
to: `${req.baseUrl}${req.path}` || "/",
|
|
|
|
})
|
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-03 22:45:03 +00:00
|
|
|
router.ws("/(:port)(/*)?", (req) => {
|
|
|
|
proxy.ws(req, req.ws, req.head, {
|
2020-10-20 23:05:58 +00:00
|
|
|
ignorePath: true,
|
|
|
|
target: getProxyTarget(req, true),
|
|
|
|
})
|
|
|
|
})
|