Skip to content

Instantly share code, notes, and snippets.

@sdjnes
Created July 26, 2023 15:10
Show Gist options
  • Save sdjnes/b63e025496cdd0961359f6b03f705425 to your computer and use it in GitHub Desktop.
Save sdjnes/b63e025496cdd0961359f6b03f705425 to your computer and use it in GitHub Desktop.
Payload access control
import { User } from 'payload/dist/auth';
import { Access, AccessArgs, FieldAccess } from 'payload/types';
type CheckerArgs = {
user?: User;
id?: string | number;
};
type Checker = (args: CheckerArgs) => boolean;
const isAdmin: Checker = ({ user }) => user?.role && user?.role === 'admin';
const isDeveloper: Checker = ({ user }) =>
user?.role && user?.role === 'developer';
const isDesigner: Checker = ({ user }) =>
user?.role && user?.role === 'designer';
const isContentEditor: Checker = ({ user }) =>
user?.role && user?.role === 'contentEditor';
const isServiceAccount: Checker = ({ user }) =>
user?.role && user?.role === 'serviceAccount';
const isLoggedInUser: Checker = ({ user }) => !!user;
const isSelf: Checker = ({ user, id }) => !!id && user?.id === id;
const not =
(fn: Checker): Checker =>
(args: CheckerArgs) =>
!fn(args);
const or =
(...checkers: Array<Checker>): Checker =>
(args: CheckerArgs) =>
checkers.some((checker) => !!checker(args));
const and =
(...checkers: Array<Checker>): Checker =>
(args: CheckerArgs) =>
checkers.every((checker) => !!checker(args));
const access =
(checker: Checker): Access & FieldAccess =>
(args: AccessArgs<any, any>) =>
checker({ user: args.req.user, id: args.id });
export {
and,
or,
not,
isAdmin,
isDesigner,
isDeveloper,
isContentEditor,
isServiceAccount,
isLoggedInUser,
isSelf,
access,
type CheckerArgs,
};
// Collection access
access: {
...,
update: access(and(isLoggedInUser, not(isServiceAccount))),
...
}
// Collection hidden
admin: {
hidden: isContentEditor,
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment