8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-11-27 15:12:25 +00:00

No need for preferences/utils

This commit is contained in:
Hugo Levy-Falk 2020-04-22 19:35:45 +02:00 committed by Gabriel Detraz
parent 6ca39663d6
commit 721c0a1a19
7 changed files with 80 additions and 147 deletions

View file

@ -37,14 +37,36 @@ from django.utils.translation import ugettext_lazy as _
import machines.models import machines.models
from .utils.models import PreferencesModel
from re2o.mixins import AclMixin, RevMixin from re2o.mixins import AclMixin, RevMixin
from re2o.aes_field import AESEncryptedField from re2o.aes_field import AESEncryptedField
from datetime import timedelta from datetime import timedelta
class PreferencesModel(models.Model):
""" Base object for the Preferences objects
Defines methods to handle the cache of the settings (they should
not change a lot) """
@classmethod
def set_in_cache(cls):
""" Save the preferences in a server-side cache """
instance, _created = cls.objects.get_or_create()
cache.set(cls().__class__.__name__.lower(), instance, None)
return instance
@classmethod
def get_cached_value(cls, key):
""" Get the preferences from the server-side cache """
instance = cache.get(cls().__class__.__name__.lower())
if instance is None:
instance = cls.set_in_cache()
return getattr(instance, key)
class Meta:
abstract = True
class OptionalUser(AclMixin, PreferencesModel): class OptionalUser(AclMixin, PreferencesModel):
"""Options pour l'user : obligation ou nom du telephone, """Options pour l'user : obligation ou nom du telephone,
activation ou non du solde, autorisation du negatif, fingerprint etc""" activation ou non du solde, autorisation du negatif, fingerprint etc"""
@ -54,7 +76,12 @@ class OptionalUser(AclMixin, PreferencesModel):
ALL_ROOM = "ALL_ROOM" ALL_ROOM = "ALL_ROOM"
ROOM_POLICY = ( ROOM_POLICY = (
(DISABLED, _("Users can't select their room")), (DISABLED, _("Users can't select their room")),
(ONLY_INACTIVE, _("Users can only select a room occupied by a user with a disabled connection.")), (
ONLY_INACTIVE,
_(
"Users can only select a room occupied by a user with a disabled connection."
),
),
(ALL_ROOM, _("Users can select all rooms")), (ALL_ROOM, _("Users can select all rooms")),
) )
@ -76,7 +103,7 @@ class OptionalUser(AclMixin, PreferencesModel):
max_length=32, max_length=32,
choices=ROOM_POLICY, choices=ROOM_POLICY,
default="DISABLED", default="DISABLED",
help_text=_("Policy on self users room edition") help_text=_("Policy on self users room edition"),
) )
local_email_accounts_enabled = models.BooleanField( local_email_accounts_enabled = models.BooleanField(
default=False, help_text=_("Enable local email accounts for users.") default=False, help_text=_("Enable local email accounts for users.")
@ -92,9 +119,7 @@ class OptionalUser(AclMixin, PreferencesModel):
) )
delete_notyetactive = models.IntegerField( delete_notyetactive = models.IntegerField(
default=15, default=15,
help_text=_( help_text=_("Not yet active users will be deleted after this number of days."),
"Not yet active users will be deleted after this number of days."
),
) )
disable_emailnotyetconfirmed = models.IntegerField( disable_emailnotyetconfirmed = models.IntegerField(
default=2, default=2,
@ -195,7 +220,7 @@ class OptionalTopologie(AclMixin, PreferencesModel):
DEFINED = "DEFINED" DEFINED = "DEFINED"
CHOICE_RADIUS = ( CHOICE_RADIUS = (
(MACHINE, _("On the IP range's VLAN of the machine")), (MACHINE, _("On the IP range's VLAN of the machine")),
(DEFINED, _("Preset in \"VLAN for machines accepted by RADIUS\"")), (DEFINED, _('Preset in "VLAN for machines accepted by RADIUS"')),
) )
CHOICE_PROVISION = (("sftp", "SFTP"), ("tftp", "TFTP")) CHOICE_PROVISION = (("sftp", "SFTP"), ("tftp", "TFTP"))
@ -335,7 +360,9 @@ class OptionalTopologie(AclMixin, PreferencesModel):
) )
class Meta: class Meta:
permissions = (("view_optionaltopologie", _("Can view the topology preferences")),) permissions = (
("view_optionaltopologie", _("Can view the topology preferences")),
)
verbose_name = _("topology preferences") verbose_name = _("topology preferences")
@ -546,7 +573,9 @@ class Mandate(RevMixin, AclMixin, models.Model):
) )
if not mandate: if not mandate:
raise cls.DoesNotExist( raise cls.DoesNotExist(
_("No mandates have been created. Please go to the preferences page to create one.") _(
"No mandates have been created. Please go to the preferences page to create one."
)
) )
return mandate return mandate
@ -653,7 +682,7 @@ class RadiusOption(AclMixin, PreferencesModel):
DEFINED = "DEFINED" DEFINED = "DEFINED"
CHOICE_RADIUS = ( CHOICE_RADIUS = (
(MACHINE, _("On the IP range's VLAN of the machine")), (MACHINE, _("On the IP range's VLAN of the machine")),
(DEFINED, _("Preset in \"VLAN for machines accepted by RADIUS\"")), (DEFINED, _('Preset in "VLAN for machines accepted by RADIUS"')),
) )
REJECT = "REJECT" REJECT = "REJECT"
SET_VLAN = "SET_VLAN" SET_VLAN = "SET_VLAN"

View file

@ -1,55 +0,0 @@
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2020 Gabriel Détraz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# App de gestion des machines pour re2o
# Gabriel Détraz, Augustin Lemesle
# Gplv2
"""
Utils for preferences
"""
from __future__ import unicode_literals
from django.core.cache import cache
from django.db import models
class PreferencesModel(models.Model):
""" Base object for the Preferences objects
Defines methods to handle the cache of the settings (they should
not change a lot) """
@classmethod
def set_in_cache(cls):
""" Save the preferences in a server-side cache """
instance, _created = cls.objects.get_or_create()
cache.set(cls().__class__.__name__.lower(), instance, None)
return instance
@classmethod
def get_cached_value(cls, key):
""" Get the preferences from the server-side cache """
instance = cache.get(cls().__class__.__name__.lower())
if instance is None:
instance = cls.set_in_cache()
return getattr(instance, key)
class Meta:
abstract = True

View file

@ -1,68 +0,0 @@
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2020 Gabriel Détraz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# App de gestion des machines pour re2o
# Gabriel Détraz, Augustin Lemesle
# Gplv2
"""
Utils for preferences
"""
from __future__ import unicode_literals
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib import messages
from django.db.models import ProtectedError
from django.db import transaction
from django.utils.translation import ugettext as _
from reversion import revisions as reversion
from re2o.views import form
def edit_options_template_function(request, section, forms, models):
""" Edition des préférences générales"""
model = getattr(models, section, None)
form_instance = getattr(forms, "Edit" + section + "Form", None)
if not (model or form_instance):
messages.error(request, _("Unknown object."))
return redirect(reverse("preferences:display-options"))
options_instance, _created = model.objects.get_or_create()
can, msg, permissions = options_instance.can_edit(request.user)
if not can:
messages.error(request, acl_error_message(msg, permissions))
return redirect(reverse("index"))
options = form_instance(
request.POST or None, request.FILES or None, instance=options_instance
)
if options.is_valid():
with transaction.atomic(), reversion.create_revision():
options.save()
reversion.set_user(request.user)
reversion.set_comment(
"Field(s) edited: %s"
% ", ".join(field for field in options.changed_data)
)
messages.success(request, _("The preferences were edited."))
return redirect(reverse("preferences:display-options"))
return form({"options": options}, "preferences/edit_preferences.html", request)

View file

@ -86,7 +86,35 @@ from .models import (
from . import models from . import models
from . import forms from . import forms
from .utils.views import edit_options_template_function
def edit_options_template_function(request, section, forms, models):
""" Edition des préférences générales"""
model = getattr(models, section, None)
form_instance = getattr(forms, "Edit" + section + "Form", None)
if not (model or form_instance):
messages.error(request, _("Unknown object."))
return redirect(reverse("preferences:display-options"))
options_instance, _created = model.objects.get_or_create()
can, msg, permissions = options_instance.can_edit(request.user)
if not can:
messages.error(request, acl_error_message(msg, permissions))
return redirect(reverse("index"))
options = form_instance(
request.POST or None, request.FILES or None, instance=options_instance
)
if options.is_valid():
with transaction.atomic(), reversion.create_revision():
options.save()
reversion.set_user(request.user)
reversion.set_comment(
"Field(s) edited: %s"
% ", ".join(field for field in options.changed_data)
)
messages.success(request, _("The preferences were edited."))
return redirect(reverse("preferences:display-options"))
return form({"options": options}, "preferences/edit_preferences.html", request)
@login_required @login_required
@can_view_all( @can_view_all(
@ -320,10 +348,7 @@ def add_switchmanagementcred(request):
messages.success(request, _("The switch management credentials were added.")) messages.success(request, _("The switch management credentials were added."))
return redirect(reverse("preferences:display-options")) return redirect(reverse("preferences:display-options"))
return form( return form(
{ {"preferenceform": switchmanagementcred, "action_name": _("Add"),},
"preferenceform": switchmanagementcred,
"action_name": _("Add"),
},
"preferences/preferences.html", "preferences/preferences.html",
request, request,
) )
@ -367,7 +392,10 @@ def del_switchmanagementcred(request, switchmanagementcred_instance, **_kwargs):
) )
return redirect(reverse("preferences:display-options")) return redirect(reverse("preferences:display-options"))
return form( return form(
{"objet": switchmanagementcred_instance, "objet_name": _("switch management credentials")}, {
"objet": switchmanagementcred_instance,
"objet_name": _("switch management credentials"),
},
"preferences/delete.html", "preferences/delete.html",
request, request,
) )
@ -383,10 +411,7 @@ def add_mailcontact(request):
messages.success(request, _("The contact email address was created.")) messages.success(request, _("The contact email address was created."))
return redirect(reverse("preferences:display-options")) return redirect(reverse("preferences:display-options"))
return form( return form(
{ {"preferenceform": mailcontact, "action_name": _("Add"),},
"preferenceform": mailcontact,
"action_name": _("Add"),
},
"preferences/preferences.html", "preferences/preferences.html",
request, request,
) )

View file

@ -28,7 +28,8 @@ from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from re2o.mixins import AclMixin, RevMixin from re2o.mixins import AclMixin, RevMixin
from preferences.utils.models import PreferencesModel from preferences.models import PreferencesModel
class TicketOption(AclMixin, PreferencesModel): class TicketOption(AclMixin, PreferencesModel):
""" Definition of the ticket's settings""" """ Definition of the ticket's settings"""

View file

@ -38,11 +38,12 @@ from re2o.base import re2o_paginator
from re2o.acl import can_view, can_view_all, can_edit, can_create from re2o.acl import can_view, can_view_all, can_edit, can_create
from preferences.utils.views import edit_options_template_function from preferences.views import edit_options_template_function
from . import forms from . import forms
from . import models from . import models
def aff_preferences(request): def aff_preferences(request):
""" View to display the settings of the tickets in the preferences page""" """ View to display the settings of the tickets in the preferences page"""
pref, created = models.TicketOption.objects.get_or_create() pref, created = models.TicketOption.objects.get_or_create()
@ -54,7 +55,7 @@ def aff_preferences(request):
"tickets/preferences.html", context=context, request=request, using=None "tickets/preferences.html", context=context, request=request, using=None
) )
@login_required @login_required
def edit_options(request, section): def edit_options(request, section):
return edit_options_template_function(request, section, forms, models) return edit_options_template_function(request, section, forms, models)