- 在客户端添加首页路由的认证逻辑,提高用户体验 - 优化静态资源服务配置,增强安全性 - 添加 URL 解析和保存功能,为后续的路由认证做准备 - 调整中间件顺序和配置,提升应用性能和安全性
72 lines
1.6 KiB
Go
72 lines
1.6 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 {
|
|
// 检查是否在受保护列表中
|
|
for _, protectedURL := range protectedURLs {
|
|
if requestPath == 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()
|
|
}
|
|
}
|