π The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
Add delete ressources
Smaug#67393e87bbad6851
diff --git a/backend/controllers/uploads.controller.go b/backend/controllers/uploads.controller.goindex 26cb6548..b5526c9a 100644--- a/backend/controllers/uploads.controller.go+++ b/backend/controllers/uploads.controller.go@@ -4,11 +4,13 @@ import ("alexandrie/app""alexandrie/models""alexandrie/utils"+ "context""errors""fmt""net/http""os""path/filepath"+ "strconv""time""slices"@@ -19,8 +21,8 @@ import (type UploadController interface {GetAllUploads(c *gin.Context) (int, any)- UploadAvatar(c *gin.Context) (int, any)UploadFile(c *gin.Context) (int, any)+ DeleteUpload(c *gin.Context) (int, any)}func NewUploadController(app *app.App) UploadController {@@ -38,57 +40,9 @@ func (ctr *Controller) GetAllUploads(c *gin.Context) (int, any) {if err != nil {return http.StatusInternalServerError, err}-return http.StatusOK, uploads}-func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {- file, header, err := c.Request.FormFile("avatar")- if err != nil {- return http.StatusBadRequest, errors.New("failed to get file")- }- defer file.Close()-- ext := filepath.Ext(header.Filename)-- // Check if the file size exceeds the limit- if header.Size > int64(ctr.app.Config.Cdn.MaxSize) {- return http.StatusBadRequest, errors.New("file size exceeds the limit")- }-- // Check if the MIME type is supported- mimeType := header.Header.Get("Content-Type")- isSupportedMime := slices.Contains(ctr.app.Config.Cdn.SupportedTypesImages, mimeType)- if !isSupportedMime {- return http.StatusBadRequest, errors.New("file type not supported")- }-- userID, _ := c.Get("user_id")- prefix := fmt.Sprintf("avatars/%0.f", userID)-- // Lister les fichiers de l'utilisateur dans MinIO- objectsCh := ctr.app.MinioClient.ListObjects(c, os.Getenv("MINIO_BUCKET"), minio.ListObjectsOptions{- Prefix: prefix,- Recursive: true,- })-- // Supprimer les anciens avatars- for object := range objectsCh {- if object.Err == nil {- _ = ctr.app.MinioClient.RemoveObject(c, os.Getenv("MINIO_BUCKET"), object.Key, minio.RemoveObjectOptions{})- }- }-- objectName := fmt.Sprintf("avatars/%0.f%s", userID, ext)-- _, err = ctr.app.MinioClient.PutObject(c, os.Getenv("MINIO_BUCKET"), objectName, file, header.Size, minio.PutObjectOptions{ContentType: header.Header.Get("Content-Type")})- if err != nil {- return http.StatusInternalServerError, errors.New("failed to upload file")- }-- return http.StatusOK, "Avatar uploaded successfully"-}-// UploadFile// @Summary Upload a file// @Method POST@@ -136,7 +90,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {// Create a new ressourceressource := &models.Ressource{Id: ctr.app.Snowflake.Generate(),- Filename: header.Filename,+ Filename: fmt.Sprintf("%.*s", 40, header.Filename),Filesize: header.Size,Filetype: mimeType,OriginalPath: header.Filename,@@ -148,6 +102,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {_, err = ctr.app.Services.Ressource.CreateRessource(ressource)if err != nil {+ fmt.Println(err)return http.StatusInternalServerError, errors.New("failed to create ressource")}@@ -158,3 +113,57 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {return http.StatusOK, ressource}++// DeleteUpload+// @Summary Delete an upload+// @Method DELETE+// @Router /uploads/{id} [delete]+// @Security Authenfification: Auth+// @Param id path string true "ID of the upload to delete"+// @Success 200 {object} Success(string)+// @Failure 400 {object} Error+// @Failure 401 {object} Error+func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {+ id, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil {+ return http.StatusBadRequest, errors.New("invalid id format")+ }+ userId, err := utils.GetUserIdCtx(c)+ if err != nil {+ return http.StatusUnauthorized, err+ }+ ressource, err := ctr.app.Services.Ressource.GetRessourceById(id)+ if err != nil {+ return http.StatusInternalServerError, "failed to get ressource"+ }+ if ressource == nil {+ return http.StatusBadRequest, errors.New("ressource not found")+ }+ if ressource.AuthorId != userId && !utils.CheckUserRequestPermission(c, utils.ADMINISTRATOR) {+ return http.StatusUnauthorized, errors.New("you are not authorized to delete this ressource")+ }++ prefix := fmt.Sprintf("uploads/%d/%d", ressource.AuthorId, ressource.Id)+ // List all objects in the bucket with the given prefix+ ctx := context.Background()+ objectCh := ctr.app.MinioClient.ListObjects(ctx, os.Getenv("MINIO_BUCKET"), minio.ListObjectsOptions{+ Prefix: prefix,+ Recursive: true,+ })++ // Delete each object+ for object := range objectCh {+ if object.Err != nil {+ return http.StatusInternalServerError, object.Err+ }+ err = ctr.app.MinioClient.RemoveObject(ctx, os.Getenv("MINIO_BUCKET"), object.Key, minio.RemoveObjectOptions{})+ if err != nil {+ return http.StatusInternalServerError, fmt.Errorf("failed to delete object: %v", err)+ }+ }+ err = ctr.app.Services.Ressource.DeleteRessource(id)+ if err != nil {+ return http.StatusInternalServerError, err+ }+ return http.StatusOK, "File deleted successfully"+}diff --git a/backend/router/routes/uploads.go b/backend/router/routes/uploads.goindex 005bcbaa..49145a99 100644--- a/backend/router/routes/uploads.go+++ b/backend/router/routes/uploads.go@@ -14,7 +14,8 @@ func Uploads(app *app.App, router *gin.RouterGroup) {uploadsCtrl := controllers.NewUploadController(app)uploads.Use(middlewares.Auth())+uploads.GET(("/:userId"), utils.WP(uploadsCtrl.GetAllUploads))- uploads.POST("/avatar", utils.WP(uploadsCtrl.UploadAvatar))uploads.POST("/", utils.WP(uploadsCtrl.UploadFile))+ uploads.DELETE("/:id", utils.WP(uploadsCtrl.DeleteUpload))}diff --git a/backend/services/ressource.service.go b/backend/services/ressource.service.goindex 6ea9523e..a3b95237 100644--- a/backend/services/ressource.service.go+++ b/backend/services/ressource.service.go@@ -7,8 +7,10 @@ import (type RessourceService interface {GetAllUploadsByUserId(userId int64) ([]*models.Ressource, error)+ GetRessourceById(id int64) (*models.Ressource, error)GetUserUploadsSize(userId int64) (int64, error)CreateRessource(ressource *models.Ressource) (*models.Ressource, error)+ DeleteRessource(id int64) error}func NewRessourceService(db *sql.DB) RessourceService {@@ -33,19 +35,36 @@ func (s *Service) GetAllUploadsByUserId(userId int64) ([]*models.Ressource, erroreturn ressources, nil}-func (s *Service) CreateRessource(ressource *models.Ressource) (*models.Ressource, error) {- _, err := s.db.Exec("INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path, author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ressource.Id, ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.AuthorId, ressource.CreatedTimestamp)+func (s *Service) GetRessourceById(id int64) (*models.Ressource, error) {+ var ressource models.Ressource+ err := s.db.QueryRow("SELECT * FROM ressources WHERE id = ?", id).Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.AuthorId, &ressource.CreatedTimestamp)if err != nil {return nil, err}- return ressource, nil+ return &ressource, nil}func (s *Service) GetUserUploadsSize(userId int64) (int64, error) {- var totalSize int64+ var totalSize *int64err := s.db.QueryRow("SELECT SUM(file_size) FROM ressources WHERE author_id = ?", userId).Scan(&totalSize)if err != nil {return 0, err}- return totalSize, nil+ if totalSize == nil {+ return 0, nil+ }+ return *totalSize, nil+}++func (s *Service) CreateRessource(ressource *models.Ressource) (*models.Ressource, error) {+ _, err := s.db.Exec("INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path, author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ressource.Id, ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.AuthorId, ressource.CreatedTimestamp)+ if err != nil {+ return nil, err+ }+ return ressource, nil+}++func (s *Service) DeleteRessource(id int64) error {+ _, err := s.db.Exec("DELETE FROM ressources WHERE id = ?", id)+ return err}diff --git a/backend/utils/permissions.go b/backend/utils/permissions.goindex d387fb31..ad0a39aa 100644--- a/backend/utils/permissions.go+++ b/backend/utils/permissions.go@@ -20,6 +20,18 @@ func CheckPermission(userRole, requiredRole int) bool {return userRole&requiredRole == requiredRole}+func CheckUserRequestPermission(ctx *gin.Context, requiredRole int) bool {+ // Check if the user has the required permission+ role, exists := ctx.Get("user_role")+ if !exists {+ return false+ }+ if CheckPermission(role.(int), requiredRole) {+ return true+ }+ return false+}+func GetUserIdParam(param string, ctx *gin.Context) (int64, error) {if param == "" {return 0, errors.New("user ID parameter is empty")