skibidi
This commit is contained in:
parent
93aec1336d
commit
e16a4eae26
3 changed files with 16 additions and 3 deletions
76
internal/api/routes/files.go
Normal file
76
internal/api/routes/files.go
Normal file
|
@ -0,0 +1,76 @@
|
|||
package routes
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"stereo.cat/backend/internal/auth"
|
||||
"stereo.cat/backend/internal/types"
|
||||
)
|
||||
|
||||
func RegisterFileRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
|
||||
api.POST("/upload", auth.JwtMiddleware(cfg.JWTSecret), func(c *gin.Context) {
|
||||
claims := c.MustGet("claims").(jwt.MapClaims)
|
||||
user := claims["user"].(auth.User)
|
||||
|
||||
uid := user.ID
|
||||
if uid == "" {
|
||||
c.JSON(401, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"error": "file is required"})
|
||||
return
|
||||
}
|
||||
|
||||
filePath := filepath.Join(cfg.ImagePath, uid, file.Filename)
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
|
||||
c.JSON(500, gin.H{"error": "failed to create directory"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.SaveUploadedFile(file, filePath); err != nil {
|
||||
c.JSON(500, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
|
||||
fileMeta := types.File{
|
||||
ID: uid + "_" + file.Filename,
|
||||
Path: filePath,
|
||||
Owner: uid,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := cfg.Database.Create(&fileMeta).Error; err != nil {
|
||||
c.JSON(500, gin.H{"error": "failed to save file metadata"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"message": "file uploaded successfully", "file_id": fileMeta.ID})
|
||||
})
|
||||
|
||||
api.GET("/:name", func(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
path := filepath.Join(cfg.ImagePath, name)
|
||||
c.File(path)
|
||||
})
|
||||
|
||||
api.GET("/list", auth.JwtMiddleware(cfg.JWTSecret), func(c *gin.Context) {
|
||||
claims := c.MustGet("claims").(jwt.MapClaims)
|
||||
user := claims["user"].(auth.User)
|
||||
|
||||
var files []types.File
|
||||
if err := cfg.Database.Where("owner = ?", user.ID).Find(&files).Error; err != nil {
|
||||
c.JSON(500, gin.H{"error": "failed to retrieve files"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, files)
|
||||
})
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue