102 lines
2.6 KiB
Go
102 lines
2.6 KiB
Go
package user
|
|
|
|
import (
|
|
"fmt"
|
|
"jannex/admin-dashboard-backend/modules/config"
|
|
"jannex/admin-dashboard-backend/modules/database"
|
|
"jannex/admin-dashboard-backend/modules/logger"
|
|
"jannex/admin-dashboard-backend/modules/structs"
|
|
"jannex/admin-dashboard-backend/modules/utils"
|
|
"jannex/admin-dashboard-backend/socketclients"
|
|
"os"
|
|
"strings"
|
|
|
|
"git.ex.umbach.dev/Alex/roese-utils/rslogger"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/savsgio/gotils/uuid"
|
|
)
|
|
|
|
func UpdateAvatar(c *fiber.Ctx) error {
|
|
// swagger:operation POST /user/avatar user userAvatar
|
|
// ---
|
|
// summary: Update user avatar
|
|
// consumes:
|
|
// - multipart/form-data
|
|
// produces:
|
|
// - application/json
|
|
// parameters:
|
|
// - name: X-Api-Key
|
|
// in: header
|
|
// description: You can create a new api key in your user profile
|
|
// - name: file
|
|
// in: formData
|
|
// type: file
|
|
// description: Avatar file
|
|
// responses:
|
|
// '200':
|
|
// description: User avatar updated successfully
|
|
// '400':
|
|
// description: Invalid request body
|
|
// '401':
|
|
// description: No permissions
|
|
// '413':
|
|
// description: File too large
|
|
// '422':
|
|
// description: Invalid file type
|
|
// '500':
|
|
// description: Failed to update user avatar
|
|
|
|
fileHeader, err := c.FormFile("file")
|
|
|
|
if err != nil {
|
|
log.Error().Msgf("User Avatar file error: %v", err)
|
|
return c.SendStatus(fiber.StatusBadRequest)
|
|
}
|
|
|
|
if fileHeader.Size > utils.MaxAvatarSize {
|
|
return c.SendStatus(fiber.StatusRequestEntityTooLarge)
|
|
}
|
|
|
|
if !isAvatarFileTypeInList(fileHeader.Header["Content-Type"][0]) {
|
|
return c.SendStatus(fiber.StatusUnprocessableEntity)
|
|
}
|
|
|
|
user := structs.User{Id: c.Locals("userId").(string)}
|
|
|
|
database.DB.First(&user)
|
|
|
|
if user.Avatar != "" {
|
|
os.Remove(config.Cfg.FolderPaths.PublicStatic + "avatars/" + user.Avatar)
|
|
}
|
|
|
|
fileName := uuid.V4() + "." + strings.Split(fileHeader.Header["Content-Type"][0], "/")[1]
|
|
|
|
database.DB.Model(&structs.User{}).Where("id = ?", user.Id).Updates(&structs.User{Avatar: fileName})
|
|
|
|
socketclients.BroadcastMessage(structs.SendSocketMessage{
|
|
Cmd: utils.SentCmdUpdateAllUsersUserAvatar,
|
|
Body: struct {
|
|
UserId string
|
|
Avatar string
|
|
}{
|
|
UserId: user.Id,
|
|
Avatar: fileName,
|
|
},
|
|
})
|
|
|
|
logger.AddSystemLog(rslogger.LogTypeInfo, "User %s has changed his avatar", user.Id)
|
|
|
|
return c.SaveFile(fileHeader, fmt.Sprintf("%savatars/%s", config.Cfg.FolderPaths.PublicStatic, fileName))
|
|
}
|
|
|
|
func isAvatarFileTypeInList(contentType string) bool {
|
|
for _, aType := range utils.AcceptedAvatarFileTypes {
|
|
if aType == contentType {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|