File size: 3,869 Bytes
6c6d16c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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[]> {
    // 创建一个队列来存储所有的 promise
    const queue: Promise<any>[] = [];
    const results: any[] = new Array(items.length);
    let nextIndex = 0;

    // 创建指定数量的worker
    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'
                };
            }
        }
    });

    // 等待所有worker完成
    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; // 90天转换为毫秒
    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 }
        );
    }
};