Skip to content

Commit

Permalink
chg: [api] improved validators.
Browse files Browse the repository at this point in the history
  • Loading branch information
cedricbonhomme committed Nov 23, 2023
1 parent 095eadb commit 33ea79b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
15 changes: 5 additions & 10 deletions api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from django_q import models as q_models
from rest_framework import serializers
from rest_framework.serializers import ValidationError

from api import validators
from authentication.models import User
from automation.models import HttpAutomatedTest, PingAutomatedTest
from testing.models import TlsScanHistory
from testing.validators import domain_name

#
# Model: User
Expand Down Expand Up @@ -112,9 +111,7 @@ def validate_file(self, data):
"""
Check that the file is not bigger than 5000000 bytes.
"""
if data.size > 5000000:
raise ValidationError("The file size can not be more than 5000000 bytes.")
return data
return validators.file_size(data)


class DomainNameSerializer(serializers.Serializer):
Expand All @@ -131,7 +128,7 @@ def validate_domain_name(self, data):
"""
Check that data is a valid domain name.
"""
return domain_name(data)
return validators.domain_name(data)


class DomainNameAndServiceSerializer(serializers.Serializer):
Expand All @@ -151,12 +148,10 @@ def validate_service(self, data):
"""
Check that data is a valid service.
"""
if data not in ["web", "email"]:
raise ValidationError("Service must be 'web' or 'email'.")
return data
return validators.service(data)

def validate_domain_name(self, data):
"""
Check that data is a valid domain name.
"""
return domain_name(data)
return validators.domain_name(data)
35 changes: 35 additions & 0 deletions api/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import re

from rest_framework.serializers import ValidationError

pattern = re.compile(
r"^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|"
r"([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|"
r"([a-zA-Z0-9][-_.a-zA-Z0-9]{0,61}[a-zA-Z0-9]))\."
r"([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}.[a-zA-Z]{2,3})$"
)


def service(value):
if value not in ["web", "email"]:
raise ValidationError("Service must be 'web' or 'email'.")
return value


def file_size(file):
if file.size > 5000000:
raise ValidationError("The file size can not be more than 5000000 bytes.")
return file


def domain_name(value):
"""
Return whether or not given value is a valid domain.
See:
https://validators.readthedocs.io/en/latest/_modules/validators/domain.html#domain
"""
res = pattern.match(value)
if res:
return value
else:
raise ValidationError("This field must be a domain name.")

0 comments on commit 33ea79b

Please sign in to comment.