feat: checking user authorization on image retrieval
This commit is contained in:
@ -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)
|
||||
|
@ -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}
|
||||
}
|
||||
|
Reference in New Issue
Block a user