Access Control for a collection when authenticated against specific collection only #185
-
My apologies about this question, as it may be something that's clearly answered in the docs. I have two user collections: I'd like to make it so admins could see the list of all other admins, where standard users shouldn't have this functionality. I see in the docs for Access Control it says:
Based on this, I think a query constraint is what I need, however, I get a little lost regarding how to specify a query that says "show me this collection ONLY if I'm in an admin list." As it stands today, I can see the admins collection whether I'm logged in as a standard user or an admin, instead of admin only. One other thing I tried is to perform a payload.query inside the access control function, but that seemed to cause errors due to the async / promises. Any thoughts on how to achieve this would be greatly appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @ryanlanciaux, thanks for the question. You were definitely on the right track. We could probably explain this more and add examples of this in the documentation. Here is an example of doing what you describe: You can see from the code that if the user is in the const userAccess = ({ req: { user } }) => {
if (user) {
if (user.collection === 'admins') {
return true;
}
if (user.collection === 'users') {
return {
id: {
equals: user.id,
},
};
}
}
return false;
};
export { userAccess }; If you put that code in a separate file, then import it - you'd use it in your collection like this: access: {
admin: () => true, // Allow access to admin panel
read: userAccess,
update: userAccess,
}, You may also consider having a similar function for Hopefully, this helps. Let me know if there are any issues running that code 👍 |
Beta Was this translation helpful? Give feedback.
Hey @ryanlanciaux, thanks for the question. You were definitely on the right track. We could probably explain this more and add examples of this in the documentation. Here is an example of doing what you describe:
You can see from the code that if the user is in the
admins
collection it will returntrue
, indicating access to all. However, if the user is in theusers
collection, a query constraint is returned that will return only documents with that user'sid
.