Search code examples
python-2.7google-app-enginejinja2google-identity

Appengine users and admins - render template elements depending on user type


I am using the Google Identity platform for Python and I have two types of users - Provider and Consultant. Both will have an account in the Google Apps domain.

In order to separate my app workflows I think

  • Provider should be a regular user

  • Consultant should be an admin user

Admin users are discussed here: https://cloud.google.com/appengine/docs/standard/python/users/adminusers

I have a basic understanding that is_current_user_admin() provides a test if the current user is of type admin (and therefore a consultant in my app).

There are things I wish to display on particular pages differently depending on the user type.

For example how would I display the "Insert Assessment" link only to the admin in the following dropdown menu, and not to the non-admin users:

<div class="btn-group pull-right">
  <button type="button" class="btn btn-danger">Consult Actions</button>
  <button type="button" class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
  <span class="sr-only">Toggle Dropdown</span>
  </button>
  <div class="dropdown-menu">
    <a class="dropdown-item" href="#">Edit Consult</a>
    <a class="dropdown-item" href="#">Cancel Consult</a>
  <div class="dropdown-divider"></div>
    <a class="dropdown-item" href="/schedule/insert-assessment?key={{consult.key.urlsafe()}}">Insert Assessment</a>
  </div>
</div>

Edit: define admin variable ...?

def get(self):
        consult_key = ndb.Key(urlsafe=self.request.get('key'))
        consult = consult_key.get()
        # assessment and consult have the same key ID
        assessment = Assessments.get_by_id(consult_key.id())
        template = JINJA_ENVIRONMENT.get_template('/templates/view-consult.html')
        template_values = {
        'consult': consult,
        'assessment': assessment
        'admin': user is not None and user.is_current_user_admin()
        }
        self.response.out.write(template.render(template_values))

Solution

  • You have a problem that divides into two separate subproblems: How do you display text in a template conditionally, and how do you tell if the current user is an admin.

    The first problem is solved with the {% if %} tag. E.g, by

    {% if admin %}
    <div class="dropdown-divider"></div>
      <a class="dropdown-item" href="/schedule/insert-assessment?key={{consult.key.urlsafe()}}">Insert Assessment</a>
    </div>
    {% endif %}
    

    The second problem is how to set the value of the admin variable. For that you can borrow code on the page you linked to, and use something like

    'admin': user is not None and user.is_current_user_admin()
    

    when you render the template.