import { authApiToken, authMiddleware } from "../../utils/auth.js"; import { addCorsHeaders } from "../../utils/cors.js"; import { get_access_token, sendEmail } from "../../utils/mail.js"; export const onRequest = async (context: RouteContext): Promise => { 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 method = request.method; if (method !== 'POST') { return new Response( JSON.stringify({ error: 'Method not allowed' }), { status: 405 } ); } try { const { email, to, subject, body, isHtml = false } = await request.json() as any; // 检查必要参数 if (!email || !to || !subject || !body) { return new Response( JSON.stringify({ error: 'Missing required parameters: email, to, subject, body' }), { status: 400 } ); } // 从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); // 发送邮件 await sendEmail(access_token, Array.isArray(to) ? to : [to], subject, body, isHtml); return new Response( JSON.stringify({ message: 'Email sent successfully' }), { 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': '*' } } ); } };