package app import ( "recook/internal/back" "recook/internal/cache" "recook/internal/dbc" "recook/internal/model/user" "strconv" "strings" "github.com/gin-gonic/gin" ) /* 令牌校验 中间件拦截 */ func authorize() gin.HandlerFunc { return func(c *gin.Context) { deviceType := cache.GetDeviceType(c) c.Set("deviceType", deviceType) if c.Request.Method == "GET" { c.Next() } else if c.Request.Method == "POST" { path := c.Request.URL.Path if strings.Contains(path, "/login") || strings.Contains(path, "/register") || strings.Contains(path, "/callback") || strings.Contains(path, "callback") || strings.HasPrefix(path, "/api/v1/show") || strings.HasPrefix(path, "/api/v1/cron") || strings.HasPrefix(path, "/api/v1/users/profile") || strings.HasPrefix(path, "/api/v1/users/top") || strings.HasPrefix(path, "/api/v1/goods") || strings.HasPrefix(path, "/api/v1/diamond_show") || strings.HasPrefix(path, "/api/v1/messages") || strings.HasPrefix(path, "/api/v1/attention/list/moment_copy") || strings.HasPrefix(path, "/api/v1/attention/moment_copy/recommend/list") || strings.HasPrefix(path, "/api/v1/application") || strings.HasPrefix(path, "/api/v1/activity") || strings.HasPrefix(path, "/api/v1/diamond_register") || strings.HasPrefix(path, "/api/v1/lives/trend/list") || strings.HasPrefix(path, "/api/v1/lives/trend/info") || strings.HasPrefix(path, "/api/v1/lives/trend/infos") || strings.HasPrefix(path, "/api/v1/lives/trend/goods") || strings.HasPrefix(path, "/api/v1/lives/goods") || strings.HasPrefix(path, "/api/v1/lives/order/liveorderdata") || strings.HasPrefix(path, "/api/v1/lives/user/users") || strings.HasPrefix(path, "/api/v1/region") || strings.HasPrefix(path, "/api/v1/ticket/list") || strings.HasPrefix(path, "/api/v1/ticket/info") || strings.HasPrefix(path, "/api/v1/ticket/history") { c.Next() return } if len(c.Request.Header.Get("X-Recook-ID")) == 0 { back.Fail(c, "游客无法使用该功能,请登录") c.Abort() return } if len(c.Request.Header.Get("X-Recook-Token")) == 0 { back.Fail(c, "游客无法使用该功能,请登录") c.Abort() return } id, err := strconv.Atoi(c.Request.Header.Get("X-Recook-ID")) if id <= 0 || err != nil { back.Fail(c, "游客无法使用该功能,请登录") c.Abort() return } token := c.Request.Header.Get("X-Recook-Token") // 先命中缓存 val := cache.GetUserLoginCache(uint(id), deviceType) if val != token { // 缓存失效查数据库 login := &user.Login{} dbc.DB.First(login, "id=? and device_type = ?", id, val) if login.Token == token { cache.SetUserLoginCache(login) c.Next() } else { back.Unauthorized(c) c.Abort() } } else { c.Request.Header.Set("X-Recook-ID", strconv.Itoa(id)) c.Next() } } else { c.Abort() } } }