Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Using Access function with custom User interface

default discord avatar
Martin Törnros2 years ago
1

When using Access Controls I can for example create a function

isSuperAdmin

to only let users with a certain role create new content, like.



const isSuperAdmin: Access<any, User> = ({req: {user}}) => {
  return (user?.role?.value as Role).hierarchy <= 1
}

and


access: {
    create: isSuperAdmin,
    ...

and within the function,

user

would be recognised and typed as a

User

.



How could I achieve the same without having to create a separate function? The following code works but in the editor the

user

variable is typed as

any

(not

User

) hence not recognising the

role

field:


create: ({req: {user}}) => {
      return (user?.role?.value as Role).hierarchy <= 1
    }

I realise I'd probably have to specify

Access<any, User>

(or, at least

User

somewhere) but I can't figure out where.



(I'm aware that creating a function is good for reusability, but the admin case is just an example. Please ignore the reusability aspect when answering the question)



Thanks!



Solution:


create: ({req: {user}}) => {
  return ((user as User)?.role?.value as Role).hierarchy <= 1
}
    Star on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get dedicated engineering support directly from the Payload team.