mirror of
https://github.com/ZSCGR/CloudFlare-ImgBed.git
synced 2026-08-13 04:03:42 +08:00
Merge pull request #3 from hl128k/main
增加从URL,Referer,headers,Cookie获取authCode
This commit is contained in:
+44
-6
@@ -22,21 +22,59 @@ function isAuthCodeDefined(authCode) {
|
||||
return authCode !== undefined && authCode !== null && authCode.trim() !== '';
|
||||
}
|
||||
|
||||
|
||||
function getCookieValue(cookies, name) {
|
||||
const match = cookies.match(new RegExp('(^| )' + name + '=([^;]+)'));
|
||||
return match ? decodeURIComponent(match[2]) : null;
|
||||
}
|
||||
|
||||
export async function onRequestPost(context) { // Contents of context object
|
||||
const { request, env, params, waitUntil, next, data } = context;
|
||||
const referer = request.headers.get('Referer');
|
||||
// const authCode = new URLSearchParams(new URL(referer).search).get('authcode');
|
||||
const authCode = new URL(request.url).searchParams.get('authcode');
|
||||
const clonedRequest = request.clone();
|
||||
const url = new URL(request.url);
|
||||
// 优先从请求 URL 获取 authCode
|
||||
let authCode = url.searchParams.get('authCode');
|
||||
// 如果 URL 中没有 authCode,从 Referer 中获取
|
||||
if (!authCode) {
|
||||
const referer = request.headers.get('Referer');
|
||||
if (referer) {
|
||||
try {
|
||||
const refererUrl = new URL(referer);
|
||||
authCode = new URLSearchParams(refererUrl.search).get('authCode');
|
||||
} catch (e) {
|
||||
console.error('Invalid referer URL:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果 Referer 中没有 authCode,从请求头中获取
|
||||
if (!authCode) {
|
||||
authCode = request.headers.get('authCode');
|
||||
}
|
||||
// 如果请求头中没有 authCode,从 Cookie 中获取
|
||||
if (!authCode) {
|
||||
const cookies = request.headers.get('Cookie');
|
||||
if (cookies) {
|
||||
authCode = getCookieValue(cookies, 'authCode');
|
||||
}
|
||||
}
|
||||
if (isAuthCodeDefined(env.AUTH_CODE) && !isValidAuthCode(env.AUTH_CODE, authCode)) {
|
||||
return new UnauthorizedException("error");
|
||||
}
|
||||
const clonedRequest = request.clone();
|
||||
await errorHandling(context);
|
||||
telemetryData(context);
|
||||
const targetUrl = new URL('/upload' + new URL(request.url).search, 'https://telegra.ph');
|
||||
// 构建目标 URL 时剔除 authCode 参数
|
||||
const targetUrl = new URL(url.pathname, 'https://telegra.ph');
|
||||
url.searchParams.forEach((value, key) => {
|
||||
if (key !== 'authCode') {
|
||||
targetUrl.searchParams.append(key, value);
|
||||
}
|
||||
});
|
||||
// 复制请求头并剔除 authCode
|
||||
const headers = new Headers(clonedRequest.headers);
|
||||
headers.delete('authCode');
|
||||
const response = await fetch(targetUrl.href, {
|
||||
method: clonedRequest.method,
|
||||
headers: clonedRequest.headers,
|
||||
headers: headers,
|
||||
body: clonedRequest.body,
|
||||
});
|
||||
return response;
|
||||
|
||||
Reference in New Issue
Block a user