Display Roles in 'Logged in as...' Text in the Info Bar

As a user, you might want to see what role you’re logged in as.

Here’s a quick snippet that will append your user role to the “Logged in as…” text.

Before:
before

After:

Copy-paste the following code in your app under Settings > API & Code > JavaScript.

// On all scenes
$(document).on('knack-scene-render.any', function(event, scene) {
  showRoleInsideInfoBar()
})

// Function to show user roles in 'Logged in as...' text in the Info Bar
function showRoleInsideInfoBar() {
  if (loggedIn()) {
    const str = getRoles()
    updateInfoBar(str)
  }

  function loggedIn() {
    return Knack.getUserAttributes().id
  }

  function getRoles() {
    const roles = Knack.getUserAttributes().roles // e.g. ['object_1', 'object_2']
    let str = ''
    for (let i = 0; i < roles.length; i++) {
      if (roles.length > 1 && i > 0) str += ', '
      str += Knack.objects.models.find(object => object.attributes.key === roles[i]).attributes.inflections.singular
    }
    return str
  }

  function updateInfoBar(str) {
    const $currentUser = $('.kn-current_user')
    if ($currentUser.hasClass('has-roles')) return
    const $lastName = $currentUser.find('.last')
    $lastName.text(`${$lastName.text()} (${str})`)
    $currentUser.addClass('has-roles')
  }
}

Nice snippet @KnackPros :muscle:

Love it. Was wishing for something like this last week!
Thanks!

Is it possible this does not work anymore whith Next Gen version of Knack?

This works in Knack Classic because Classic uses jQuery and fires those knack-scene-render events, and the page structure stays fairly static so you can tweak the Info Bar directly. Next Gen is built very differently using React, so there’s no jQuery, those events don’t exist, and the UI constantly re-renders, which means this kind of direct DOM manipulation won’t stick or run at all. Unfortunately I’m not a coder, so I can’t help with rewriting this for Next Gen, but hopefully this explains why the same code won’t work in both.