Skip to content

πŸ“š The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

Upload file service & checks

Smaug#6739fdb5578c889d
diff --git a/backend/app/app.go b/backend/app/app.go
index 49516624..36187d91 100644
--- a/backend/app/app.go
+++ b/backend/app/app.go
@@ -30,10 +30,11 @@ type Config struct {
}
type Services struct {
- User services.UserService
- Session services.AuthService
- Log services.LogService
- Document services.DocumentService
+ User services.UserService
+ Session services.AuthService
+ Log services.LogService
+ Document services.DocumentService
+ Ressource services.RessourceService
}
type App struct {
@@ -51,10 +52,11 @@ func InitApp(config Config) *App {
app.Snowflake = utils.NewSnowflake(1609459200000)
app.Config = config
app.Services = Services{
- User: services.NewUserService(app.DB),
- Session: services.NewAuthService(app.DB),
- Log: services.NewLogService(app.DB),
- Document: services.NewDocumentService(app.DB),
+ User: services.NewUserService(app.DB),
+ Session: services.NewAuthService(app.DB),
+ Log: services.NewLogService(app.DB),
+ Document: services.NewDocumentService(app.DB),
+ Ressource: services.NewRessourceService(app.DB),
}
Migrate(&config)
diff --git a/backend/controllers/uploads.controller.go b/backend/controllers/uploads.controller.go
index 9df12c64..26cb6548 100644
--- a/backend/controllers/uploads.controller.go
+++ b/backend/controllers/uploads.controller.go
@@ -2,17 +2,23 @@ package controllers
import (
"alexandrie/app"
+ "alexandrie/models"
+ "alexandrie/utils"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
+ "time"
+
+ "slices"
"github.com/gin-gonic/gin"
"github.com/minio/minio-go/v7"
)
type UploadController interface {
+ GetAllUploads(c *gin.Context) (int, any)
UploadAvatar(c *gin.Context) (int, any)
UploadFile(c *gin.Context) (int, any)
}
@@ -23,6 +29,19 @@ func NewUploadController(app *app.App) UploadController {
}
}
+func (ctr *Controller) GetAllUploads(c *gin.Context) (int, any) {
+ userId, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ uploads, err := ctr.app.Services.Ressource.GetAllUploadsByUserId(userId)
+ 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 {
@@ -39,13 +58,7 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {
// Check if the MIME type is supported
mimeType := header.Header.Get("Content-Type")
- isSupportedMime := false
- for _, supportedMime := range ctr.app.Config.Cdn.SupportedTypesImages {
- if mimeType == supportedMime {
- isSupportedMime = true
- break
- }
- }
+ isSupportedMime := slices.Contains(ctr.app.Config.Cdn.SupportedTypesImages, mimeType)
if !isSupportedMime {
return http.StatusBadRequest, errors.New("file type not supported")
}
@@ -76,6 +89,15 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {
return http.StatusOK, "Avatar uploaded successfully"
}
+// UploadFile
+// @Summary Upload a file
+// @Method POST
+// @Router /uploads/ [post]
+// @Security Authenfification: Auth
+// @Param file formData file true "File to upload"
+// @Success 200 {object} Success(ressource)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
file, header, err := c.Request.FormFile("file")
if err != nil {
@@ -86,31 +108,53 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
ext := filepath.Ext(header.Filename)
// Check if the file size exceeds the limit
- if header.Size > int64(ctr.app.Config.Cdn.MaxUploadsSize) {
+ 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 := false
- for _, supportedMime := range ctr.app.Config.Cdn.SupportedTypes {
- if mimeType == supportedMime {
- isSupportedMime = true
- break
- }
- }
+ isSupportedMime := slices.Contains(ctr.app.Config.Cdn.SupportedTypes, mimeType)
if !isSupportedMime {
return http.StatusBadRequest, errors.New("file type not supported")
}
- userID, _ := c.Get("user_id")
+ userId, err := utils.GetUserIdCtx(c)
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+
+ // Check total size of uploads
+ totalSize, err := ctr.app.Services.Ressource.GetUserUploadsSize(userId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ if totalSize+header.Size > int64(ctr.app.Config.Cdn.MaxUploadsSize) {
+ return http.StatusBadRequest, errors.New("total size of uploads exceeds the limit")
+ }
+
+ // Create a new ressource
+ ressource := &models.Ressource{
+ Id: ctr.app.Snowflake.Generate(),
+ Filename: header.Filename,
+ Filesize: header.Size,
+ Filetype: mimeType,
+ OriginalPath: header.Filename,
+ TransformedPath: "uploads/" + header.Filename,
+ AuthorId: userId,
+ CreatedTimestamp: time.Now().UnixMilli(),
+ }
+ objectName := fmt.Sprintf("uploads/%d/%d%s", ressource.AuthorId, ressource.Id, ext)
- objectName := fmt.Sprintf("uploads/%0.f%s", userID, ext)
+ _, err = ctr.app.Services.Ressource.CreateRessource(ressource)
+ if err != nil {
+ return http.StatusInternalServerError, errors.New("failed to create ressource")
+ }
_, 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, "File uploaded successfully"
+ return http.StatusOK, ressource
}
diff --git a/backend/router/routes/uploads.go b/backend/router/routes/uploads.go
index c0c2b4af..005bcbaa 100644
--- a/backend/router/routes/uploads.go
+++ b/backend/router/routes/uploads.go
@@ -14,5 +14,7 @@ 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))
}
diff --git a/backend/services/ressource.service.go b/backend/services/ressource.service.go
new file mode 100644
index 00000000..6ea9523e
--- /dev/null
+++ b/backend/services/ressource.service.go
@@ -0,0 +1,51 @@
+package services
+
+import (
+ "alexandrie/models"
+ "database/sql"
+)
+
+type RessourceService interface {
+ GetAllUploadsByUserId(userId int64) ([]*models.Ressource, error)
+ GetUserUploadsSize(userId int64) (int64, error)
+ CreateRessource(ressource *models.Ressource) (*models.Ressource, error)
+}
+
+func NewRessourceService(db *sql.DB) RessourceService {
+ return &Service{db: db}
+}
+
+func (s *Service) GetAllUploadsByUserId(userId int64) ([]*models.Ressource, error) {
+ var ressources []*models.Ressource
+ rows, err := s.db.Query("SELECT * from ressources WHERE author_id = ?", userId)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var ressource models.Ressource
+ if err := rows.Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.AuthorId, &ressource.CreatedTimestamp); err != nil {
+ return nil, err
+ }
+ ressources = append(ressources, &ressource)
+ }
+ return 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)
+ if err != nil {
+ return nil, err
+ }
+ return ressource, nil
+}
+
+func (s *Service) GetUserUploadsSize(userId int64) (int64, error) {
+ var totalSize int64
+ err := s.db.QueryRow("SELECT SUM(file_size) FROM ressources WHERE author_id = ?", userId).Scan(&totalSize)
+ if err != nil {
+ return 0, err
+ }
+ return totalSize, nil
+}