File size: 1,402 Bytes
6e73b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { HTTPError } from 'h3';

/**
 * 认证中间件 - 验证 API 密钥
 */
export const authMiddleware = (event) => {
  // 跳过健康检查的认证
  if (event.path === '/health') {
    return;
  }

  // 只对 API 路由进行认证
  if (!event.path?.startsWith('/v1/')) {
    return;
  }

  // 尝试多种方式获取 authorization 头
  const authorization = event.headers?.authorization ||
                       event.req?.headers?.authorization ||
                       event.node?.req?.headers?.authorization;

  if (!authorization) {
    throw new HTTPError(401, 'Authorization header is required');
  }

  // 支持 Bearer token 格式
  const token = authorization.startsWith('Bearer ')
    ? authorization.slice(7)
    : authorization;

  if (!token) {
    throw new HTTPError(401, 'Invalid authorization format');
  }

  // 验证 token(这里可以根据需要实现更复杂的验证逻辑)
  if (!isValidApiKey(token)) {
    throw new HTTPError(401, 'Invalid API key');
  }

  // 将 API 密钥添加到事件上下文中
  event.context.apiKey = token;
};

/**
 * 验证 API 密钥
 */
function isValidApiKey(apiKey) {
  // 简单验证:检查是否为非空字符串
  // 在实际应用中,你可能需要:
  // 1. 检查数据库中的有效密钥
  // 2. 验证密钥格式
  // 3. 检查密钥权限
  return typeof apiKey === 'string' && apiKey.length > 0;
}