package router import ( "ArmedPolice/app/service" "ArmedPolice/config" cache2 "ArmedPolice/serve/cache" "ArmedPolice/utils" "fmt" "net/http" "time" "github.com/gin-gonic/gin" ) // SkipperURL 跳过验证 type SkipperURL func(*gin.Context) bool // PermissionHandle 权限验证 type PermissionHandle func(key string) gin.HandlerFunc // AddSkipperURL 添加路由 func AddSkipperURL(url ...string) SkipperURL { return func(c *gin.Context) bool { path := c.Request.URL.Path return utils.InArray(path, url) } } // NeedLogin 需要登录 func NeedLogin(skipperURL ...SkipperURL) gin.HandlerFunc { return func(c *gin.Context) { if len(skipperURL) > 0 && skipperURL[0](c) { c.Next() return } token := c.GetHeader(config.APIRequestToken) if token == "" { c.JSON(http.StatusUnauthorized, gin.H{"message": "Token异常"}) c.Abort() return } tokenInfo := utils.JWTDecrypt(token) if tokenInfo == nil || len(tokenInfo) <= 0 { c.JSON(http.StatusUnauthorized, gin.H{"message": "Token无效"}) c.Abort() return } expTimestamp := utils.StringToInt64(fmt.Sprintf("%v", tokenInfo["exp"])) expTime := time.Unix(expTimestamp, 0) ok := expTime.After(time.Now()) if !ok { c.JSON(http.StatusUnauthorized, gin.H{"message": "Token过期"}) c.Abort() return } cache, _ := cache2.Cache.HGet(config.RedisKeyForAccount, fmt.Sprintf("%v", tokenInfo[config.TokenForUID])) if cache == "" { c.JSON(http.StatusUnauthorized, gin.H{"message": "用户未登录或已退出"}) c.Abort() return } session := new(service.Session) _ = session.UnmarshalBinary([]byte(cache)) if !config.SettingInfo.MultipleLogin && session.Token != token { c.JSON(http.StatusUnauthorized, gin.H{"message": "登录失效,已在其他地方登录!"}) c.Abort() return } c.Set(config.TokenForSession, session) c.Next() } } // NeedPermission 需要权限验证 func NeedPermission(skipperURL ...SkipperURL) PermissionHandle { return func(key string) gin.HandlerFunc { return func(c *gin.Context) { if len(skipperURL) > 0 && skipperURL[0](c) { c.Next() return } //session, _ := c.Get(config.TokenForSession) //_session := session.(*service.Session) //if pass, _ := service.NewPermission(nil, &service.AuthRequest{ // Url: key, // Method: c.Request.Method, //})(_session.TenantKey, fmt.Sprintf("%d", _session.UID)).Enforce(); !pass { // c.JSON(http.StatusOK, gin.H{"code": http.StatusForbidden, "msg": "无权限访问!"}) // c.Abort() // return //} c.Next() } } }