|
import { authApiToken, authMiddleware } from "../../utils/auth.js"; |
|
import { addCorsHeaders } from "../../utils/cors.js"; |
|
import { AuthService } from "../../utils/authService.js"; |
|
|
|
|
|
async function processBatch<T>( |
|
items: T[], |
|
processor: (item: T) => Promise<any>, |
|
concurrency: number = 2 |
|
): Promise<any[]> { |
|
|
|
const queue: Promise<any>[] = []; |
|
const results: any[] = new Array(items.length); |
|
let nextIndex = 0; |
|
|
|
|
|
const workers = new Array(concurrency).fill(null).map(async () => { |
|
while (nextIndex < items.length) { |
|
const currentIndex = nextIndex++; |
|
try { |
|
const result = await processor(items[currentIndex]); |
|
results[currentIndex] = result; |
|
} catch (error) { |
|
results[currentIndex] = { |
|
error: error instanceof Error ? error.message : 'Unknown error' |
|
}; |
|
} |
|
} |
|
}); |
|
|
|
|
|
await Promise.all(workers); |
|
return results; |
|
} |
|
|
|
|
|
async function checkAuthStatus(email: string, env: Env): Promise<{ needsAuth: boolean, reason?: string }> { |
|
const tokenInfoStr = await env.KV.get(`refresh_token_${email}`); |
|
if (!tokenInfoStr) { |
|
return { needsAuth: true, reason: "未认证" }; |
|
} |
|
|
|
const tokenInfo = JSON.parse(tokenInfoStr); |
|
const threeMonths = 90 * 24 * 60 * 60 * 1000; |
|
const isExpired = Date.now() - tokenInfo.timestamp > threeMonths; |
|
|
|
if (isExpired) { |
|
return { needsAuth: true, reason: "认证已过期" }; |
|
} |
|
|
|
return { needsAuth: false }; |
|
} |
|
|
|
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); |
|
} |
|
|
|
try { |
|
const { emails } = await request.json() as { emails: string[] }; |
|
if (!emails || !Array.isArray(emails)) { |
|
throw new Error("Emails array is required"); |
|
} |
|
|
|
const authService = new AuthService(env); |
|
const results = await processBatch( |
|
emails, |
|
async (email) => { |
|
try { |
|
|
|
const authStatus = await checkAuthStatus(email, env); |
|
if (!authStatus.needsAuth) { |
|
return { |
|
email, |
|
success: true, |
|
message: "已认证且在有效期内" |
|
}; |
|
} |
|
|
|
|
|
const result = await authService.authenticateEmail(email); |
|
return { |
|
email, |
|
success: result.success, |
|
message: authStatus.reason, |
|
error: result.error |
|
}; |
|
} catch (error: any) { |
|
return { |
|
email, |
|
success: false, |
|
error: error.message || 'Failed to process' |
|
}; |
|
} |
|
}, |
|
2 |
|
); |
|
|
|
return new Response( |
|
JSON.stringify(results), |
|
{ |
|
status: 200, |
|
headers: { 'Content-Type': 'application/json' } |
|
} |
|
); |
|
|
|
} catch (error: any) { |
|
return new Response( |
|
JSON.stringify({ error: error.message }), |
|
{ status: 500 } |
|
); |
|
} |
|
}; |
|
|