44 lines
1 KiB
Go
44 lines
1 KiB
Go
package routes
|
|
|
|
import (
|
|
"path/filepath"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"stereo.cat/backend/internal/auth"
|
|
"stereo.cat/backend/internal/types"
|
|
)
|
|
|
|
func RegisterUploadRoutes(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 := c.SaveUploadedFile(file, filePath); err != nil {
|
|
c.JSON(500, gin.H{"error": "failed to save file"})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, gin.H{"message": "file uploaded successfully"})
|
|
})
|
|
|
|
api.GET("/:name", func(c *gin.Context) {
|
|
name := c.Param("name")
|
|
path := filepath.Join(cfg.ImagePath, name)
|
|
c.File(path)
|
|
})
|
|
}
|