Add to serializer only for staff and current user

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.

1 Like

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.

3 Likes

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.

1 Like

You could try an additional serializer call like this:

https://github.com/discourse/discourse-intercom/blob/22bdd11e1eb4ef284a86b6e5a36fcf0bf5990d4e/plugin.rb#L9

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

3 Likes

@pfaffman Did you find a solution for this?

Thanks!

1 Like

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

2 Likes

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?
  }
3 Likes