Created
July 26, 2023 15:10
-
-
Save sdjnes/b63e025496cdd0961359f6b03f705425 to your computer and use it in GitHub Desktop.
Payload access control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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