Prevent users from accessing admin panel

default discord avatar
mosattler
7 months ago
9

How do i define which loged in users can access the admin, and which cannot?



Do I need two seperate user collections (one for admin, one for regular user), or can I add a flag to my user collection for indicating admins?

  • discord user avatar
    jacobsfletch
    Payload Team
    7 months ago
  • default discord avatar
    mosattler
    7 months ago

    @jacobsfletch this makes me think that i need two seperate collections for users and for admins, is that correct?



    (as in, i can "assign" one collection to be the admin collection, and I cannot make this assignment on a per-user level)

  • discord user avatar
    jacobsfletch
    Payload Team
    7 months ago

    You could still use a single collection and implement role or user-based access control



    You can either assign a roles select field on the user and check that in your access control function, here's example of that

    https://github.com/payloadcms/template-ecommerce/blob/main/src/access/admins.ts


    Or go even simpler and just add a checkbox to the user and check

    that
  • default discord avatar
    mosattler
    7 months ago

    @jacobsfletch that is super helpful. thansk a bunch!



    sorry @jacobsfletch - one more question regarding this. How do i limit the access to the admin pabel based on a checkbox like that?



    as in, I dont want normal users being able to login in

    /admin
  • discord user avatar
    jacobsfletch
    Payload Team
    7 months ago

    Add a

    canAccessAdmin

    checkbox field to the user collection and then in your

    access.admin

    hook, do something like this:


    export const admins: Access = ({ req: { user } }) => user.canAccessAdmin
  • default discord avatar
    mosattler
    7 months ago

    makes sense, but what i dont quite understand is where to use the

    const Admins

    of your example after I defined it.

  • discord user avatar
    jacobsfletch
    Payload Team
    7 months ago

    On your user collection, like this:



    {
      slug: 'users',
      auth: true,
      access: {
        admin: admins
      }
    }
  • default discord avatar
    mosattler
    7 months ago

    ahhh



    i really missed the obvious here, didnt I



    thank you so much!

  • discord user avatar
    jacobsfletch
    Payload Team
    7 months ago

    No prob!

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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