Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding inaccessible links in Jinja2 templates

We're writing a web application in Flask + Jinja2 at work. The application has registered users which can access certain pages based on their roles. In order to achieve this on the server side we just use decorate the pages:

@app.route('/action1')
@security_requirements(roles=['some_role'])
def action1():
    ...

The decorator checks if the logged on user has 'some_role' in its role list and decides whether to pass the call to the decorated function or just redirect the user to the "access denied" page.

The application also has a navigation bar implemented using bootstrap. The navigation bar is displayed in each page using a base template. As for now, every page in the application has an entry in the navigation bar, regardless if the current user can access it or not. Despite the fact that this is not a security hole, I would like to hide from users pages which they cannot access. Furthermore, I would like to achieve this functionality without duplicating the allowed roles lists inside the Jinja templates. Is it possible to achieve this functionality in Jinja somehow by using my current decorator?

like image 262
reish Avatar asked Nov 25 '13 12:11

reish


1 Answers

I use Flask-Security, which ties a lot of the login/security modules together in a nice package. It comes with role management courtesy of Flask-Principal, which will allow you to do:

{% if current_user.has_role('admin') %}
    <li><a href="#">Manage Site</a></li>
{% endif %}

You can see how that's implemented in the source, the current_user proxy comes from Flask-Login

like image 144
Doobeh Avatar answered Oct 01 '22 05:10

Doobeh