密码字段验证
serializers.py
from django.contrib.auth import password_validation
class PhoneCodeSerializer(BaseSerializer):
code = serializers.CharField(
required=True, allow_blank=False, min_length=4, max_length=4,
help_text='验证码',
error_messages={
'blank': '请输入验证码',
'required': '请输入验证码',
'min_length': '验证码格式错误',
'max_length': '验证码格式错误',
})
phone = PhoneField(
required=True, max_length=11, min_length=11, help_text='手机号')
def validate_code(self, code):
"""
code.create user.receive user.register
t1 t2 t3
5min内:
t3-t1<5
t3-5<t1: 5min内
t3-5>t1: 过期
:param code:
:return:
"""
last_record = VerifyCode.objects \
.filter(phone=self.initial_data['phone']) \
.order_by('-create_time').first()
if not last_record:
raise MyException(
'Verification code not exist',
errors.VerifyCode.CODE_NOT_EXIST)
now = get_now()
five_minutes_ago = now - datetime.timedelta(
hours=0, minutes=5, seconds=0)
if last_record.create_time < five_minutes_ago:
raise MyException(
'Verification code expired, try again',
errors.VerifyCode.CODE_EXPIRED)
if last_record.code != code:
raise MyException(
'Verification code err not equal',
errors.VerifyCode.CODE_NOT_EQUAL)
return code
class UserRegisterSerializer(PhoneCodeSerializer):
# 利用drf中的validators验证username是否唯一
username = serializers.CharField(
required=True, allow_blank=False,
validators=[
UniqueValidator(queryset=User.objects.all(), message='用户已经存在')
])
password = serializers.CharField(
required=True,
style={'input_type': 'password'},
write_only=True,
)
@staticmethod
def validate_password(data):
password_validation.validate_password(password=data, user=User)
return data
settings.py
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # 用户密码与用户属性
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # 最小长度验证
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # 撞库检查
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # 全数字检查
},
]