zhemima/msmail
0
1 2import { authApiToken, authMiddleware } from "../../utils/auth.js";3import { addCorsHeaders } from "../../utils/cors.js";4import { get_access_token, activateMailbox, syncMailbox } from '../../utils/mail.js';5 6export const onRequest = async (context: RouteContext): Promise<Response> => {7 const request = context.request;8 const env: Env = context.env;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 if (request.method === 'OPTIONS') {17 return new Response(null, {18 status: 200,19 headers: {20 'Access-Control-Allow-Origin': '*',21 'Access-Control-Allow-Methods': 'POST, OPTIONS',22 'Access-Control-Allow-Headers': 'Content-Type, Authorization'23 }24 });25 }26 27 if (request.method !== 'POST') {28 return new Response('Method not allowed', { status: 405 });29 }30 31 try {32 const { email } = await request.json() as any;33 if (!email) {34 throw new Error("Email is required");35 }36 37 // 从KV获取刷新令牌38 const tokenInfoStr = await env.KV.get(`refresh_token_${email}`);39 if (!tokenInfoStr) {40 throw new Error("No refresh token found for this email");41 }42 43 const tokenInfo = JSON.parse(tokenInfoStr);44 const access_token = await get_access_token(tokenInfo, env.ENTRA_CLIENT_ID, env.ENTRA_CLIENT_SECRET);45 46 // 执行邮箱激活操作47 console.log(`开始激活邮箱: ${email}`);48 await activateMailbox(access_token);49 await syncMailbox(access_token);50 51 // 等待同步完成52 await new Promise(resolve => setTimeout(resolve, 3000));53 54 return new Response(55 JSON.stringify({ 56 success: true, 57 message: "邮箱激活完成",58 email: email,59 timestamp: new Date().toISOString()60 }),61 {62 status: 200,63 headers: {64 'Content-Type': 'application/json',65 'Access-Control-Allow-Origin': '*'66 }67 }68 );69 } catch (error: any) {70 console.error('邮箱激活失败:', error);71 return new Response(72 JSON.stringify({ 73 success: false,74 error: error.message,75 message: "邮箱激活失败"76 }),77 {78 status: 500,79 headers: {80 'Content-Type': 'application/json',81 'Access-Control-Allow-Origin': '*'82 }83 }84 );85 }86};87 