- 新增 getUserInfo 辅助函数以获取用户信息 - 更新 ServeIndex 和 ServeStatic 函数以使用数据库参数 - 修改 LogAccess 函数以记录用户信息 - 优化 AuthRequired 中间件,对登出操作进行特殊处理
57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
|
|
"gateway/models"
|
|
"gateway/utils"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/jinzhu/gorm"
|
|
)
|
|
|
|
// 获取用户信息的辅助函数
|
|
func getUserInfo(c *gin.Context, db *gorm.DB) map[string]interface{} {
|
|
session := sessions.Default(c)
|
|
userID := session.Get("user")
|
|
if userID == nil {
|
|
return nil
|
|
}
|
|
|
|
var user models.User
|
|
if err := db.Preload("Region").First(&user, userID).Error; err != nil {
|
|
return nil
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"user_id": user.ID,
|
|
"full_name": user.FullName,
|
|
"region": user.Region.Name,
|
|
}
|
|
}
|
|
|
|
// 处理首页请求
|
|
func ServeIndex(db *gorm.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
userInfo := getUserInfo(c, db)
|
|
utils.LogAccess(c.ClientIP(), c.Request.URL.Path, c.Request.Method, userInfo)
|
|
http.ServeFile(c.Writer, c.Request, "./static/index.html")
|
|
}
|
|
}
|
|
|
|
// 处理静态文件请求
|
|
func ServeStatic(db *gorm.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
userInfo := getUserInfo(c, db)
|
|
utils.LogAccess(c.ClientIP(), c.Request.URL.Path, c.Request.Method, userInfo)
|
|
filePath := "./static" + c.Request.URL.Path
|
|
if _, err := os.Stat(filePath); err == nil {
|
|
http.ServeFile(c.Writer, c.Request, filePath)
|
|
} else {
|
|
c.AbortWithStatus(http.StatusNotFound)
|
|
}
|
|
}
|
|
}
|