package middleware import ( "fmt" "github.com/gin-gonic/gin" "iot_manager_service/app/file/dao" dao2 "iot_manager_service/app/user/dao" "iot_manager_service/util/common" "iot_manager_service/util/token" "net/http" "strconv" "strings" "time" ) // 校验用户对文件的权限 func CheckAuth() gin.HandlerFunc { return func(c *gin.Context) { header := c.GetHeader("Authorization") claims, _ := token.JwtClaims.ParseJwtToken(header) userdao := dao2.SysUser{} id, _ := strconv.Atoi(claims.ID) nowSysUser, err2 := userdao.GetNowSysUser(id) if err2 != nil { panic(err2) } fileid := c.Query("fileId") filedao := &dao.File{} fileInfo, err := filedao.GetFileInfo(fileid, claims.ID) if err != nil { c.JSON(http.StatusOK, err) c.Abort() return } // 将时间字符串解析为时间对象 targetTime, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", fileInfo.EffectiveDate.String()) now := time.Now() // 比较两个时间 if !now.Before(targetTime) { c.JSON(http.StatusForbidden, common.StatusForbidden("访问时间已过,无权访问", nil)) c.Abort() return } userAuth := nowSysUser.AuthId fileAuth := fileInfo.AuthId var permissionMap = map[string]struct { index string message string }{ "/viewFile": {"1", "查看"}, "/downloadFile": {"2", "下载"}, "/forwardingFile": {"3", "转发"}, } for url, obj := range permissionMap { if strings.Contains(c.Request.RequestURI, url) { if !strings.Contains(fileAuth, obj.index) { c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("抱歉,该文件不支持【%s】操作,请联系管理员。", obj.message), nil)) c.Abort() return } if !strings.Contains(userAuth, obj.index) { c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("抱歉,您没有对文件的【%s】权限,请联系管理员。", obj.message), nil)) c.Abort() return } } } c.Next() } }