feat(storage): implement user-group level file management dashboard and APIs

- Expose user-scoped CRUD APIs under `/api/v1/upload` (my files query, stats, rename, delete)
- Update backend handlers and routers with ownership validation checks
- Create a dedicated frontend personal file manager card-list and upload button under `/files`
- Add comprehensive backend test coverage and update API docs
This commit is contained in:
ryan
2026-06-13 16:14:22 +08:00
parent 8b19ffed90
commit 5b13d5b464
13 changed files with 1421 additions and 21 deletions
+198
View File
@@ -10,6 +10,7 @@ import (
"strconv"
"strings"
"github.com/Rain-kl/Wavelet/internal/apps/oauth"
"github.com/Rain-kl/Wavelet/internal/db"
"github.com/Rain-kl/Wavelet/internal/model"
"github.com/Rain-kl/Wavelet/internal/util"
@@ -164,3 +165,200 @@ func GetDistinctUploadTypes(c *gin.Context) {
sort.Strings(dbTypes)
c.JSON(http.StatusOK, util.OK(dbTypes))
}
type listMyFilesRequest struct {
Page int `form:"page"`
PageSize int `form:"page_size"`
Keyword string `form:"keyword"`
Type string `form:"type"`
Extension string `form:"extension"`
}
type listMyFilesResponse struct {
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
Items []model.Upload `json:"items"`
}
// ListMyFiles 获取当前用户上传的文件列表
// @Summary 获取我的文件列表
// @Description 分页获取当前登录用户上传的文件,支持文件名关键词、业务类型、扩展名过滤
// @Tags upload
// @Produce json
// @Param page query int false "页码(默认 1)"
// @Param page_size query int false "每页数量(默认 20,最大 100)"
// @Param keyword query string false "文件名关键词(模糊匹配)"
// @Param type query string false "业务分类过滤"
// @Param extension query string false "扩展名过滤"
// @Security SessionCookie
// @Success 200 {object} util.ResponseAny{data=listMyFilesResponse} "查询成功"
// @Failure 401 {object} util.ResponseAny "未登录"
// @Router /api/v1/upload/my [get]
func ListMyFiles(c *gin.Context) {
currUser, _ := util.GetFromContext[*model.User](c, oauth.UserObjKey)
ctx := c.Request.Context()
var req listMyFilesRequest
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusOK, util.Err(ErrInvalidParams))
return
}
if req.Page <= 0 {
req.Page = 1
}
if req.PageSize <= 0 || req.PageSize > 100 {
req.PageSize = 20
}
query := db.DB(ctx).Model(&model.Upload{}).
Where("user_id = ? AND status != ?", currUser.ID, model.UploadStatusDeleted)
if req.Keyword != "" {
query = query.Where("LOWER(file_name) LIKE ?", "%"+strings.ToLower(req.Keyword)+"%")
}
if req.Type != "" {
query = query.Where("type = ?", req.Type)
}
if req.Extension != "" {
query = query.Where("extension = ?", strings.ToLower(req.Extension))
}
var total int64
if err := query.Count(&total).Error; err != nil {
c.JSON(http.StatusOK, util.Err(ErrQueryFileCountFailed))
return
}
var items []model.Upload
offset := (req.Page - 1) * req.PageSize
if err := query.Order("created_at DESC").Offset(offset).Limit(req.PageSize).Find(&items).Error; err != nil {
c.JSON(http.StatusOK, util.Err(ErrQueryFileListFailed))
return
}
c.JSON(http.StatusOK, util.OK(listMyFilesResponse{
Total: total,
Page: req.Page,
PageSize: req.PageSize,
Items: items,
}))
}
// DeleteMyFile 软删除当前用户本人的文件
// @Summary 删除我的文件
// @Description 将当前用户本人的文件状态置为 deleted(软删除)
// @Tags upload
// @Produce json
// @Param id path string true "文件 ID"
// @Security SessionCookie
// @Success 200 {object} util.ResponseAny "删除成功"
// @Failure 403 {object} util.ResponseAny "无权操作"
// @Failure 404 {object} util.ResponseAny "文件不存在"
// @Router /api/v1/upload/{id} [delete]
func DeleteMyFile(c *gin.Context) {
currUser, _ := util.GetFromContext[*model.User](c, oauth.UserObjKey)
ctx := c.Request.Context()
if storageReadOnly(ctx) {
c.JSON(http.StatusConflict, util.Err(ErrStorageReadOnly))
return
}
uploadID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusOK, util.Err(ErrInvalidFileID))
return
}
var upload model.Upload
if err := db.DB(ctx).Where("id = ? AND status != ?", uploadID, model.UploadStatusDeleted).First(&upload).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithStatus(http.StatusNotFound)
return
}
c.JSON(http.StatusOK, util.Err(ErrQueryUploadRecordFailed))
return
}
if upload.UserID != currUser.ID {
c.AbortWithStatus(http.StatusForbidden)
return
}
if err := db.DB(ctx).Model(&upload).Update("status", model.UploadStatusDeleted).Error; err != nil {
c.JSON(http.StatusOK, util.Err(ErrDeleteFileFailed))
return
}
c.JSON(http.StatusOK, util.OKNil())
}
type updateMyFileRequest struct {
FileName string `json:"file_name" binding:"max=255"`
AccessMode *int `json:"access_mode" binding:"omitempty,oneof=0 1"`
}
// UpdateMyFile 更新当前用户本人的文件信息
// @Summary 更新我的文件信息
// @Description 更新当前用户本人的文件名或访问权限模式 (AccessMode)
// @Tags upload
// @Accept json
// @Produce json
// @Param id path string true "文件 ID"
// @Param request body updateMyFileRequest true "更新字段"
// @Security SessionCookie
// @Success 200 {object} util.ResponseAny{data=model.Upload} "更新成功"
// @Failure 403 {object} util.ResponseAny "无权操作"
// @Failure 404 {object} util.ResponseAny "文件不存在"
// @Router /api/v1/upload/{id} [put]
func UpdateMyFile(c *gin.Context) {
currUser, _ := util.GetFromContext[*model.User](c, oauth.UserObjKey)
ctx := c.Request.Context()
if storageReadOnly(ctx) {
c.JSON(http.StatusConflict, util.Err(ErrStorageReadOnly))
return
}
uploadID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusOK, util.Err(ErrInvalidFileID))
return
}
var req updateMyFileRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, util.Err(ErrInvalidParams))
return
}
var upload model.Upload
if err := db.DB(ctx).Where("id = ? AND status != ?", uploadID, model.UploadStatusDeleted).First(&upload).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithStatus(http.StatusNotFound)
return
}
c.JSON(http.StatusOK, util.Err(ErrQueryUploadRecordFailed))
return
}
if upload.UserID != currUser.ID {
c.AbortWithStatus(http.StatusForbidden)
return
}
updates := make(map[string]any)
if req.FileName != "" {
updates["file_name"] = req.FileName
}
if req.AccessMode != nil {
updates["access_mode"] = *req.AccessMode
}
if len(updates) > 0 {
if err := db.DB(ctx).Model(&upload).Updates(updates).Error; err != nil {
c.JSON(http.StatusOK, util.Err("更新文件记录失败"))
return
}
}
c.JSON(http.StatusOK, util.OK(upload))
}
+136
View File
@@ -48,6 +48,11 @@ func setupTestRouter(authUser *model.User) *gin.Engine {
uploadGroup.Use(authMiddleware)
{
uploadGroup.POST("", UploadFile)
uploadGroup.GET("/my", ListMyFiles)
uploadGroup.DELETE("/:id", DeleteMyFile)
uploadGroup.PUT("/:id", UpdateMyFile)
uploadGroup.GET("/download/:id", DownloadFile)
uploadGroup.POST("/download/batch", BatchDownloadFiles)
}
adminGroup := r.Group("/api/v1/admin/uploads")
@@ -855,3 +860,134 @@ func TestGetFileStats(t *testing.T) {
t.Errorf("expected 1 document category, got %d", categoryMap["文档"])
}
}
func TestUserUploadManagement(t *testing.T) {
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
defer cleanup()
user1 := &model.User{ID: 1001, Username: "user1"}
user2 := &model.User{ID: 1002, Username: "user2"}
_ = dbConn.Create(user1)
_ = dbConn.Create(user2)
router1 := setupTestRouter(user1)
router2 := setupTestRouter(user2)
// Seed upload records
upload1 := model.Upload{
ID: 4001,
UserID: 1001,
FileName: "user1-file.txt",
FilePath: "uploads/user1-file.txt",
FileSize: 100,
MimeType: "text/plain",
Extension: "txt",
StorageDriver: "local",
Status: model.UploadStatusUsed,
CreatedAt: time.Now(),
}
upload2 := model.Upload{
ID: 4002,
UserID: 1002,
FileName: "user2-file.png",
FilePath: "uploads/user2-file.png",
FileSize: 200,
MimeType: "image/png",
Extension: "png",
StorageDriver: "local",
Status: model.UploadStatusUsed,
CreatedAt: time.Now(),
}
_ = dbConn.Create(&upload1)
_ = dbConn.Create(&upload2)
t.Run("ListMyFiles only returns own files", func(t *testing.T) {
req, _ := http.NewRequest("GET", "/api/v1/upload/my", nil)
w := httptest.NewRecorder()
router1.ServeHTTP(w, req)
var resp struct {
ErrorMsg string `json:"error_msg"`
Data listMyFilesResponse `json:"data"`
}
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp.ErrorMsg != "" {
t.Fatalf("ListMyFiles error: %s", resp.ErrorMsg)
}
if resp.Data.Total != 1 {
t.Errorf("expected 1 file for user1, got %d", resp.Data.Total)
}
if len(resp.Data.Items) != 1 || resp.Data.Items[0].ID != 4001 {
t.Errorf("expected file 4001, got items: %+v", resp.Data.Items)
}
})
t.Run("UpdateMyFile updates file name and access mode successfully", func(t *testing.T) {
newMode := 1
reqBody, _ := json.Marshal(updateMyFileRequest{
FileName: "renamed.txt",
AccessMode: &newMode,
})
req, _ := http.NewRequest("PUT", "/api/v1/upload/4001", bytes.NewReader(reqBody))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router1.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d. Body: %s", w.Code, w.Body.String())
}
var updated model.Upload
dbConn.First(&updated, 4001)
if updated.FileName != "renamed.txt" {
t.Errorf("expected file name renamed.txt, got %s", updated.FileName)
}
if updated.AccessMode != 1 {
t.Errorf("expected access mode 1, got %d", updated.AccessMode)
}
})
t.Run("UpdateMyFile blocks non-owners", func(t *testing.T) {
reqBody, _ := json.Marshal(updateMyFileRequest{
FileName: "hack.txt",
})
req, _ := http.NewRequest("PUT", "/api/v1/upload/4001", bytes.NewReader(reqBody))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router2.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Errorf("expected status 403, got %d", w.Code)
}
})
t.Run("DeleteMyFile blocks non-owners", func(t *testing.T) {
req, _ := http.NewRequest("DELETE", "/api/v1/upload/4001", nil)
w := httptest.NewRecorder()
router2.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Errorf("expected status 403, got %d", w.Code)
}
})
t.Run("DeleteMyFile deletes file successfully", func(t *testing.T) {
req, _ := http.NewRequest("DELETE", "/api/v1/upload/4001", nil)
w := httptest.NewRecorder()
router1.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
var deleted model.Upload
dbConn.First(&deleted, 4001)
if deleted.Status != model.UploadStatusDeleted {
t.Errorf("expected status deleted, got %s", deleted.Status)
}
})
}
+16 -7
View File
@@ -14,6 +14,15 @@ import (
"github.com/gin-gonic/gin"
)
const (
catImage = "图片"
catVideo = "视频"
catAudio = "音频"
catDocument = "文档"
catArchive = "压缩包"
catOther = "其他"
)
type trendItem struct {
Date string `json:"date"`
Count int64 `json:"count"`
@@ -110,7 +119,7 @@ func GetFileStats(c *gin.Context) {
catCount := make(map[string]int64)
catSize := make(map[string]int64)
categoriesList := []string{"图片", "视频", "音频", "文档", "压缩包", "其他"}
categoriesList := []string{catImage, catVideo, catAudio, catDocument, catArchive, catOther}
for _, cat := range categoriesList {
catCount[cat] = 0
catSize[cat] = 0
@@ -190,21 +199,21 @@ func getFileCategory(mimeType, ext string) string {
ext = strings.ToLower(ext)
if strings.HasPrefix(mimeType, "image/") || isImageExtension(ext) {
return "图片"
return catImage
}
if strings.HasPrefix(mimeType, "video/") {
return "视频"
return catVideo
}
if strings.HasPrefix(mimeType, "audio/") {
return "音频"
return catAudio
}
if isArchiveExtension(ext) || strings.Contains(mimeType, "zip") || strings.Contains(mimeType, "tar") || strings.Contains(mimeType, "gzip") {
return "压缩包"
return catArchive
}
if isDocumentExtension(ext) || strings.HasPrefix(mimeType, "text/") || mimeType == "application/pdf" {
return "文档"
return catDocument
}
return "其他"
return catOther
}
func isArchiveExtension(ext string) bool {
+27 -14
View File
@@ -210,11 +210,7 @@ func registerRoutes(r *gin.Engine) {
}
// Upload
uploadRouter := apiV1Router.Group("/upload")
uploadRouter.Use(oauth.LoginRequired())
{
uploadRouter.POST("", upload.UploadFile)
}
registerUploadRoutes(apiV1Router)
// Config (public)
configRouter := apiV1Router.Group("/config")
@@ -277,15 +273,7 @@ func registerRoutes(r *gin.Engine) {
adminRouter.DELETE("/users/:id", admin_user.DeleteUser)
// Uploads
adminUploadsRouter := adminRouter.Group("/uploads")
{
adminUploadsRouter.GET("", upload.ListFiles)
adminUploadsRouter.GET("/stats", upload.GetFileStats)
adminUploadsRouter.DELETE("/:id", upload.DeleteFile)
adminUploadsRouter.GET("/download/:id", upload.DownloadFile)
adminUploadsRouter.POST("/download/batch", upload.BatchDownloadFiles)
adminUploadsRouter.GET("/types", upload.GetDistinctUploadTypes)
}
registerAdminUploadRoutes(adminRouter)
// System Config
adminRouter.POST("/system-configs", system_config.CreateSystemConfig)
@@ -325,3 +313,28 @@ func registerRoutes(r *gin.Engine) {
// 注册前端静态路由(当启用 embed_frontend 编译标签时)
registerFrontend(r)
}
func registerUploadRoutes(apiV1Router *gin.RouterGroup) {
uploadRouter := apiV1Router.Group("/upload")
uploadRouter.Use(oauth.LoginRequired())
{
uploadRouter.POST("", upload.UploadFile)
uploadRouter.GET("/my", upload.ListMyFiles)
uploadRouter.DELETE("/:id", upload.DeleteMyFile)
uploadRouter.PUT("/:id", upload.UpdateMyFile)
uploadRouter.GET("/download/:id", upload.DownloadFile)
uploadRouter.POST("/download/batch", upload.BatchDownloadFiles)
}
}
func registerAdminUploadRoutes(adminRouter *gin.RouterGroup) {
adminUploadsRouter := adminRouter.Group("/uploads")
{
adminUploadsRouter.GET("", upload.ListFiles)
adminUploadsRouter.GET("/stats", upload.GetFileStats)
adminUploadsRouter.DELETE("/:id", upload.DeleteFile)
adminUploadsRouter.GET("/download/:id", upload.DownloadFile)
adminUploadsRouter.POST("/download/batch", upload.BatchDownloadFiles)
adminUploadsRouter.GET("/types", upload.GetDistinctUploadTypes)
}
}