Limiting find results using access

default discord avatar
zillion50411 months ago

I have an application where users can log in and create journal entries. There are two user roles, "user" and "admin". I have coded the read access for journal entries as follows


export const isAdminOrCreatedBy = ({ req }: AccessArgs) => {
  // Allow admins
  if (isAdmin({ req })) return true;

  const user = req?.user as User;
  if (!user) return false;

  // Normal users can only access ones they own.
  return {
    createdBy: {
      equals: user.id,
    }
  };
};

When I run a find as a non-admin user, it will show me only entries that I own. However, as an admin it will show me every entry. In my application I don't want admin users to see all entries, I just want them to see their own. However, I do want them to see all of the entries when they're in the payload admin dashboard.



Obvious solution is to do some client-filtering in the application. However, I am wondering if anyone has suggestions for other approaches. Is there any way to do this with access control? Ideally I want the admin check to only happen if you're in the admin dashboard. Are there any methods for checking this? I can think of maybe viewing the Origin header of the request?



I found the following solution, changing my isAdmin check to disallow admin privileges from the web app:


const applicationOrigins: RegExp[] = [
  /^https?:\/\/localhost:3000/,
  /^https?:\/\/site\.com/
]

export const isAdmin = ({ req }: AccessArgs) => {
  // If the user is on the web app, do not use admin privileges.
  const origin = req.headers.origin;
  if (origin && applicationOrigins.find((appOrigin) => appOrigin.test(origin))) {
    return false;
  }

  const user = req.user as User;

  return user?.role === "admin";
};
    Star on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get help straight from the Payload team with an Enterprise License.