CoolFace
Apppublic

zhemima/msmail

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