Authorized queries & mutations (patch, delete, get)
Hi, me again 👋
I am looking for a way to authorize, not just authenticate before fetching / removing / patching a single record.
As I understood from the documentation, functions like
.get() .patch() .delete()
all take one argument, the id of the record to fetch / modify.
I am looking into a way to confirm that the currently logged in user can only do this for records they created / own.
I've come up with a following solution (picture attachment):
I make use of .query()
, .withIndex()
and .unique()
to confirm the logged in userId matches record's userId.
I am wondering if this is the correct way of doing it + would this be a candidate for an internal function?
Thanks!4 Replies
Hi! Doing the access checks like you describe sound like a good way to go about it. The code you linked would work, but it's not as efficient as doing a
db.get
and then throwing an error if the userId
field doesn't match. We have a stack post, with a library you can use, that sounds like what you're looking for: https://stack.convex.dev/row-level-securityRow Level Security: Wrappers as "Middleware"
Implementing row-level security on Convex as a library. Wrap access to the database with access checks written in plain old JS / TS.
Awesome! Checking it out now, thank you!
hi antonio 👋
i am a suscriber of yours on Youtube and also a member of your discord channel 🤗love your work by the way, you have taught me so much 🙏....just wanted to know if you are planning on using convex for the Notion clone or some other project ?
To offer an alternative to the RLS "middleware"-style approach:
You can write helper functions that do related autho checks. E.g. a function that takes in a document and a user and validates that user can insert / read / write / comment / etc.
The upside of this is that it's very flexible. You can make helpers that fetch documents while doing checks, have nuanced rules that depend on other document fetches (e.g. is the user part of a team that generally has read-only permissions for a page).
Since these functions are running server-side, you can trust that a user won't circumvent the checks. However, it puts the responsibility on the developer to do the access checks. The RLS approach is better in that respect: as long as your endpoint is using the RLS wrapper, it will automatically filter out documents that the user doesn't have access to.