瀏覽代碼

last优化

chengqian 9 月之前
父節點
當前提交
6f7a7cfb29

+ 101 - 15
app/file/controller/file.go

@@ -1,10 +1,12 @@
 package controller
 
 import (
+	"fmt"
 	"github.com/gin-gonic/gin"
 	"iot_manager_service/app/file/dao"
 	"iot_manager_service/app/file/model"
 	"iot_manager_service/app/file/service"
+	dao2 "iot_manager_service/app/user/dao"
 	"iot_manager_service/util/cache"
 	"iot_manager_service/util/common"
 	"iot_manager_service/util/token"
@@ -24,7 +26,14 @@ type file struct{}
 func (f *file) Upload(c *gin.Context) {
 	header := c.GetHeader("Authorization")
 	claims, _ := token.JwtClaims.ParseJwtToken(header)
-	nowSysUser, _ := cache.GetNowSysUser(claims.ID)
+	uploader, _ := strconv.Atoi(claims.ID)
+
+	//校验权限 -- 4代表上传权限
+	authUpload := CheckUserAuth(uploader, "4")
+	if !authUpload {
+		c.JSON(http.StatusForbidden, common.StatusForbidden("您没有上传权限,请联系管理员。", nil))
+		return
+	}
 
 	// 获取表单字段的值
 	categoryName := c.PostForm("categoryName")
@@ -66,7 +75,7 @@ func (f *file) Upload(c *gin.Context) {
 		AuthId:        authId,
 		SuffixName:    path.Ext(formFile.Filename),
 		UploadTime:    &currentTimeValue,
-		Uploader:      int(nowSysUser.ID),
+		Uploader:      uploader,
 		Icon:          strings.TrimPrefix(path.Ext(formFile.Filename), ".") + ".png",
 		Iv:            iv,
 	})
@@ -107,36 +116,113 @@ func (f *file) GetSysUserFiles(c *gin.Context) {
 
 // 转发文件
 func (f *file) ForwardingFile(c *gin.Context) {
-	fileid := c.Query("fileId")
 	header := c.GetHeader("Authorization")
 	claims, _ := token.JwtClaims.ParseJwtToken(header)
+	uid, _ := strconv.Atoi(claims.ID)
 
 	requsers := model.ReqSysUsers{}
-	if err := c.ShouldBindJSON(&requsers); err != nil {
+	if err := c.ShouldBind(&requsers); err != nil {
 		c.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
 		return
 	}
-	uid, _ := strconv.Atoi(claims.ID)
-	fid, _ := strconv.Atoi(fileid)
-	forwardingFile := service.FileService.ForwardingFile(uid, fid, requsers.SysUsersId)
+
+	authView := CheckUserAuth(uid, "3")
+	if !authView {
+		c.JSON(http.StatusForbidden, common.StatusForbidden("您没有【转发】权限,请联系管理员。", nil))
+		return
+	}
+
+	for _, fid := range requsers.FilesId {
+		auth, time, name := CheckFileAuth(uid, fid, "3")
+		if time {
+			c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("文件【%s】操作时间已过,无权操作。", name), nil))
+			return
+		}
+		if auth {
+			c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("文件【%s】不支持转发操作,请联系管理员。", name), nil))
+			return
+		}
+	}
+
+	forwardingFile := service.FileService.ForwardingFile(uid, requsers.FilesId, requsers.SysUsersId)
 	c.JSON(http.StatusOK, forwardingFile)
 }
 
-func (f *file) GetMyUploadFiles(c *gin.Context) {
+// 查看文件
+func (f *file) ViewFile(c *gin.Context) {
+	//校验权限
 	header := c.GetHeader("Authorization")
 	claims, _ := token.JwtClaims.ParseJwtToken(header)
-	files := service.FileService.GetMyUploadFiles(claims.ID)
-	c.JSON(http.StatusOK, files)
-}
+	uid, _ := strconv.Atoi(claims.ID)
+
+	authView := CheckUserAuth(uid, "1")
+	if !authView {
+		c.JSON(http.StatusForbidden, common.StatusForbidden("您没有【查看】权限,请联系管理员。", nil))
+		return
+	}
 
-// 查看文件
-func (f *file) ViewFile(c *gin.Context) {
 	fileId := c.Query("fileId")
+	fid, _ := strconv.Atoi(fileId)
+	auth, time, name := CheckFileAuth(uid, fid, "1")
+	if time {
+		c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("文件【%s】操作时间已过,无权操作。", name), nil))
+		return
+	}
+	if auth {
+		c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("文件【%s】不支持查看操作,请联系管理员。", name), nil))
+		return
+	}
 	service.FileService.GetFile(fileId, c)
 }
 
 // 下载文件
 func (f *file) DownloadFile(c *gin.Context) {
-	fileid := c.Query("fileId")
-	service.FileService.GetFile(fileid, c)
+	//校验权限
+	header := c.GetHeader("Authorization")
+	claims, _ := token.JwtClaims.ParseJwtToken(header)
+	uid, _ := strconv.Atoi(claims.ID)
+
+	authView := CheckUserAuth(uid, "2")
+	if !authView {
+		c.JSON(http.StatusForbidden, common.StatusForbidden("您没有【下载】权限,请联系管理员。", nil))
+		return
+	}
+
+	fileId := c.Query("fileId")
+	fid, _ := strconv.Atoi(fileId)
+	auth, time, name := CheckFileAuth(uid, fid, "2")
+	if time {
+		c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("文件【%s】操作时间已过,无权操作。", name), nil))
+		return
+	}
+	if auth {
+		c.JSON(http.StatusForbidden, common.StatusForbidden(fmt.Sprintf("文件【%s】不支持下载操作,请联系管理员。", name), nil))
+		return
+	}
+	service.FileService.GetFile(fileId, c)
+}
+
+func (f *file) GetMyUploadFiles(c *gin.Context) {
+	header := c.GetHeader("Authorization")
+	claims, _ := token.JwtClaims.ParseJwtToken(header)
+	files := service.FileService.GetMyUploadFiles(claims.ID)
+	c.JSON(http.StatusOK, files)
+}
+
+func CheckUserAuth(uid int, authstr string) bool {
+	userdao := dao2.SysUser{}
+	user, _ := userdao.GetNowSysUser(uid)
+	if !strings.Contains(user.AuthId, authstr) {
+		return false
+	}
+	return true
+}
+
+func CheckFileAuth(uid, fileid int, authstr string) (bool, bool, string) {
+	filedao := &dao.File{}
+	fileInfo, _ := filedao.GetFileInfo(fileid, uid)
+
+	targetTime, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", fileInfo.EffectiveDate.String())
+	now := time.Now()
+	return !strings.Contains(fileInfo.AuthId, authstr), !now.Before(targetTime), fileInfo.OriginalName
 }

+ 9 - 4
app/file/dao/file.go

@@ -39,7 +39,7 @@ func (f *File) GetSysUserFiles(uid int, search model.SearchSysUserFiles) ([]File
 	db := Db.Table("file").
 		Select("file.*").
 		Joins("left join user_file uf on uf.file_id = file.id").
-		Where("uf.receiver = ? AND file.is_showed = 0 AND file.is_deleted = 0 AND uf.is_deleted = 0 AND uf.operation_status = '下发'", uid). // 根据upload_time字段降序排列
+		Where("uf.receiver = ? AND file.is_showed = 0 AND file.is_deleted = 0 AND uf.is_deleted = 0 AND uf.operation_status = '下发' OR uf.operation_status = '转发'", uid). // 根据upload_time字段降序排列
 		Group("file.id")
 
 	if search.OriginalName != "" {
@@ -63,12 +63,17 @@ func (f *File) GetSysUserFiles(uid int, search model.SearchSysUserFiles) ([]File
 	return files, err
 }
 
-func (f *File) GetFileInfo(fileid, uid string) (model.RespFileInfo, error) {
+func (f *File) GetFileInfo(fileid, uid int) (model.RespFileInfo, error) {
 	var result map[string]interface{}
-	Db.Raw("SELECT file.auth_id, uf.effective_date FROM file LEFT JOIN user_file uf ON uf.file_id = file.id WHERE uf.file_id = ? AND uf.operation_status = '下发' AND uf.receiver = ? ORDER BY uf.effective_date DESC LIMIT 1", fileid, uid).Scan(&result)
+	query := `SELECT file.original_name, file.auth_id, uf.effective_date FROM 
+            file LEFT JOIN user_file uf ON uf.file_id = file.id WHERE uf.file_id = ?  
+                        AND uf.receiver = ? ORDER BY uf.effective_date DESC LIMIT 1`
+	Db.Raw(query, fileid, uid).Scan(&result)
 	authId, _ := result["auth_id"].(string)
+	originalName, _ := result["original_name"].(string)
 	effectiveDate, _ := result["effective_date"].(time.Time)
-	return model.RespFileInfo{AuthId: authId, EffectiveDate: effectiveDate}, nil
+
+	return model.RespFileInfo{AuthId: authId, OriginalName: originalName, EffectiveDate: effectiveDate}, nil
 }
 
 func (f *File) GetFile(id string) (*File, error) {

+ 3 - 1
app/file/model/file.go

@@ -11,7 +11,8 @@ type ReqSysUserFile struct {
 }
 
 type ReqSysUsers struct {
-	SysUsersId []int `json:"users"` //转发的用户id
+	SysUsersId []int `json:"users"`   //转发的用户id
+	FilesId    []int `json:"filesId"` //转发的用户id
 }
 
 type SearchSysUserFiles struct {
@@ -24,5 +25,6 @@ type SearchSysUserFiles struct {
 
 type RespFileInfo struct {
 	AuthId        string    `json:"authId"`                             //权限id
+	OriginalName  string    `json:"originalName"`                       //权限id
 	EffectiveDate time.Time `json:"effectiveDate" gorm:"effectiveDate"` //阅读的有效日期
 }

+ 17 - 11
app/file/service/fileService.go

@@ -94,23 +94,29 @@ func (f *fileService) GetMyUploadFiles(id string) *common.Errors {
 }
 
 // 转发
-func (f *fileService) ForwardingFile(uid, fileid int, users []int) *common.Errors {
+func (f *fileService) ForwardingFile(uid int, filesid []int, users []int) *common.Errors {
 	var userfile []dao.SysUserFile
-	var nilTime *time.Time
-	for _, u := range users {
-		userfile = append(userfile, dao.SysUserFile{
-			Operator:        uid,
-			Receiver:        u,
-			FileID:          fileid,
-			EffectiveDate:   nilTime,
-			OperationStatus: "转发",
-		})
+	currentTime := time.Now()
+	//对于转发的文件,三天后过期
+	after := currentTime.AddDate(0, 0, 3)
+	for _, fid := range filesid {
+		for _, u := range users {
+			userfile = append(userfile, dao.SysUserFile{
+				Operator:        uid,
+				Receiver:        u,
+				FileID:          fid,
+				EffectiveDate:   &after,
+				OperationStatus: "转发",
+			})
+		}
 	}
 	userfiledao := &dao.SysUserFile{}
 	err := userfiledao.BatchUFRecords(userfile)
 	if err != nil {
 		return common.FailResponse(err.Error(), nil)
-
+	}
+	for _, u := range users {
+		websocket.SendMessage(strconv.Itoa(u), "您有新的文件,请注意查收!")
 	}
 	return common.SuccessResponse("新增记录成功", nil)
 }

+ 0 - 82
app/middleware/checkAuth.go

@@ -1,82 +0,0 @@
-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)
-		}
-		userAuth := nowSysUser.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) {
-				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
-				}
-
-				fileAuth := fileInfo.AuthId
-				// 将时间字符串解析为时间对象
-				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
-				}
-
-				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
-				}
-			}
-		}
-
-		if strings.Contains(c.Request.RequestURI, "/upload") && !strings.Contains(userAuth, "4") {
-			c.JSON(http.StatusForbidden, common.StatusForbidden("您没有上传权限,请联系管理员。", nil))
-			c.Abort()
-			return
-		}
-		c.Next()
-	}
-}

+ 2 - 2
app/user/controller/user.go

@@ -61,8 +61,8 @@ func (u *user) GetNewTokens(c *gin.Context) {
 	claims, _ := token.JwtClaims.ParseJwtToken(header)
 	nowSysUser, _ := cache.GetNowSysUser(claims.ID)
 
-	accessToken, _ := token.JwtClaims.CreateJwtToken(strconv.Itoa(nowSysUser.ID), nowSysUser.Username, nowSysUser.UUID, 1)
-	refreshToken, _ := token.JwtClaims.CreateJwtToken(strconv.Itoa(nowSysUser.ID), nowSysUser.Username, nowSysUser.UUID, 24*7)
+	accessToken, _ := token.JwtClaims.CreateJwtToken(claims.ID, nowSysUser.Username, nowSysUser.UUID, 1)
+	refreshToken, _ := token.JwtClaims.CreateJwtToken(claims.ID, nowSysUser.Username, nowSysUser.UUID, 24*7)
 	tokens := make(map[string]interface{})
 
 	tokens["accessToken"] = accessToken

+ 1 - 1
app/user/service/userService.go

@@ -48,7 +48,7 @@ func (s *userService) Login(username string, pwd string) *common.Errors {
 	tokens["refreshToken"] = refreshToken
 
 	//TODO:到时候记得修改服务器域名
-	urlWebSocket := "ws://localhost:8085/notice/webSocket?userID=" + USERID
+	urlWebSocket := "ws://106.52.134.22:8890/notice/websocket?userID=" + USERID
 	return common.SuccessResponse("登录成功", gin.H{"token": tokens, "websocket": urlWebSocket})
 }
 

+ 4 - 4
router/router.go

@@ -40,10 +40,10 @@ func InitRouter(engine *gin.Engine) {
 		files.POST("/distribute", file.FileController.Distribute)
 		files.GET("/getMyUpload", file.FileController.GetMyUploadFiles)
 		files.POST("/getUserFiles", file.FileController.GetSysUserFiles)
-		files.POST("/upload", middleware.CheckAuth(), file.FileController.Upload)
-		files.GET("/viewFile", middleware.CheckAuth(), file.FileController.ViewFile)
-		files.GET("/downloadFile", middleware.CheckAuth(), file.FileController.DownloadFile)
-		files.POST("/forwardingFile", middleware.CheckAuth(), file.FileController.ForwardingFile)
+		files.POST("/upload", file.FileController.Upload)
+		files.GET("/viewFile", file.FileController.ViewFile)
+		files.GET("/downloadFile", file.FileController.DownloadFile)
+		files.POST("/forwardingFile", file.FileController.ForwardingFile)
 
 	}