Convert routes to Express

This commit is contained in:
Asher
2020-10-20 18:05:58 -05:00
parent 4b6cbacbad
commit 112eda4605
20 changed files with 1031 additions and 1523 deletions

View File

@@ -1,43 +1,43 @@
import * as http from "http"
import { Request, Router } from "express"
import qs from "qs"
import { HttpCode, HttpError } from "../../common/http"
import { HttpProvider, HttpResponse, Route, WsResponse } from "../http"
import { authenticated, redirect } from "../http"
import { proxy } from "../proxy"
/**
* Proxy HTTP provider.
*/
export class ProxyHttpProvider extends HttpProvider {
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
if (!this.authenticated(request)) {
if (this.isRoot(route)) {
return { redirect: "/login", query: { to: route.fullPath } }
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
export const router = Router()
// Ensure there is a trailing slash so relative paths work correctly.
if (this.isRoot(route) && !route.fullPath.endsWith("/")) {
return {
redirect: `${route.fullPath}/`,
}
}
const port = route.base.replace(/^\//, "")
return {
proxy: {
strip: `${route.providerBase}/${port}`,
port,
},
}
}
public async handleWebSocket(route: Route, request: http.IncomingMessage): Promise<WsResponse> {
this.ensureAuthenticated(request)
const port = route.base.replace(/^\//, "")
return {
proxy: {
strip: `${route.providerBase}/${port}`,
port,
},
}
const getProxyTarget = (req: Request, rewrite: boolean): string => {
if (rewrite) {
const query = qs.stringify(req.query)
return `http://127.0.0.1:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
return `http://127.0.0.1:${req.params.port}/${req.originalUrl}`
}
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}` || "/",
})
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// 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),
})
})
router.ws("/(:port)(/*)?", (socket, head, req) => {
proxy.ws(req, socket, head, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})