From f509fd6dbf9ffeb7fd29cfac6d1b051a07eed754 Mon Sep 17 00:00:00 2001 From: Daniel Roschka Date: Mon, 23 Mar 2015 21:51:31 +0100 Subject: [PATCH] Added validation for the admin forms. Especially the validation of the key should be helpful, as it prevents users to store wrongly formatted keys. --- binder/admin.py | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/binder/admin.py b/binder/admin.py index 6fc90d6..d2814c1 100644 --- a/binder/admin.py +++ b/binder/admin.py @@ -1,11 +1,38 @@ +import binascii +import dns.tsigkeyring from models import BindServer, Key from django.contrib import admin +from django.forms import ModelForm, ValidationError + +class BindServerAdminForm(ModelForm): + def clean_statistics_port(self): + port = self.cleaned_data["statistics_port"] + if port < 1 or port > 65535: + raise ValidationError("Invalid port number %(port)s. Please enter " + "a valid one between 1 and 65535.", + params={'port': port}) + return self.cleaned_data["statistics_port"] + class BindServerAdmin(admin.ModelAdmin): - list_display = [ 'hostname', 'statistics_port', 'default_transfer_key' ] + form = BindServerAdminForm + list_display = ['hostname', 'statistics_port', 'default_transfer_key'] + + +class KeyAdminForm(ModelForm): + def clean_data(self): + try: + keyring = dns.tsigkeyring.from_text({'': self.cleaned_data["data"]}) + except binascii.Error as err: + raise ValidationError("Invalid key data: %(error)s", + params={'error': err}) + return self.cleaned_data["data"] + class KeyAdmin(admin.ModelAdmin): - list_display = [ 'name', 'data', 'algorithm' ] + form = KeyAdminForm + list_display = ['name', 'data', 'algorithm'] + admin.site.register(BindServer, BindServerAdmin) admin.site.register(Key, KeyAdmin)