Add to serializer only for staff and current user

AI-generated summary

The discussion revolves around adding custom data to the user serializer in Discourse, but only for staff and the current user. pfaffman initially needs to add a manager_status field to the user serializer, but only wants it to appear for staff and the current user. justin suggests creating a separate profile page for the data, but also provides a potential solution using object.admin || object.staff in the serializer.

However, pfaffman notes that this approach will only work for the user being serialized, not the current user. justin suggests using an additional serializer call to access the current user object.

Later, paresy asks if a solution was found, and pfaffman suggests trying the approach mentioned earlier. paresy eventually finds a working solution using scope.is_staff? to check if the current user is staff, and shares the code snippet.

I’m working on a plugin that needs to add stuff to the user serializer. It’s working! :tada:

But I need to add it to the user serializer only for staff and the current user.

But . . . backing up, perhaps, I really need this information only on the user profile page, so perhaps I need to put it somewhere else?

  add_to_serializer(:user, :manager_status) {
    # TODO: include only for current user and staff
    return object.manager_status
  }

I’m currently displaying this on the user profile page. I’d like to know how to create a separate profile page with just this stuff on it. Links to something doing that would be great.

You’d have to create a new route and make sure it’s guarded against anyone but staff and the current user from seeing it. Probably a lot more complex than serializing it where you are.

I’m thinking you can do this via something like so:

  add_to_serializer(:user, :manager_status) {
    return object.manager_status if object.admin || object.staff
  }

Off the top of my head you may have to do a dance to pull in the current user object and check for a match.

yeah. I can’t figure out how to get the current user. I think what you have will add it if the user (but not the current user) is an admin.

You could try an additional serializer call like this:

I haven’t tested this so you’ll want to make sure it’s secured as you need.

@pfaffman Did you find a solution for this?

Thanks!

I don’t remember, but I think the above should work.

This seem to be the droids i was looking for :slight_smile:

  add_to_serializer(:post, :user_xxx, false) {
    #object.user.custom_fields['xxx'] if object.user && scope.is_admin?
    #object.user.custom_fields['xxx'] if object.user && scope.is_moderator?

    # Staff will allow for Admins and Moderators
    object.user.custom_fields['xxx'] if object.user && scope.is_staff?
  }