| 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, limit = 10 } = params; |
|
|
| |
| if (!email) { |
| return new Response( |
| JSON.stringify({ |
| error: 'Missing required parameters: email' |
| }), |
| { status: 400 } |
| ); |
| } |
|
|
| try { |
| |
| 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, Number(limit)); |
| |
| return new Response( |
| JSON.stringify(emails), |
| { |
| 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': '*' |
| } |
| } |
| ); |
| } |
| }; |