2026-04-09 10:01:23 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
2026-08-28 22:23:13 +08:00
|
|
|
"net/url"
|
|
|
|
|
"strings"
|
|
|
|
|
|
2026-08-21 00:41:07 +08:00
|
|
|
"code.tczkiot.com/wlw/ai-agent/internal/pkg/httpx"
|
|
|
|
|
"code.tczkiot.com/wlw/ai-agent/internal/services"
|
2026-04-09 10:01:23 +08:00
|
|
|
|
2026-05-23 22:10:20 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
2026-04-09 10:01:23 +08:00
|
|
|
)
|
|
|
|
|
|
2026-05-23 22:10:20 +08:00
|
|
|
func ExternalUserMiddleware(ctx *gin.Context) {
|
2026-04-28 10:15:15 +08:00
|
|
|
channel := services.ChannelService.GetEnabledChannel(ctx)
|
2026-04-28 10:40:53 +08:00
|
|
|
if channel == nil {
|
2026-08-28 22:23:13 +08:00
|
|
|
httpx.AbortJSON(ctx, 200, httpx.JsonErrorMsg(ctx, "error.e0210"))
|
2026-04-28 10:40:53 +08:00
|
|
|
return
|
2026-04-28 10:15:15 +08:00
|
|
|
}
|
2026-08-28 22:23:13 +08:00
|
|
|
external, err := services.SubjectService.ResolveExternal(
|
|
|
|
|
ctx.Request.Context(),
|
|
|
|
|
requestExternalValue(ctx, "X-External-Id", "external_id"),
|
|
|
|
|
decodeExternalName(requestExternalValue(ctx, "X-External-Name", "external_name")),
|
|
|
|
|
)
|
2026-04-09 10:01:23 +08:00
|
|
|
if err != nil {
|
2026-08-28 22:23:13 +08:00
|
|
|
httpx.AbortJSON(ctx, 200, httpx.JsonErrorMsg(ctx, "error.auth.expired"))
|
2026-04-09 10:01:23 +08:00
|
|
|
return
|
|
|
|
|
}
|
2026-08-21 00:41:07 +08:00
|
|
|
httpx.SetExternalUser(ctx, external)
|
2026-04-09 10:01:23 +08:00
|
|
|
ctx.Next()
|
|
|
|
|
}
|
2026-08-28 22:23:13 +08:00
|
|
|
|
|
|
|
|
func requestExternalValue(ctx *gin.Context, header, query string) string {
|
|
|
|
|
if value := strings.TrimSpace(ctx.GetHeader(header)); value != "" {
|
|
|
|
|
return value
|
|
|
|
|
}
|
|
|
|
|
return strings.TrimSpace(ctx.Query(query))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func decodeExternalName(value string) string {
|
|
|
|
|
decoded, err := url.QueryUnescape(strings.TrimSpace(value))
|
|
|
|
|
if err != nil {
|
|
|
|
|
return strings.TrimSpace(value)
|
|
|
|
|
}
|
|
|
|
|
return strings.TrimSpace(decoded)
|
|
|
|
|
}
|