2014-05-08 16:59:35 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
2015-04-04 17:44:07 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2014-05-08 16:59:35 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
2014-10-15 21:18:50 +00:00
|
|
|
from orchestra.api.serializers import HyperlinkedModelSerializer
|
2014-05-08 16:59:35 +00:00
|
|
|
from orchestra.apps.accounts.serializers import AccountSerializerMixin
|
|
|
|
|
|
|
|
from .helpers import domain_for_validation
|
|
|
|
from .models import Domain, Record
|
|
|
|
from . import validators
|
|
|
|
|
|
|
|
|
|
|
|
class RecordSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = Record
|
|
|
|
fields = ('type', 'value')
|
|
|
|
|
|
|
|
def get_identity(self, data):
|
|
|
|
return data.get('value')
|
|
|
|
|
|
|
|
|
2014-10-15 21:18:50 +00:00
|
|
|
class DomainSerializer(AccountSerializerMixin, HyperlinkedModelSerializer):
|
2014-05-08 16:59:35 +00:00
|
|
|
""" Validates if this zone generates a correct zone file """
|
|
|
|
records = RecordSerializer(required=False, many=True, allow_add_remove=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Domain
|
2014-10-15 21:18:50 +00:00
|
|
|
fields = ('url', 'name', 'records')
|
|
|
|
postonly_fields = ('name',)
|
2014-05-08 16:59:35 +00:00
|
|
|
|
2014-10-20 15:51:24 +00:00
|
|
|
def clean_name(self, attrs, source):
|
|
|
|
""" prevent users creating subdomains of other users domains """
|
|
|
|
name = attrs[source]
|
2015-03-29 16:10:07 +00:00
|
|
|
top = Domain.get_parent_domain(name)
|
2014-10-20 15:51:24 +00:00
|
|
|
if top and top.account != self.account:
|
|
|
|
raise ValidationError(_("Can not create subdomains of other users domains"))
|
|
|
|
return attrs
|
|
|
|
|
2014-05-08 16:59:35 +00:00
|
|
|
def full_clean(self, instance):
|
|
|
|
""" Checks if everything is consistent """
|
|
|
|
instance = super(DomainSerializer, self).full_clean(instance)
|
|
|
|
if instance and instance.name:
|
2014-11-14 15:51:18 +00:00
|
|
|
records = self.init_data.get('records', [])
|
2014-05-08 16:59:35 +00:00
|
|
|
domain = domain_for_validation(instance, records)
|
2014-11-14 15:51:18 +00:00
|
|
|
validators.validate_zone(domain.render_zone())
|
2014-05-08 16:59:35 +00:00
|
|
|
return instance
|