Skip to content
Snippets Groups Projects
Commit d11cd042 authored by Benjamin Bertrand's avatar Benjamin Bertrand
Browse files

Filter networks for non admin users

When registering a new host, only admin users shall be able to select
networks marked as "admin_only"
parent 7e170a8b
No related branches found
No related tags found
No related merge requests found
......@@ -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')
......@@ -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
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment