为 Web UI 添加完整的登录验证系统,遵循 CQRS 架构模式。 主要功能: - 创建登录页面 UI (web/login.html) - 美观的渐变背景设计 - 密钥输入和验证 - 错误提示和加载状态 - 实现登录验证 (遵循 CQRS) - 新增 LoginQuery 和 LoginHandler (internal/api/handlers/auth_handlers.go) - 新增 AuthEndpoint (internal/api/endpoints/auth_endpoints.go) - 注册登录接口 /auth/login (无需授权) - 更新主页面 (web/index.html) - 添加登录状态检查 - 未登录显示提示信息 - 所有 API 请求自动携带 X-API-Key 头 - 添加退出登录功能 - 401 错误自动跳转登录页 - 更新路由配置 (cmd/server/main.go) - 添加 /auth/login 公开路由 - 注册登录处理器和端点 - 新增登录文档 (docs/LOGIN_GUIDE.md) - 完整的使用说明 - 技术实现细节 - API 接口说明 安全特性: - 密钥存储在 localStorage - 自动处理登录过期 - 支持主动退出登录 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
46 lines
866 B
Go
46 lines
866 B
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
)
|
|
|
|
// LoginQuery 登录查询
|
|
type LoginQuery struct {
|
|
APIKey string `json:"api_key" binding:"required"`
|
|
}
|
|
|
|
// LoginResult 登录结果
|
|
type LoginResult struct {
|
|
Success bool `json:"success"`
|
|
Message string `json:"message"`
|
|
Token string `json:"token,omitempty"`
|
|
}
|
|
|
|
// LoginHandler 登录处理器
|
|
type LoginHandler struct {
|
|
apiKey string
|
|
}
|
|
|
|
// NewLoginHandler 创建登录处理器
|
|
func NewLoginHandler(apiKey string) *LoginHandler {
|
|
return &LoginHandler{
|
|
apiKey: apiKey,
|
|
}
|
|
}
|
|
|
|
// Handle 处理登录查询
|
|
func (h *LoginHandler) Handle(ctx context.Context, query LoginQuery) (LoginResult, error) {
|
|
if query.APIKey == h.apiKey {
|
|
return LoginResult{
|
|
Success: true,
|
|
Message: "登录成功",
|
|
Token: query.APIKey,
|
|
}, nil
|
|
}
|
|
|
|
return LoginResult{
|
|
Success: false,
|
|
Message: "API密钥无效",
|
|
}, nil
|
|
}
|