From 283265c8c5800a074c6b662b73cce45374241117 Mon Sep 17 00:00:00 2001 From: John Costa Date: Fri, 11 Apr 2025 19:41:36 +0100 Subject: [PATCH] feat: checking user authorization on image retrieval --- backend/main.go | 29 ++++++++++++++++------------- backend/models/image.go | 9 +++++++++ 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/backend/main.go b/backend/main.go index 7f1deb8..e0b58e3 100644 --- a/backend/main.go +++ b/backend/main.go @@ -80,8 +80,6 @@ func main() { return } - log.Println(images) - type DataType struct { Type string `json:"type"` Data any `json:"data"` @@ -123,12 +121,24 @@ func main() { }) r.Get("/image/{id}", func(w http.ResponseWriter, r *http.Request) { - imageId := r.PathValue("id") + stringImageId := r.PathValue("id") + userId := r.Context().Value(USER_ID).(uuid.UUID) - _ = r.Context().Value(USER_ID).(uuid.UUID) + imageId, err := uuid.Parse(stringImageId) + if err != nil { + w.WriteHeader(http.StatusForbidden) + fmt.Fprintf(w, "You cannot read this") + return + } + + if authorized := imageModel.IsUserAuthorized(r.Context(), imageId, userId); !authorized { + w.WriteHeader(http.StatusForbidden) + fmt.Fprintf(w, "You cannot read this") + return + } // TODO: really need authorization here! - image, err := imageModel.Get(r.Context(), uuid.MustParse(imageId)) + image, err := imageModel.Get(r.Context(), imageId) if err != nil { log.Println(err) w.WriteHeader(http.StatusNotFound) @@ -146,12 +156,7 @@ func main() { r.Post("/image/{name}", func(w http.ResponseWriter, r *http.Request) { imageName := r.PathValue("name") - - userId := r.Header.Get("userId") - - w.Header().Add("Access-Control-Allow-Origin", "*") - w.Header().Add("Access-Control-Allow-Credentials", "*") - w.Header().Add("Access-Control-Allow-Headers", "*") + userId := r.Context().Value(USER_ID).(uuid.UUID) if len(imageName) == 0 { w.WriteHeader(http.StatusBadRequest) @@ -161,8 +166,6 @@ func main() { contentType := r.Header.Get("Content-Type") - log.Println(contentType) - // TODO: length checks on body // TODO: extract this shit out image := make([]byte, 0) diff --git a/backend/models/image.go b/backend/models/image.go index 894c579..a0c29f7 100644 --- a/backend/models/image.go +++ b/backend/models/image.go @@ -147,6 +147,15 @@ func (m ImageModel) Get(ctx context.Context, imageId uuid.UUID) (ImageData, erro return images[0], err } +func (m ImageModel) IsUserAuthorized(ctx context.Context, imageId uuid.UUID, userId uuid.UUID) bool { + getImageUserId := UserImages.SELECT(UserImages.UserID).WHERE(UserImages.ImageID.EQ(UUID(imageId))) + + userImage := model.UserImages{} + err := getImageUserId.QueryContext(ctx, m.dbPool, &userImage) + + return err != nil && userImage.UserID.String() == userId.String() +} + func NewImageModel(db *sql.DB) ImageModel { return ImageModel{dbPool: db} }