Prevent users from accessing admin panel

default discord avatar
mosattlerlast year
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?

  • default discord avatar
    mosattlerlast year

    @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
    last year

    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
    mosattlerlast year

    @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
    last year

    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
    mosattlerlast year

    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
    last year

    On your user collection, like this:



    {
      slug: 'users',
      auth: true,
      access: {
        admin: admins
      }
    }
  • default discord avatar
    mosattlerlast year

    ahhh



    i really missed the obvious here, didnt I



    thank you so much!

  • discord user avatar
    jacobsfletch
    last year

    No prob!

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.