106 lines
2.9 KiB
JavaScript
106 lines
2.9 KiB
JavaScript
import { BASE_URL } from "../../../actions/core/env";
|
|
import { getToken } from "../../../actions/core/token";
|
|
import { azureHeaders } from "../../../actions/core/headers";
|
|
import { consoleLogger } from "../../../actions/core/logger";
|
|
import { hashAPIPath } from "../../../actions/core/hash";
|
|
import axios from "axios";
|
|
import { respondError, respondSuccess } from "../middleware/apiResponse";
|
|
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "../auth/[...nextauth]";
|
|
|
|
const isTrustedInternalDestination = () => {
|
|
try {
|
|
return (
|
|
new URL(BASE_URL).origin ===
|
|
new URL(process.env.NEXTAUTH_URL).origin
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const forbidden = (res) =>
|
|
respondError(res, {
|
|
status: 403,
|
|
code: "FORBIDDEN",
|
|
message: "Request not permitted"
|
|
});
|
|
|
|
const isValidContainer = (value) =>
|
|
typeof value === "string" &&
|
|
value.length >= 3 &&
|
|
value.length <= 63 &&
|
|
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
|
|
|
|
export default async function ApiProxy(req, res) {
|
|
res.setHeader("Allow", "GET");
|
|
|
|
if (req.method !== "GET") {
|
|
return respondError(res, {
|
|
status: 405,
|
|
code: "METHOD_NOT_ALLOWED",
|
|
message: "Method not allowed"
|
|
});
|
|
}
|
|
|
|
const containerName = req.query.container;
|
|
|
|
if (typeof containerName === "undefined" || containerName === "") {
|
|
return respondError(res, {
|
|
status: 400,
|
|
code: "MISSING_REQUIRED_QUERY",
|
|
message: "container is required"
|
|
});
|
|
}
|
|
|
|
if (!isValidContainer(containerName)) {
|
|
return respondError(res, {
|
|
status: 400,
|
|
code: "INVALID_REQUEST",
|
|
message: "Invalid request"
|
|
});
|
|
}
|
|
|
|
const session = await getServerSession(req, res, authOptions(req, res));
|
|
if (
|
|
typeof session?.user?.id !== "string" ||
|
|
session.user.id.length === 0 ||
|
|
session.user.id !== containerName
|
|
) {
|
|
return forbidden(res);
|
|
}
|
|
|
|
if (!isTrustedInternalDestination()) {
|
|
return forbidden(res);
|
|
}
|
|
|
|
const token = await getToken();
|
|
|
|
const queryUrl =
|
|
"/api/file/getrepsblob?container=" + encodeURIComponent(containerName);
|
|
|
|
try {
|
|
const config = azureHeaders(token.access_token);
|
|
|
|
const { data } = await axios.get(
|
|
BASE_URL + queryUrl + hashAPIPath(queryUrl),
|
|
{
|
|
...config,
|
|
headers: {
|
|
...config.headers,
|
|
Cookie: req.headers.cookie || ""
|
|
},
|
|
maxRedirects: 0
|
|
}
|
|
);
|
|
return respondSuccess(res, data);
|
|
} catch (error) {
|
|
consoleLogger(error);
|
|
return respondError(res, {
|
|
status: 400,
|
|
code: "GET_REPS_BLOB_PROXY_FAILED",
|
|
message: "Failed to fetch representation blobs"
|
|
});
|
|
}
|
|
}
|