from rest_framework import serializers
from api.models import User
from django.contrib.auth.hashers import make_password

class UserRegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password')
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate_username(self, value):
        if len(value) < 5 or len(value) > 12:
            raise serializers.ValidationError("用户名长度需在5-12位之间")
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在")
        return value

    def validate_password(self, value):
        if len(value) < 6 or len(value) > 20:
            raise serializers.ValidationError("密码长度需在6-20位之间")
        return value

    def create(self, validated_data):
        # 使用固定盐值加密
        validated_data['password'] = make_password(
            validated_data['password'],
            salt='vrviewer',
            hasher='pbkdf2_sha256'
        )
        return User.objects.create(**validated_data)