From d11cd042b726b8687e7c0ccac71e93ea6c59c64b Mon Sep 17 00:00:00 2001 From: Benjamin Bertrand <benjamin.bertrand@esss.se> Date: Tue, 19 Dec 2017 09:12:12 +0100 Subject: [PATCH] Filter networks for non admin users When registering a new host, only admin users shall be able to select networks marked as "admin_only" --- app/network/forms.py | 8 +++++++- app/utils.py | 6 ++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/network/forms.py b/app/network/forms.py index dc750f6..f3ba1e8 100644 --- a/app/network/forms.py +++ b/app/network/forms.py @@ -9,6 +9,7 @@ This module defines the network blueprint forms. :license: BSD 2-Clause, see LICENSE for more details. """ +from flask_login import current_user from flask_wtf import FlaskForm from wtforms import (SelectField, StringField, TextAreaField, SelectMultipleField, BooleanField, validators) @@ -82,6 +83,11 @@ class HostForm(FlaskForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.item_id.choices = utils.get_model_choices(models.Item, allow_none=True, attr='ics_id') - self.network_id.choices = utils.get_model_choices(models.Network, allow_none=False, attr='vlan_name') + if current_user.is_admin: + network_query = models.Network.query + else: + network_query = models.Network.query.filter(models.Network.admin_only.is_(False)) + self.network_id.choices = utils.get_model_choices(models.Network, allow_none=False, + attr='vlan_name', query=network_query) self.mac_id.choices = utils.get_model_choices(models.Mac, allow_none=True, attr='address') self.tags.choices = utils.get_model_choices(models.Tag, allow_none=True, attr='name') diff --git a/app/utils.py b/app/utils.py index 232cc52..67128fa 100644 --- a/app/utils.py +++ b/app/utils.py @@ -107,12 +107,14 @@ def get_choices(iterable, allow_blank=False, allow_null=False): return choices -def get_model_choices(model, allow_none=False, attr='name'): +def get_model_choices(model, allow_none=False, attr='name', query=None): """Return a list of (value, label)""" choices = [] if allow_none: choices = [(None, '')] - choices.extend([(str(instance.id), getattr(instance, attr)) for instance in model.query.all()]) + if query is None: + query = model.query + choices.extend([(str(instance.id), getattr(instance, attr)) for instance in query.all()]) return choices -- GitLab