0

I'm using the "Viewer pattern" to fetch images that belong to the authenticated user:

type Query {
  me: User! @auth
}

type User {
  name: String!
  images: [Image] @hasMany
}

And I fetch with:

{
  me {
    images {
      id
      url
    }
  }
}

This all works well, but it returns me all the images from the user.

My question is: How to get a single image from the authenticated user by its ID?

I tried this:

type User {
  name: String!
  images: [Image] @hasMany

  "Fetch image by its ID"
  image(id: ID @eq): Image @find
}

And I fetch with:

{
  me {
    image(id: 4) {
      id
      url
    }
  }
}

While this works, it creates a huge security issue. Anyone logged in can access any image from any user.

I tried to mix @find and @whereAuth but I got this

exception:

Call to a member function getRelationExistenceQuery() on null

Ideas?

Daniel Loureiro
  • 4,595
  • 34
  • 48

1 Answers1

0

I found what I was doing wrong. The @whereAuth needs a parameter:

type User {
  name: String!
  images: [Image] @hasMany

  "Fetch image by its ID"
  image(id: ID @eq): Image @find @whereAuth(relation: "user")
}

Alternatively, you can replace @find with @where + @first:

type User {
  name: String!
  images: [Image] @hasMany

  "Fetch image by its ID"
  image(id: ID @where): Image @whereAuth(relation: "user") @first
}

And of course, there's always the alternative of using Policies.

Daniel Loureiro
  • 4,595
  • 34
  • 48