Flask-User icon indicating copy to clipboard operation
Flask-User copied to clipboard

Enhancement for roles

Open zerc opened this issue 9 years ago • 0 comments

Hi everyone,

Sometimes may be useful to know about rights (roles) of a user for a particular view by its URL.

Something like this:

{% if current_user.can_view('myapp.list_objects') %}
  <a href="{{ url_for('myapp.list_objects') }}">Link</a>
{% endif %}

Of course, we can write:

{% if current_user.has_roles('role1', 'role2') %}
...

And then for a view:

@myapp.route('/list')
@roles_required('role1', 'role2')
def list_objects():
    ...

But in this case, we have a duplicate list of roles and we need to maintain these two pieces.

I propose are two things:

  • Modify the @roles_required decorator for tracking views and their roles, e.g. like this:
def roles_required(*role_names):
    def wrapper(func):
        func.ROLES = role_names
        @wraps(func)
        def decorated_view(*args, **kwargs):
            ...
  • Add UserMixin.has_roles_for_view method. Something like this:
def has_roles_for_view(self, url):
    default = True  # If it's not deny - is allow
    try:
        view_func = app.view_functions['users.users_list']
    except KeyError:
        return default
    roles = getattr(view_func, 'ROLES', None)
    if roles is None:
        return default
    return self.has_roles(*roles)

I can prepare PR with these changes if needed.

zerc avatar Jan 24 '16 16:01 zerc