- 移除了 PostLogin 中的 URL 解码步骤,直接使用 returnURL - 在 StaticAuthMiddleware 中增加了 URL 解码,以确保准确匹配受保护 URL - 优化了错误处理,提高了代码的健壮性
77 lines
1.7 KiB
Go
77 lines
1.7 KiB
Go
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()
|
|
}
|
|
}
|