- 工单编号改为业务格式 TK-yyMMdd-NNN
- 类型断言加 comma-ok 防 panic
- priority 用指针区分未传/P0
- json.Marshal 错误处理
- 提取 ParseID 公共函数消除重复
- HTTP client 包级别复用
- LIKE 查询特殊字符转义
- interface{} → any
- auth 中间件用 dto.Fail 统一响应
76 lines
1.5 KiB
Go
76 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"strconv"
|
|
|
|
"github.com/casehub/ticket-workbench/internal/dto"
|
|
"github.com/casehub/ticket-workbench/internal/model"
|
|
"github.com/casehub/ticket-workbench/internal/service"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func Auth(db *gorm.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
sessionID := extractSessionID(c)
|
|
if sessionID == "" {
|
|
c.JSON(200, dto.Fail("未登录"))
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
user := service.GetUserBySession(sessionID)
|
|
if user == nil {
|
|
c.JSON(200, dto.Fail("登录已过期"))
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("userid", user.Userid)
|
|
c.Set("username", user.Username)
|
|
c.Set("account", user.Account)
|
|
c.Set("role", user.Role)
|
|
c.Set("team", user.Team)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func extractSessionID(c *gin.Context) string {
|
|
if s := c.GetHeader("Authorization"); s != "" {
|
|
return s
|
|
}
|
|
if s := c.GetHeader("jsessionid"); s != "" {
|
|
return s
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func GetCurrentUser(c *gin.Context) *model.TicketUser {
|
|
uid, ok := c.Get("userid")
|
|
if !ok {
|
|
return nil
|
|
}
|
|
userid, ok := uid.(int)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
username, _ := c.Get("username")
|
|
role, _ := c.Get("role")
|
|
team, _ := c.Get("team")
|
|
return &model.TicketUser{
|
|
Userid: userid,
|
|
Username: username.(string),
|
|
Role: role.(int16),
|
|
Team: team.(string),
|
|
}
|
|
}
|
|
|
|
func ParseID(c *gin.Context) (int, bool) {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
c.JSON(200, dto.Fail("参数错误"))
|
|
return 0, false
|
|
}
|
|
return id, true
|
|
}
|