package middleware import ( "gateway/config" "net/url" "path/filepath" "strings" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) func StaticAuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // 获取受保护的URL列表 protectedURLs, err := config.GetProtectedURLs() if err != nil { c.AbortWithStatus(500) return } // 检查当前请求路径是否在受保护列表中 requestPath := c.Request.URL.Path // 如果是登录相关的资源,直接放行 if strings.Contains(c.Request.Referer(), "/login") || strings.Contains(c.Request.Referer(), "/register") { c.Next() return } // 检查是否是静态资源 if strings.HasPrefix(requestPath, "/") { needAuth := false // 检查是否是HTML文件 if filepath.Ext(requestPath) == ".html" { needAuth = true } else { // 检查是否在受保护列表中 decodedPath, err := url.QueryUnescape(requestPath) if err != nil { c.AbortWithStatus(400) return } for _, protectedURL := range protectedURLs { if decodedPath == protectedURL { needAuth = true break } } } // 如果需要认证,检查用户是否已登录 if needAuth { session := sessions.Default(c) user := session.Get("user") if user == nil { if filepath.Ext(requestPath) == ".html" { // HTML 文件重定向到登录页面 returnURL := c.Request.URL.String() encodedURL := url.QueryEscape(returnURL) c.Redirect(302, "/login?return_url="+encodedURL) } else { // 非 HTML 文件返回 401 未授权状态码 c.AbortWithStatus(401) } c.Abort() return } } } c.Next() } }