Merge upstream main and resolve conflicts
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -504,6 +506,79 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// AutoSetup godoc
|
||||
// @Summary 自动初始化(Lite 桌面版)
|
||||
// @Description Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} types.LoginResponse
|
||||
// @Failure 403 {object} errors.AppError "非 Lite 版本"
|
||||
// @Router /auth/auto-setup [post]
|
||||
func (h *AuthHandler) AutoSetup(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
if Edition != "lite" {
|
||||
appErr := errors.NewForbiddenError("auto-setup is only available in lite edition")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
const defaultEmail = "admin@weknora.local"
|
||||
|
||||
user, _ := h.userService.GetUserByEmail(ctx, defaultEmail)
|
||||
if user == nil {
|
||||
logger.Info(ctx, "Auto-setup: creating default user and tenant for lite edition")
|
||||
|
||||
randomBytes := make([]byte, 24)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
appErr := errors.NewInternalServerError("auto-setup failed: unable to generate credentials")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
randomPassword := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
randomUsername := fmt.Sprintf("user_%s", base64.RawURLEncoding.EncodeToString(randomBytes[:6]))
|
||||
|
||||
_, err := h.userService.Register(ctx, &types.RegisterRequest{
|
||||
Username: randomUsername,
|
||||
Email: defaultEmail,
|
||||
Password: randomPassword,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Auto-setup: failed to register default user: %v", err)
|
||||
appErr := errors.NewInternalServerError("auto-setup failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
user, _ = h.userService.GetUserByEmail(ctx, defaultEmail)
|
||||
if user == nil {
|
||||
appErr := errors.NewInternalServerError("auto-setup failed: user not found after registration")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
accessToken, refreshToken, err := h.userService.GenerateTokens(ctx, user)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Auto-setup: failed to generate tokens: %v", err)
|
||||
appErr := errors.NewInternalServerError("auto-setup failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
tenant, _ := h.tenantService.GetTenantByID(ctx, user.TenantID)
|
||||
|
||||
logger.Info(ctx, "Auto-setup: completed successfully")
|
||||
c.JSON(http.StatusOK, &types.LoginResponse{
|
||||
Success: true,
|
||||
Message: "Auto-setup successful",
|
||||
User: user,
|
||||
Tenant: tenant,
|
||||
Token: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
})
|
||||
}
|
||||
|
||||
// ValidateToken godoc
|
||||
// @Summary 验证令牌
|
||||
// @Description 验证访问令牌是否有效
|
||||
|
||||
+23
-16
@@ -14,6 +14,7 @@ import (
|
||||
// validIMPlatforms is the set of supported IM platforms.
|
||||
var validIMPlatforms = map[string]bool{
|
||||
"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true, "mattermost": true,
|
||||
"wechat": true,
|
||||
}
|
||||
|
||||
// IMHandler handles IM platform callback requests and channel CRUD.
|
||||
@@ -45,13 +46,13 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Platform string `json:"platform" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
Mode string `json:"mode"`
|
||||
OutputMode string `json:"output_mode"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Credentials types.JSON `json:"credentials"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Platform string `json:"platform" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
Mode string `json:"mode"`
|
||||
OutputMode string `json:"output_mode"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Credentials types.JSON `json:"credentials"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -59,7 +60,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
}
|
||||
|
||||
if !validIMPlatforms[req.Platform] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram', 'dingtalk' or 'mattermost'"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram', 'dingtalk', 'mattermost' or 'wechat'"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -77,15 +78,21 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
if req.Enabled != nil {
|
||||
channel.Enabled = *req.Enabled
|
||||
}
|
||||
if channel.Mode == "" {
|
||||
if channel.Platform == "mattermost" {
|
||||
channel.Mode = "webhook"
|
||||
} else {
|
||||
channel.Mode = "websocket"
|
||||
// WeChat uses long-polling mode and full output only
|
||||
if req.Platform == "wechat" {
|
||||
channel.Mode = "longpoll"
|
||||
channel.OutputMode = "full"
|
||||
} else {
|
||||
if channel.Mode == "" {
|
||||
if channel.Platform == "mattermost" {
|
||||
channel.Mode = "webhook"
|
||||
} else {
|
||||
channel.Mode = "websocket"
|
||||
}
|
||||
}
|
||||
if channel.OutputMode == "" {
|
||||
channel.OutputMode = "stream"
|
||||
}
|
||||
}
|
||||
if channel.OutputMode == "" {
|
||||
channel.OutputMode = "stream"
|
||||
}
|
||||
if channel.Credentials == nil {
|
||||
channel.Credentials = types.JSON("{}")
|
||||
|
||||
@@ -1468,6 +1468,7 @@ type RemoteModelCheckRequest struct {
|
||||
ModelName string `json:"modelName" binding:"required"`
|
||||
BaseURL string `json:"baseUrl" binding:"required"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Provider string `json:"provider"`
|
||||
}
|
||||
|
||||
// CheckRemoteModel godoc
|
||||
@@ -1513,8 +1514,9 @@ func (h *InitializationHandler) CheckRemoteModel(c *gin.Context) {
|
||||
Name: req.ModelName,
|
||||
Source: "remote",
|
||||
Parameters: types.ModelParameters{
|
||||
BaseURL: req.BaseURL,
|
||||
APIKey: req.APIKey,
|
||||
BaseURL: req.BaseURL,
|
||||
APIKey: req.APIKey,
|
||||
Provider: req.Provider,
|
||||
},
|
||||
Type: "llm", // 默认类型,实际检查时不区分具体类型
|
||||
}
|
||||
@@ -1644,6 +1646,7 @@ func (h *InitializationHandler) checkRemoteModelConnection(ctx context.Context,
|
||||
ModelName: model.Name,
|
||||
APIKey: model.Parameters.APIKey,
|
||||
ModelID: model.Name,
|
||||
Provider: model.Parameters.Provider,
|
||||
}
|
||||
|
||||
// 创建聊天实例
|
||||
@@ -1669,15 +1672,20 @@ func (h *InitializationHandler) checkRemoteModelConnection(ctx context.Context,
|
||||
// 使用聊天实例进行测试
|
||||
_, err = chatInstance.Chat(ctx, testMessages, testOptions)
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
// 根据错误类型返回不同的错误信息
|
||||
if strings.Contains(err.Error(), "401") || strings.Contains(err.Error(), "unauthorized") {
|
||||
if strings.Contains(errMsg, "401") || strings.Contains(errMsg, "unauthorized") {
|
||||
return false, "认证失败,请检查API Key"
|
||||
} else if strings.Contains(err.Error(), "403") || strings.Contains(err.Error(), "forbidden") {
|
||||
return false, "权限不足,请检查API Key权限:" + err.Error()
|
||||
} else if strings.Contains(err.Error(), "404") || strings.Contains(err.Error(), "not found") {
|
||||
} else if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "forbidden") {
|
||||
return false, "权限不足,请检查API Key权限:" + errMsg
|
||||
} else if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "not found") {
|
||||
return false, "API端点不存在,请检查Base URL"
|
||||
} else if strings.Contains(err.Error(), "timeout") {
|
||||
} else if strings.Contains(errMsg, "timeout") {
|
||||
return false, "连接超时,请检查网络连接"
|
||||
} else if strings.Contains(errMsg, "status code: 400") {
|
||||
// 400 错误说明 API 端点可达、认证通过,只是请求参数不兼容(如 max_tokens vs max_completion_tokens)
|
||||
// 视为连接成功
|
||||
return true, "连接正常,模型可用"
|
||||
} else {
|
||||
return false, fmt.Sprintf("连接失败: %v", err)
|
||||
}
|
||||
|
||||
+131
-15
@@ -9,6 +9,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/database"
|
||||
@@ -28,14 +29,20 @@ type SystemHandler struct {
|
||||
cfg *config.Config
|
||||
neo4jDriver neo4j.Driver
|
||||
documentReader interfaces.DocumentReader
|
||||
tenantSvc interfaces.TenantService
|
||||
}
|
||||
|
||||
// NewSystemHandler creates a new system handler
|
||||
func NewSystemHandler(cfg *config.Config, neo4jDriver neo4j.Driver, documentReader interfaces.DocumentReader) *SystemHandler {
|
||||
func NewSystemHandler(cfg *config.Config,
|
||||
neo4jDriver neo4j.Driver,
|
||||
documentReader interfaces.DocumentReader,
|
||||
tenantSvc interfaces.TenantService,
|
||||
) *SystemHandler {
|
||||
return &SystemHandler{
|
||||
cfg: cfg,
|
||||
neo4jDriver: neo4jDriver,
|
||||
documentReader: documentReader,
|
||||
tenantSvc: tenantSvc,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,9 +140,6 @@ func (h *SystemHandler) getDocReaderConnInfo() (addr, transport string) {
|
||||
// @Success 200 {object} map[string]interface{} "解析引擎列表"
|
||||
// @Router /system/parser-engines [get]
|
||||
func (h *SystemHandler) ListParserEngines(c *gin.Context) {
|
||||
docreaderAddr, docreaderTransport := h.getDocReaderConnInfo()
|
||||
connected := h.documentReader != nil && h.documentReader.IsConnected()
|
||||
|
||||
var overrides map[string]string
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.ParserEngineConfig != nil {
|
||||
@@ -143,7 +147,9 @@ func (h *SystemHandler) ListParserEngines(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), overrides)
|
||||
reader, docreaderAddr, docreaderTransport := h.resolveDocReader(c.Request.Context(), overrides)
|
||||
connected := reader != nil && reader.IsConnected()
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), reader, overrides)
|
||||
engines := docparser.ListAllEngines(connected, overrides, remoteEngines)
|
||||
c.JSON(200, gin.H{"code": 0, "msg": "success", "data": engines, "docreader_addr": docreaderAddr, "docreader_transport": docreaderTransport, "connected": connected})
|
||||
}
|
||||
@@ -194,7 +200,7 @@ func (h *SystemHandler) ReconnectDocReader(c *gin.Context) {
|
||||
overrides = tenant.ParserEngineConfig.ToOverridesMap()
|
||||
}
|
||||
}
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), overrides)
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), h.documentReader, overrides)
|
||||
engines := docparser.ListAllEngines(true, overrides, remoteEngines)
|
||||
|
||||
_, docreaderTransport := h.getDocReaderConnInfo()
|
||||
@@ -211,28 +217,46 @@ func (h *SystemHandler) ReconnectDocReader(c *gin.Context) {
|
||||
// @Success 200
|
||||
// @Router /system/parser-engines/check [post]
|
||||
func (h *SystemHandler) CheckParserEngines(c *gin.Context) {
|
||||
docreaderAddr, docreaderTransport := h.getDocReaderConnInfo()
|
||||
connected := h.documentReader != nil && h.documentReader.IsConnected()
|
||||
|
||||
var body types.ParserEngineConfig
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(400, gin.H{"code": 1, "msg": "请求体格式错误"})
|
||||
return
|
||||
}
|
||||
overrides := body.ToOverridesMap()
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), overrides)
|
||||
reader, docreaderAddr, docreaderTransport := h.resolveDocReader(c.Request.Context(), overrides)
|
||||
connected := reader != nil && reader.IsConnected()
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), reader, overrides)
|
||||
engines := docparser.ListAllEngines(connected, overrides, remoteEngines)
|
||||
c.JSON(200, gin.H{"code": 0, "msg": "success", "data": engines, "docreader_addr": docreaderAddr, "docreader_transport": docreaderTransport, "connected": connected})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) resolveDocReader(ctx context.Context, overrides map[string]string) (interfaces.DocumentReader, string, string) {
|
||||
if len(overrides) > 0 {
|
||||
if addr := strings.TrimSpace(overrides["docreader_addr"]); addr != "" && service.IsWeKnoraCloudDocReaderAddr(addr) {
|
||||
reader := h.ResolveDocumentReader(ctx, addr)
|
||||
return reader, addr, transportFromDocReaderAddr(addr)
|
||||
}
|
||||
}
|
||||
|
||||
addr, transport := h.getDocReaderConnInfo()
|
||||
return h.documentReader, addr, transport
|
||||
}
|
||||
|
||||
func transportFromDocReaderAddr(addr string) string {
|
||||
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(addr)), "https://") {
|
||||
return "https"
|
||||
}
|
||||
return "http"
|
||||
}
|
||||
|
||||
// fetchRemoteEngines queries the remote docreader for its engine list.
|
||||
// Returns nil on any error (e.g. not connected), letting the caller
|
||||
// fall back to Go's static registry only.
|
||||
func (h *SystemHandler) fetchRemoteEngines(ctx context.Context, overrides map[string]string) []types.ParserEngineInfo {
|
||||
if h.documentReader == nil || !h.documentReader.IsConnected() {
|
||||
func (h *SystemHandler) fetchRemoteEngines(ctx context.Context, reader interfaces.DocumentReader, overrides map[string]string) []types.ParserEngineInfo {
|
||||
if reader == nil || !reader.IsConnected() {
|
||||
return nil
|
||||
}
|
||||
engines, err := h.documentReader.ListEngines(ctx, overrides)
|
||||
engines, err := reader.ListEngines(ctx, overrides)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch remote engines from docreader: %v", err)
|
||||
return nil
|
||||
@@ -372,6 +396,17 @@ func (h *SystemHandler) isTOSConfigured(c *gin.Context) bool {
|
||||
return h.isTOSEnvAvailable()
|
||||
}
|
||||
|
||||
// isOSSConfigured checks whether OSS connection info is available from tenant config.
|
||||
func (h *SystemHandler) isOSSConfigured(c *gin.Context) bool {
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.OSS != nil {
|
||||
ossConf := tenant.StorageEngineConfig.OSS
|
||||
return ossConf.Endpoint != "" && ossConf.Region != "" && ossConf.AccessKey != "" && ossConf.SecretKey != "" && ossConf.BucketName != ""
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isTOSEnvAvailable checks whether TOS env vars are set.
|
||||
func (h *SystemHandler) isTOSEnvAvailable() bool {
|
||||
return os.Getenv("TOS_ENDPOINT") != "" &&
|
||||
@@ -418,11 +453,13 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) {
|
||||
minioEnvAvailable := h.isMinioEnvAvailable()
|
||||
cosConfigured := h.isCOSConfigured(c)
|
||||
tosConfigured := h.isTOSConfigured(c)
|
||||
ossConfigured := h.isOSSConfigured(c)
|
||||
engines := []StorageEngineStatusItem{
|
||||
{Name: "local", Available: true, Description: "本地文件系统存储,仅适合单机部署"},
|
||||
{Name: "minio", Available: minioConfigured || minioEnvAvailable, Description: "S3 兼容的自托管对象存储,适合内网和私有云部署"},
|
||||
{Name: "cos", Available: cosConfigured, Description: "腾讯云对象存储服务,适合公有云部署,支持 CDN 加速"},
|
||||
{Name: "tos", Available: tosConfigured, Description: "火山引擎对象存储服务,适合公有云部署"},
|
||||
{Name: "oss", Available: ossConfigured, Description: "阿里云对象存储服务,适合公有云部署,支持 S3 兼容协议"},
|
||||
}
|
||||
c.JSON(200, gin.H{
|
||||
"code": 0,
|
||||
@@ -616,6 +653,9 @@ func hasGetObjectAction(action interface{}) bool {
|
||||
// cosFieldPattern validates COS region and bucket name format to prevent URL injection.
|
||||
var cosFieldPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)
|
||||
|
||||
// ossFieldPattern validates OSS region and bucket name format to prevent URL injection.
|
||||
var ossFieldPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)
|
||||
|
||||
// sanitizeStorageCheckError converts a raw storage connectivity error into a safe
|
||||
// user-facing message that does not leak internal network details (hostnames, IPs, ports).
|
||||
func sanitizeStorageCheckError(err error) string {
|
||||
@@ -703,11 +743,12 @@ func isBlockedStorageEndpoint(endpoint string) (bool, string) {
|
||||
|
||||
// StorageCheckRequest is the body for POST /system/storage-engine-check.
|
||||
type StorageCheckRequest struct {
|
||||
Provider string `json:"provider"` // "minio", "cos", "tos", or "s3"
|
||||
Provider string `json:"provider"` // "minio", "cos", "tos", "s3", "oss"
|
||||
MinIO *types.MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *types.COSEngineConfig `json:"cos,omitempty"`
|
||||
TOS *types.TOSEngineConfig `json:"tos,omitempty"`
|
||||
S3 *types.S3EngineConfig `json:"s3,omitempty"`
|
||||
OSS *types.OSSEngineConfig `json:"oss,omitempty"`
|
||||
}
|
||||
|
||||
// StorageCheckResponse is the response for a single-engine connectivity check.
|
||||
@@ -744,6 +785,8 @@ func (h *SystemHandler) CheckStorageEngine(c *gin.Context) {
|
||||
h.checkTOS(c, ctx, req.TOS)
|
||||
case "s3":
|
||||
h.checkS3(c, ctx, req.S3)
|
||||
case "oss":
|
||||
h.checkOSS(c, ctx, req.OSS)
|
||||
default:
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: "本地存储无需检测"}})
|
||||
}
|
||||
@@ -768,7 +811,7 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ
|
||||
|
||||
if cfg.Mode == "remote" {
|
||||
if blocked, reason := isBlockedStorageEndpoint(endpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection", "endpoint", endpoint)
|
||||
logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection endpoint=%s", endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
@@ -935,3 +978,76 @@ func (h *SystemHandler) checkS3(c *gin.Context, ctx context.Context, cfg *types.
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types.OSSEngineConfig) {
|
||||
if cfg == nil {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "未提供 OSS 配置"}})
|
||||
return
|
||||
}
|
||||
|
||||
endpoint, accessKey, secretKey := cfg.Endpoint, cfg.AccessKey, cfg.SecretKey
|
||||
if endpoint == "" || accessKey == "" || secretKey == "" || cfg.BucketName == "" {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Endpoint、Access Key、Secret Key、Bucket Name 不能为空"}})
|
||||
return
|
||||
}
|
||||
|
||||
// Strip URL scheme before SSRF check — OSS endpoint may include http:// or https://
|
||||
ssrfEndpoint := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")
|
||||
if blocked, reason := isBlockedStorageEndpoint(ssrfEndpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection", "endpoint", endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
if !ossFieldPattern.MatchString(cfg.Region) {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Region 格式不正确,仅允许字母、数字、点、连字符"}})
|
||||
return
|
||||
}
|
||||
if !ossFieldPattern.MatchString(cfg.BucketName) {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Bucket 名称格式不正确,仅允许字母、数字、点、连字符"}})
|
||||
return
|
||||
}
|
||||
|
||||
err := file.CheckOssConnectivity(ctx, endpoint, cfg.Region, accessKey, secretKey, cfg.BucketName)
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "AccessDenied") {
|
||||
logger.Errorf(ctx, "Storage check: OSS auth failed", "endpoint", endpoint, "bucket", cfg.BucketName)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Access Key / Secret Key 是否正确"}})
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "NoSuchBucket") {
|
||||
logger.Errorf(ctx, "Storage check: OSS bucket not found", "bucket", cfg.BucketName)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
logger.Errorf(ctx, "Storage check: OSS connectivity failed", "endpoint", endpoint, "bucket", cfg.BucketName, "error", err)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("OSS 连通性检测失败: %s", sanitizeStorageCheckError(err))}})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) ResolveDocumentReader(ctx context.Context, addr string) interfaces.DocumentReader {
|
||||
if addr == "" {
|
||||
return h.documentReader
|
||||
}
|
||||
|
||||
if service.IsWeKnoraCloudDocReaderAddr(addr) {
|
||||
creds := h.tenantSvc.GetDocreaderCredentials(ctx)
|
||||
if creds == nil {
|
||||
return nil
|
||||
}
|
||||
reader, err := docparser.NewWeKnoraCloudSignedDocumentReader(addr, creds.AppID, creds.APIKey)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return reader
|
||||
}
|
||||
|
||||
reader, err := docparser.NewHTTPDocumentReader(addr)
|
||||
if err != nil || reader == nil {
|
||||
return reader
|
||||
}
|
||||
return reader
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im/wechat"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// qrCodeService is a singleton for WeChat QR code operations.
|
||||
var qrCodeService = wechat.NewQRCodeService()
|
||||
|
||||
// WeChatGetQRCode generates a QR code for WeChat login.
|
||||
// POST /api/v1/wechat/qrcode
|
||||
func (h *IMHandler) WeChatGetQRCode(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
result, err := qrCodeService.GetLoginQRCode(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[WeChat] Failed to generate QR code: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate QR code: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"qrcode_url": result.QRCodeURL,
|
||||
"qrcode": result.QRCode,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// WeChatPollQRCodeStatus checks the scan status of a WeChat QR code.
|
||||
// POST /api/v1/wechat/qrcode/status
|
||||
func (h *IMHandler) WeChatPollQRCodeStatus(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var req struct {
|
||||
QRCode string `json:"qrcode" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "qrcode is required"})
|
||||
return
|
||||
}
|
||||
|
||||
result, err := qrCodeService.PollQRCodeStatus(ctx, req.QRCode)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[WeChat] Failed to poll QR code status: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to check QR code status"})
|
||||
return
|
||||
}
|
||||
|
||||
resp := gin.H{
|
||||
"status": result.Status,
|
||||
}
|
||||
|
||||
// Only include credentials when login is confirmed
|
||||
if result.Status == "confirmed" {
|
||||
resp["credentials"] = gin.H{
|
||||
"bot_token": result.BotToken,
|
||||
"ilink_bot_id": result.ILinkBotID,
|
||||
"ilink_user_id": result.ILinkUserID,
|
||||
}
|
||||
// Include baseurl if the server returned one (may override default)
|
||||
if result.BaseURL != "" {
|
||||
resp["baseurl"] = result.BaseURL
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": resp})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// WeKnoraCloudHandler 处理 WeKnoraCloud 初始化请求
|
||||
type WeKnoraCloudHandler struct {
|
||||
svc interfaces.WeKnoraCloudService
|
||||
}
|
||||
|
||||
// NewWeKnoraCloudHandler 构造函数
|
||||
func NewWeKnoraCloudHandler(svc interfaces.WeKnoraCloudService) *WeKnoraCloudHandler {
|
||||
return &WeKnoraCloudHandler{svc: svc}
|
||||
}
|
||||
|
||||
type initializeWeKnoraCloudRequest struct {
|
||||
AppID string `json:"app_id" binding:"required"`
|
||||
AppSecret string `json:"app_secret" binding:"required"`
|
||||
}
|
||||
|
||||
// Initialize POST /api/v1/models/weknoracloud/initialize
|
||||
func (h *WeKnoraCloudHandler) Initialize(c *gin.Context) {
|
||||
var req initializeWeKnoraCloudRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.svc.Initialize(c.Request.Context(), req.AppID, req.AppSecret)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
|
||||
// Status GET /api/v1/models/weknoracloud/status
|
||||
// 检查当前租户的 WeKnoraCloud 凭证是否完好,如需重新初始化则返回 needs_reinit=true
|
||||
func (h *WeKnoraCloudHandler) Status(c *gin.Context) {
|
||||
result, err := h.svc.CheckStatus(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
Reference in New Issue
Block a user