You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.9 KiB
75 lines
1.9 KiB
// Code scaffolded by goctl. Safe to edit.
|
|
// goctl 1.9.2
|
|
|
|
package file
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type DeleteFileLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 删除文件
|
|
func NewDeleteFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteFileLogic {
|
|
return &DeleteFileLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *DeleteFileLogic) DeleteFile(req *types.DeleteFileRequest) (resp *types.Response, err error) {
|
|
// Get userId and role from context
|
|
userId, _ := l.ctx.Value("userId").(int64)
|
|
if userId == 0 {
|
|
if num, ok := l.ctx.Value("userId").(interface{ Int64() (int64, error) }); ok {
|
|
userId, _ = num.Int64()
|
|
}
|
|
}
|
|
userRole, _ := l.ctx.Value("role").(string)
|
|
|
|
// Find file by ID
|
|
fileRecord, err := model.FileFindOne(l.ctx, l.svcCtx.DB, req.Id)
|
|
if err != nil {
|
|
if err == model.ErrNotFound {
|
|
return nil, fmt.Errorf("file not found")
|
|
}
|
|
return nil, fmt.Errorf("failed to query file: %v", err)
|
|
}
|
|
|
|
// Permission check: user can only delete own files, admin can delete all
|
|
if userRole != model.RoleAdmin && userRole != model.RoleSuperAdmin {
|
|
if fileRecord.UserId != userId {
|
|
return nil, fmt.Errorf("permission denied")
|
|
}
|
|
}
|
|
|
|
// Soft delete the file record
|
|
if err := model.FileDelete(l.ctx, l.svcCtx.DB, req.Id); err != nil {
|
|
return nil, fmt.Errorf("failed to delete file: %v", err)
|
|
}
|
|
|
|
// Attempt to delete from storage (log error but don't fail)
|
|
if err := l.svcCtx.Storage.Delete(l.ctx, fileRecord.Key); err != nil {
|
|
l.Errorf("failed to delete file from storage (key=%s): %v", fileRecord.Key, err)
|
|
}
|
|
|
|
resp = &types.Response{
|
|
Code: 0,
|
|
Message: "file deleted successfully",
|
|
Success: true,
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|