chore: remove direct avatar upload endpoint (POST /profile/avatar);

feat: add endpoints for presigned upload URLs (GET /upload/avatar, GET /upload/image);
refactor: replace ProfileDto with NewProfileDto in update profile endpoint;
feat: implement S3 integration for avatar management;
fix: update database queries to handle new avatar upload flow;
chore: add new dependencies for S3 handling (golang.org/x/time);
refactor: rename UploadService to S3Service;
refactor: change return type for func LocalizeS3Url(originalURL string) (*url.URL, error);
feat: add custom validator for upload_id
This commit is contained in:
2025-08-01 04:34:06 +03:00
parent 8dba0f79aa
commit 669349e020
15 changed files with 405 additions and 222 deletions

View File

@@ -24,7 +24,6 @@ import (
"easywish/internal/utils/enums"
"errors"
"net/http"
"os"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -78,13 +77,6 @@ func NewProfileController(_log *zap.Logger, _ps services.ProfileService) Control
Middleware: []gin.HandlerFunc{},
Function: ctrl.updateProfileSettings,
},
{
HttpMethod: POST,
Path: "/avatar",
Authorization: enums.UserRole,
Middleware: []gin.HandlerFunc{},
Function: ctrl.uploadAvatar,
},
},
}
}
@@ -169,11 +161,11 @@ func (ctrl *ProfileController) getProfileSettings(c *gin.Context) {
// @Accept json
// @Produce json
// @Security JWT
// @Param request body dto.ProfileDto true " "
// @Param request body dto.NewProfileDto true " "
// @Success 200 {object} bool " "
// @Router /profile [put]
func (ctrl *ProfileController) updateProfile(c *gin.Context) {
request, err := GetRequest[dto.ProfileDto](c); if err != nil {
request, err := GetRequest[dto.NewProfileDto](c); if err != nil {
return
}
@@ -206,33 +198,3 @@ func (ctrl *ProfileController) updateProfileSettings(c *gin.Context) {
c.JSON(http.StatusOK, response)
}
// XXX: untested
// @Summary Upload an avatar
// @Tags Profile
// @Accept mpfd
// @Produce json
// @Security JWT
// @Param file formData file true "Avatar image file"
// @Success 200 {object} dto.UrlDto "Uploaded image url"
// @Router /profile/avatar [post]
func (ctrl *ProfileController) uploadAvatar(c *gin.Context) {
cinfo := GetClientInfo(c)
allowedTypes := map[string]bool{
"image/jpeg": true,
"image/png": true,
"image/webp": true,
}
fileName, err := GetFile(c, "file", 8*1024*1024, allowedTypes); if err != nil {
return
}
defer os.Remove(*fileName)
link, err := ctrl.ps.UploadAvatar(cinfo, *fileName); if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.JSON(http.StatusOK, dto.UrlDto{Url: *link})
}

View File

@@ -30,13 +30,13 @@ import (
"golang.org/x/time/rate"
)
type UploadController struct {
type S3Controller struct {
log *zap.Logger
us services.UploadService
s3 services.S3Service
}
func NewUploadController(_log *zap.Logger, _us services.UploadService) Controller {
ctrl := UploadController{log: _log, us: _us}
func NewS3Controller(_log *zap.Logger, _us services.S3Service) Controller {
ctrl := S3Controller{log: _log, s3: _us}
return &controllerImpl{
Path: "/upload",
@@ -71,8 +71,8 @@ func NewUploadController(_log *zap.Logger, _us services.UploadService) Controlle
// @Success 200 {object} models.PresignedUploadResponse "Presigned URL and form data"
// @Failure 500 "Internal server error"
// @Router /upload/avatar [get]
func (ctrl *UploadController) getAvatarUploadUrl(c *gin.Context) {
url, formData, err := ctrl.us.GetAvatarUrl()
func (ctrl *S3Controller) getAvatarUploadUrl(c *gin.Context) {
url, formData, err := ctrl.s3.CreateAvatarUrl()
if err != nil {
ctrl.log.Error("Failed to generate avatar upload URL", zap.Error(err))
c.Status(http.StatusInternalServerError)
@@ -94,8 +94,8 @@ func (ctrl *UploadController) getAvatarUploadUrl(c *gin.Context) {
// @Success 200 {object} models.PresignedUploadResponse "Presigned URL and form data"
// @Failure 500 "Internal server error"
// @Router /upload/image [get]
func (ctrl *UploadController) getImageUploadUrl(c *gin.Context) {
url, formData, err := ctrl.us.GetImageUrl()
func (ctrl *S3Controller) getImageUploadUrl(c *gin.Context) {
url, formData, err := ctrl.s3.CreateImageUrl()
if err != nil {
c.Status(http.StatusInternalServerError)
return

View File

@@ -990,9 +990,9 @@ SET
name = COALESCE($2, name),
bio = COALESCE($3, bio),
birthday = COALESCE($4, birthday),
avatar_url = COALESCE($5, avatar_url),
color = COALESCE($6, color),
color_grad = COALESCE($7, color_grad)
avatar_url = COALESCE($7, avatar_url),
color = COALESCE($5, color),
color_grad = COALESCE($6, color_grad)
FROM users
WHERE username = $1
`
@@ -1002,9 +1002,9 @@ type UpdateProfileByUsernameParams struct {
Name string
Bio string
Birthday pgtype.Timestamp
AvatarUrl string
Color string
ColorGrad string
AvatarUrl *string
}
func (q *Queries) UpdateProfileByUsername(ctx context.Context, arg UpdateProfileByUsernameParams) error {
@@ -1013,9 +1013,9 @@ func (q *Queries) UpdateProfileByUsername(ctx context.Context, arg UpdateProfile
arg.Name,
arg.Bio,
arg.Birthday,
arg.AvatarUrl,
arg.Color,
arg.ColorGrad,
arg.AvatarUrl,
)
return err
}

View File

@@ -18,12 +18,21 @@
package dto
type ProfileDto struct {
Name string `json:"name" binding:"required" validate:"name"`
Bio string `json:"bio" validate:"bio"`
AvatarUrl string `json:"avatar_url"`
Name string `json:"name"`
Bio string `json:"bio"`
AvatarUrl *string `json:"avatar_url"`
Birthday int64 `json:"birthday"`
Color string `json:"color" validate:"color_hex"`
ColorGrad string `json:"color_grad" validate:"color_hex"`
Color string `json:"color"`
ColorGrad string `json:"color_grad"`
}
type NewProfileDto struct {
Name string `json:"name" binding:"required" validate:"name"`
Bio string `json:"bio" validate:"bio"`
AvatarUploadID *string `json:"avatar_upload_id" validate:"upload_id=avatars"`
Birthday int64 `json:"birthday"`
Color string `json:"color" validate:"color_hex"`
ColorGrad string `json:"color_grad" validate:"color_hex"`
}
type ProfileSettingsDto struct {

View File

@@ -21,6 +21,7 @@ import (
"easywish/internal/database"
"easywish/internal/dto"
errs "easywish/internal/errors"
"easywish/internal/utils"
mapspecial "easywish/internal/utils/mapSpecial"
"errors"
"time"
@@ -36,10 +37,9 @@ import (
type ProfileService interface {
GetProfileByUsername(cinfo dto.ClientInfo, username string) (*dto.ProfileDto, error)
GetMyProfile(cinfo dto.ClientInfo) (*dto.ProfileDto, error)
UpdateProfile(cinfo dto.ClientInfo, newProfile dto.ProfileDto) (bool, error)
UpdateProfile(cinfo dto.ClientInfo, newProfile dto.NewProfileDto) (bool, error)
GetProfileSettings(cinfo dto.ClientInfo) (*dto.ProfileSettingsDto, error)
UpdateProfileSettings(cinfo dto.ClientInfo, newProfileSettings dto.ProfileSettingsDto) (bool, error)
UploadAvatar(cinfo dto.ClientInfo, filePath string) (*string, error)
}
type profileServiceImpl struct {
@@ -47,6 +47,7 @@ type profileServiceImpl struct {
dbctx database.DbContext
redis *redis.Client
minio *minio.Client
s3 S3Service
}
func NewProfileService(_log *zap.Logger, _dbctx database.DbContext, _redis *redis.Client, _minio *minio.Client) ProfileService {
@@ -117,12 +118,12 @@ func (p *profileServiceImpl) GetProfileSettings(cinfo dto.ClientInfo) (*dto.Prof
}
// XXX: no validation for timestamps' allowed ranges
func (p *profileServiceImpl) UpdateProfile(cinfo dto.ClientInfo, newProfile dto.ProfileDto) (bool, error) {
func (p *profileServiceImpl) UpdateProfile(cinfo dto.ClientInfo, newProfile dto.NewProfileDto) (bool, error) {
helper, db, err := database.NewDbHelperTransaction(p.dbctx); if err != nil {
p.log.Error(
"Failed to open transaction",
zap.Error(err))
return false, err
return false, errs.ErrServerError
}
defer helper.Rollback()
@@ -131,11 +132,25 @@ func (p *profileServiceImpl) UpdateProfile(cinfo dto.ClientInfo, newProfile dto.
Valid: true,
}
var avatarUrl *string
if newProfile.AvatarUploadID != nil {
key, err := p.s3.SaveUpload(*newProfile.AvatarUploadID, "avatars"); if err != nil {
p.log.Error("Failed to save avatar",
zap.String("upload_id", *newProfile.AvatarUploadID),
zap.Error(err))
return false, errs.ErrServerError
}
urlObj := p.s3.GetLocalizedFileUrl(*key, "avatars")
avatarUrl = utils.NewPointer(urlObj.String())
}
err = db.TXlessQueries.UpdateProfileByUsername(db.CTX, database.UpdateProfileByUsernameParams{
Username: cinfo.Username,
Name: newProfile.Name,
Bio: newProfile.Bio,
Birthday: birthdayTimestamp,
AvatarUrl: avatarUrl,
}); if err != nil {
p.log.Error(
"Failed to update user profile",
@@ -193,8 +208,3 @@ func (p *profileServiceImpl) UpdateProfileSettings(cinfo dto.ClientInfo, newProf
return true, nil
}
// TODO: implement S3 before I can do anything with it
func (p *profileServiceImpl) UploadAvatar(cinfo dto.ClientInfo, filePath string) (*string, error) {
panic("unimplemented")
}

View File

@@ -19,8 +19,11 @@ package services
import (
"context"
"easywish/config"
minioclient "easywish/internal/minioClient"
"easywish/internal/utils"
"fmt"
"net/url"
"time"
"github.com/google/uuid"
@@ -28,21 +31,24 @@ import (
"go.uber.org/zap"
)
type UploadService interface {
GetAvatarUrl() (*string, *map[string]string, error)
GetImageUrl() (*string, *map[string]string, error)
type S3Service interface {
CreateAvatarUrl() (*string, *map[string]string, error)
CreateImageUrl() (*string, *map[string]string, error)
SaveUpload(uploadID string, bucket string) (*string, error)
GetLocalizedFileUrl(key string, bucket string) url.URL
}
type uploadServiceImpl struct {
type s3ServiceImpl struct {
minio *minio.Client
log *zap.Logger
avatarPolicy minio.PostPolicy
imagePolicy minio.PostPolicy
imagePolicy minio.PostPolicy
}
func NewUploadService(_minio *minio.Client, _log *zap.Logger) UploadService {
service := uploadServiceImpl{
func NewUploadService(_minio *minio.Client, _log *zap.Logger) S3Service {
service := s3ServiceImpl{
minio: _minio,
log: _log,
}
@@ -76,41 +82,88 @@ func NewUploadService(_minio *minio.Client, _log *zap.Logger) UploadService {
return &service
}
func (u *uploadServiceImpl) genUrl(policy minio.PostPolicy, prefix string) (*string, *map[string]string, error) {
func (s *s3ServiceImpl) genUrl(policy minio.PostPolicy, prefix string) (*string, *map[string]string, error) {
object := prefix + uuid.New().String()
if err := policy.SetKey(object); err != nil {
u.log.Error(
s.log.Error(
"Failed to set random key for presigned url",
zap.Error(err))
return nil, nil, err
}
url, formData, err := u.minio.PresignedPostPolicy(context.Background(), &policy)
url, formData, err := s.minio.PresignedPostPolicy(context.Background(), &policy)
if err != nil {
u.log.Error(
s.log.Error(
"Failed to generate presigned url",
zap.String("object", object),
zap.Error(err))
return nil, nil, err
}
convertedUrl, err := utils.LocalizeS3Url(url.String()); if err != nil {
u.log.Error(
convertedUrl, err := utils.LocalizeS3Url(url.String())
if err != nil {
s.log.Error(
"Failed to localize object URL to user-accessible format",
zap.String("url", url.String()),
zap.Error(err))
return nil, nil, err
}
return &convertedUrl, &formData, nil
return utils.NewPointer(convertedUrl.String()), &formData, nil
}
func (u *uploadServiceImpl) GetAvatarUrl() (*string, *map[string]string, error) {
return u.genUrl(u.avatarPolicy, "avatar-")
func (s *s3ServiceImpl) CreateAvatarUrl() (*string, *map[string]string, error) {
return s.genUrl(s.avatarPolicy, "avatar-")
}
func (u *uploadServiceImpl) GetImageUrl() (*string, *map[string]string, error) {
return u.genUrl(u.imagePolicy, "image-")
func (s *s3ServiceImpl) CreateImageUrl() (*string, *map[string]string, error) {
return s.genUrl(s.imagePolicy, "image-")
}
func (s *s3ServiceImpl) SaveUpload(uploadID string, bucketAlias string) (*string, error) {
sourceBucket := minioclient.Buckets["uploads"]
bucket := minioclient.Buckets[bucketAlias]
newObjectKey := uuid.New().String()
_, err := s.minio.CopyObject(context.Background(), minio.CopyDestOptions{
Bucket: bucket,
Object: newObjectKey,
}, minio.CopySrcOptions{
Bucket: sourceBucket,
Object: uploadID,
})
if err != nil {
s.log.Error(
"Failed to copy object to new bucket",
zap.String("sourceBucket", sourceBucket),
zap.String("uploadID", uploadID),
zap.String("destinationBucket", bucket),
zap.String("newObjectKey", newObjectKey),
zap.Error(err))
return nil, err
}
err = s.minio.RemoveObject(context.Background(), sourceBucket, uploadID, minio.RemoveObjectOptions{})
if err != nil {
s.log.Error(
"Failed to remove original object from uploads bucket",
zap.String("sourceBucket", sourceBucket),
zap.String("uploadID", uploadID),
zap.Error(err))
return nil, err
}
return &newObjectKey, nil
}
func (s *s3ServiceImpl) GetLocalizedFileUrl(key string, bucketAlias string) url.URL {
cfg := config.GetConfig()
return url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", cfg.Hostname, cfg.Port),
Path: fmt.Sprintf("/s3/%s/%s", minioclient.Buckets[bucketAlias], key),
}
}

View File

@@ -23,22 +23,23 @@ import (
"net/url"
)
func LocalizeS3Url(originalURL string) (string, error) {
// TODO: Move this method to s3 service
func LocalizeS3Url(originalURL string) (*url.URL, error) {
cfg := config.GetConfig()
newDomain := fmt.Sprintf("%s:%d", cfg.Hostname, cfg.Port)
parsedURL, err := url.Parse(originalURL)
if err != nil {
return "", fmt.Errorf("invalid URL: %w", err)
return nil, fmt.Errorf("invalid URL: %w", err)
}
newURL := &url.URL{
newURL := url.URL{
Scheme: parsedURL.Scheme,
Host: newDomain,
Path: "/s3" + parsedURL.Path,
RawQuery: parsedURL.RawQuery,
}
return newURL.String(), nil
return &newURL, nil
}

View File

@@ -110,6 +110,20 @@ func GetCustomHandlers() []CustomValidatorHandler {
panic(fmt.Sprintf("'%s' is not a valid verification code type", codeType))
}},
{
FieldName: "upload_id",
Function: func(fl validator.FieldLevel) bool {
uploadType := fl.Param()
uploadID := fl.Field().String()
pattern := fmt.Sprintf(
"^%s-([{(]?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})[})]?)$",
uploadType,
)
return regexp.MustCompile(pattern).MatchString(uploadID)
}},
}