File size: 2,197 Bytes
7fc5208 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import { authApiToken, authMiddleware } from "../../utils/auth.js";
import { addCorsHeaders } from "../../utils/cors.js";
import { get_access_token, getEmails } from "../../utils/mail.js";
export const onRequest = async (context: RouteContext): Promise<Response> => {
const request = context.request;
const env: Env = context.env;
// 验证权限
const authResponse = await authMiddleware(request, env);
const apiResponse = await authApiToken(request, env);
if (authResponse && apiResponse) {
return addCorsHeaders(authResponse);
}
// 获取请求参数
const url = new URL(request.url);
const method = request.method;
const params: any = method === 'GET'
? Object.fromEntries(url.searchParams)
: await request.json();
const { email, mailbox = "INBOX ", response_type = 'json' } = params;
// 检查必要参数
if (!email) {
return new Response(
JSON.stringify({
error: 'Missing required parameters: email'
}),
{ status: 400 }
);
}
try {
// 从KV获取刷新令牌
const tokenInfoStr = await env.KV.get(`refresh_token_${email}`);
if (!tokenInfoStr) {
throw new Error("No refresh token found for this email");
}
const tokenInfo = JSON.parse(tokenInfoStr);
const access_token = await get_access_token(tokenInfo, env.ENTRA_CLIENT_ID, env.ENTRA_CLIENT_SECRET);
const emails = await getEmails(access_token, 1); // 只获取最新的一封邮件
return new Response(
JSON.stringify(emails[0] || null),
{
status: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}
);
} catch (error: any) {
return new Response(
JSON.stringify({ error: error.message }),
{
status: 500, headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}
);
}
}; |