71 lines
2.3 KiB
Python
71 lines
2.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
#
|
|
# ITerativ GmbH
|
|
# http://www.iterativ.ch/
|
|
#
|
|
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
|
|
#
|
|
# Created on 2019-04-02
|
|
# @author: chrigu <christian.cueni@iterativ.ch>
|
|
import re
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from rest_framework import serializers
|
|
from rest_framework.fields import CharField, URLField
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
MIN_PASSWORD_LENGTH = 8
|
|
|
|
# For future versions https://docs.djangoproject.com/en/2.1/topics/auth/passwords/#integrating-validation
|
|
|
|
|
|
def validate_old_password(old_password, username):
|
|
user = get_user_model().objects.get(username=username)
|
|
if user.check_password(old_password):
|
|
return old_password
|
|
else:
|
|
raise serializers.ValidationError(_("Das eingegebene Passwort ist falsch"))
|
|
|
|
|
|
def validate_old_new_password(value):
|
|
if value.get("old_password") == "" and value.get("new_password") == "":
|
|
return value
|
|
elif value.get("old_password") == "" and value.get("new_password") != "":
|
|
raise serializers.ValidationError(_("Das neue Passwort muss gesetzt werden"))
|
|
elif value.get("old_password") != "" and value.get("new_password") == "":
|
|
raise serializers.ValidationError(_("Das alte Passwort muss angegeben werden"))
|
|
|
|
return value
|
|
|
|
|
|
def validate_strong_password(password):
|
|
has_number = re.search(r"\d", password)
|
|
has_upper = re.search(r"[A-Z]", password)
|
|
has_lower = re.search(r"[a-z]", password)
|
|
has_special = re.search(r'[!@#$%^&*(),.?":{}|<>\+]', password)
|
|
|
|
if has_number and has_upper and has_lower and has_special:
|
|
return password
|
|
else:
|
|
raise serializers.ValidationError(
|
|
_("Das Passwort muss Grossbuchstaben, Zahlen und Sonderzeichen beinhalten")
|
|
)
|
|
|
|
|
|
class PasswordSerialzer(serializers.Serializer):
|
|
old_password = CharField(allow_blank=True)
|
|
new_password = CharField(allow_blank=True, min_length=MIN_PASSWORD_LENGTH)
|
|
|
|
def validate_new_password(self, value):
|
|
return validate_strong_password(value)
|
|
|
|
def validate_old_password(self, value):
|
|
return validate_old_password(value, self.context.username)
|
|
|
|
def validate(self, obj):
|
|
return validate_old_new_password(obj)
|
|
|
|
|
|
class AvatarUrlSerializer(serializers.Serializer):
|
|
avatar_url = URLField(allow_blank=True)
|