Validate 验证 API Key 并返回用户信息
(ctx context.Context, key string)
| 65 | |
| 66 | // Validate 验证 API Key 并返回用户信息 |
| 67 | func (a *APIKeyAuthenticator) Validate(ctx context.Context, key string) (*User, error) { |
| 68 | if key == "" { |
| 69 | return nil, ErrInvalidCredentials |
| 70 | } |
| 71 | |
| 72 | info, err := a.store.Get(ctx, key) |
| 73 | if err != nil { |
| 74 | return nil, ErrInvalidCredentials |
| 75 | } |
| 76 | |
| 77 | // 检查是否过期 |
| 78 | if info.ExpiresAt != nil && time.Now().After(*info.ExpiresAt) { |
| 79 | return nil, ErrExpiredToken |
| 80 | } |
| 81 | |
| 82 | // 更新最后使用时间 |
| 83 | now := time.Now() |
| 84 | info.LastUsed = &now |
| 85 | // 这里可以异步更新,不阻塞请求 |
| 86 | go func() { |
| 87 | _ = a.store.Create(context.Background(), info) |
| 88 | }() |
| 89 | |
| 90 | return &User{ |
| 91 | ID: info.UserID, |
| 92 | Roles: info.Roles, |
| 93 | Metadata: map[string]any{ |
| 94 | "api_key_name": info.Name, |
| 95 | }, |
| 96 | }, nil |
| 97 | } |
| 98 | |
| 99 | // GenerateAPIKey 生成新的 API Key |
| 100 | func GenerateAPIKey() (string, error) { |
no test coverage detected