用 GPT 试着写了一点,但是不是很理想
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// 从环境变量获取用户名和密码
const username = BASIC_AUTH_USERNAME;
const password = BASIC_AUTH_PASSWORD;
// 从请求中获取 Authorization 头部
const authHeader = request.headers.get("Authorization");
if (!authHeader || !isValidAuth(authHeader, username, password)) {
// 如果没有提供 Authorization 头部或者认证失败,则返回 401 Unauthorized
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}
// 认证成功,处理 OneDrive 相关的请求
return forwardRequestToOneDrive(request);
}
function isValidAuth(authHeader, username, password) {
const encoded = authHeader.split(' ')[1]; // 获取 Base64 编码的部分
const decoded = atob(encoded); // 解码 Base64
const credentials = decoded.split(':'); // 分割用户名和密码
return credentials[0] === username && credentials[1] === password;
}
async function forwardRequestToOneDrive(request) {
// 从环境变量获取 OneDrive 访问令牌
const accessToken = ONE_DRIVE_ACCESS_TOKEN;
const url = new URL(request.url);
const baseApiUrl = "https://graph.microsoft.com/v1.0/me/drive/root";
const apiRequestUrl = `${baseApiUrl}/${url.pathname}`;
const init = {
method: request.method,
headers: {
"Authorization": `Bearer ${accessToken}`,
...request.headers,
"Host": undefined, // 删除原始请求中的 Host 头部
},
body: request.method !== "GET" ? await request.body : undefined,
};
try {
const response = await fetch(apiRequestUrl, init);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
} catch (error) {
return new Response(error.toString(), { status: 500 });
}
}