How to get entire user object?

default discord avatar
jokillinger2 years ago
1 1

I have a collection of admin users with email, name and role properties modeled after the example in the payload-demo.

	fields: [
		// Email added by default
		{
			name: 'name',
			type: 'text',
		},
		{
			name: 'roles',
			label: 'Role(s)',
			type: 'select',
			options: roles,
			required: true,
			saveToJWT: true,
			hasMany: true,
		}
	],

The problem is, that I can not access the role property in the req.user object that is passed to the access properties. It only contains name and collection. What do I have to do to pass the entire user object to the req object?
Many thanks in advance.

  • Selected Answer
    discord user avatar
    DanRibbens
    2 years ago

    Interesting, you shouldn't have to do anything extra to pass the full user object in an access function. I would try:

    1. Check your database user document to make sure the role is persisted on the user
    2. Logout and log back in
    3. Can you share your access function here? maybe we've overlooking something in how the access function is being called.

    If you want to share a repo with me I'll try it out too.

    You probably saw in the demo where we have our access function example. https://github.com/payloadcms/payload/blob/master/demo/collections/Admin.ts#L5

    const access = ({ req: { user } }) => {
      return checkRole(['admin'], user);
    };

    With that we call checkRole: https://github.com/payloadcms/payload/blob/master/demo/access/checkRole.ts

    const checkRole = (allRoles, user) => {
      if (user) {
        if (allRoles.some((role) => user.roles && user.roles.some((individualRole) => individualRole === role))) {
          return true;
        }
      }

    We're able to use the user.role in the access functions on fields and collections. We also use that same function in the allFields collection to demonstrate access control on a non-auth collection field.

    Is that helpful? If not we'll get you on track.

    1 reply
  • default discord avatar
    jokillinger2 years ago

    I found the error. This hook was copied from the blog example while testing different things.

    hooks: {
    	beforeRead: [onlyNameIfPublic]
    },

    It works now. Thank you for your help.

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.