Esempio n. 1
0
class UserRegisterSerializer(_Serializer):
    from rest_framework import serializers as _se
    from rest_framework import validators as _val

    email = _se.EmailField(
        required=True,
        allow_null=False,
        allow_blank=False,
        min_length=6,
        max_length=256,
        validators=[_val.UniqueValidator(queryset=_User.objects.all())])

    phone = _se.IntegerField(
        required=True,
        allow_null=False,
        validators=[_val.UniqueValidator(queryset=_User.objects.all())])

    password = _se.CharField(
        min_length=6,
        write_only=True,
    )

    first_name = _se.CharField(
        min_length=2,
        max_length=256,
    )

    last_name = _se.CharField(
        min_length=2,
        max_length=256,
    )

    username = _se.CharField(
        min_length=4,
        max_length=256,
    )

    from django.db import transaction as _ts

    @_ts.atomic
    def create(self, validated_data):
        from django.conf import settings

        user = _User.objects.create(**validated_data)
        user.set_password(validated_data['password'])

        if settings.DEBUG:
            user.activate()
        else:
            user.save()

        if not settings.DEBUG:
            user.mail_activation()

        return user

    class Meta:
        model = _User
        fields = ('email', 'phone', 'password', 'first_name', 'last_name',
                  'username')
Esempio n. 2
0
class register_Serializer(serializers.Serializer):

    email = serializers.EmailField(
        validators=[validators.UniqueValidator(queryset=User.objects.all())])

    username = serializers.CharField(
        min_length=2,
        max_length=100,
        validators=[validators.UniqueValidator(queryset=User.objects.all())])

    password = serializers.CharField(min_length=8, max_length=255)

    password_confirmation = serializers.CharField(min_length=8, max_length=255)

    first_name = serializers.CharField(min_length=2, max_length=100)

    last_name = serializers.CharField(min_length=2, max_length=100)

    def validate(self, data):
        passwd = data['password']
        paswwd_conf = data['password_confirmation']
        if passwd != paswwd_conf:
            raise serializers.ValidationError('keys does not equals')

        password_validation.validate_password(passwd)
        return data

    def create(self, data):
        data.pop('password_confirmation')
        user = User.objects.create_user(**data, is_active=True)
        Profile.objects.create(user=user)
        return user
Esempio n. 3
0
class CreateUserSerializer(serializers.HyperlinkedModelSerializer):
    email = serializers.EmailField(
        required=True,
        validators=[
            validators.UniqueValidator(queryset=models.User.objects.all())
        ])
    username = serializers.CharField(validators=[
        validators.UniqueValidator(queryset=models.User.objects.all())
    ])
    password = serializers.CharField(min_length=8,
                                     style={"input_type": "password"},
                                     write_only=True,
                                     label="Password")

    def create(self, validated_data):
        user = models.User.objects.create_user(validated_data['username'],
                                               validated_data['email'],
                                               validated_data['password'])

        if user:
            send_mail('Welcome to the Moovie App!',
                      'Welcome to the movie app %s' % user.username,
                      '*****@*****.**', [user.email],
                      fail_silently=False)

        return user

    class Meta:
        model = models.User
        fields = ['id', 'username', 'email', 'password']
        extra_kwargs = {"password": {"write_only": True}}
Esempio n. 4
0
class ManagerUserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(min_length=6, required=False)
    username = serializers.CharField(
        validators=[validators.UniqueValidator(models.User.objects.all())])
    email = serializers.EmailField(
        validators=[validators.UniqueValidator(models.User.objects.all())])

    class Meta:
        model = models.User
        fields = ('id', 'name', 'email', 'username', 'password',
                  'is_superuser', 'is_manager', 'is_staff')
        read_only_fields = ('is_superuser', 'is_manager', 'is_staff')

    def create(self, validated_data):
        new_password = self.validated_data.pop('password')
        user = super(ManagerUserSerializer, self).create(validated_data)
        if new_password:
            user.set_password(new_password)
            user.save()
        return user

    def update(self, instance, validated_data):
        new_password = self.validated_data.pop('password', None)
        user = super(ManagerUserSerializer,
                     self).update(instance, validated_data)
        if new_password:
            user.set_password(new_password)
            user.save()
        return user
Esempio n. 5
0
class SignupSerializer(serializers.Serializer):
    username = serializers.CharField(
        required=True,
        validators=[validators.UniqueValidator(queryset=User.objects.all())])
    email = serializers.EmailField(
        required=True,
        validators=[validators.UniqueValidator(queryset=User.objects.all())])
    password = serializers.CharField(min_length=8, required=True)
    password_confirmation = serializers.CharField(min_length=8, required=True)
Esempio n. 6
0
class UserRegisterSerializer(serializers.Serializer):
    username = serializers.CharField(
        min_length=5,
        max_length=username_max,
        validators=[validators.UniqueValidator(queryset=auth.models.User.objects.all())]
    )
    email = serializers.EmailField(
        max_length=email_max,
        validators=[validators.UniqueValidator(queryset=auth.models.User.objects.all())]
    )
    password = serializers.CharField(min_length=6, max_length=password_max)
class CustomUserSerializer(serializers.ModelSerializer):
    email = serializers.CharField(validators=[
        validators.UniqueValidator(message='This email already exists',
                                   queryset=CustomUser.objects.all())
    ])
    username = serializers.CharField(validators=[
        validators.UniqueValidator(message='This username already exists',
                                   queryset=CustomUser.objects.all())
    ])
    password = serializers.CharField(write_only=True)
    role = serializers.CharField(required=True)

    class Meta:
        model = CustomUser
        fields = ('id', 'email', 'password', 'username', 'role', 'is_active')
Esempio n. 8
0
class AddUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        required=True,
        validators=[
            validators.UniqueValidator(queryset=CustomUserAkun.objects.all())
        ])
    role = serializers.CharField(required=False)
    password = serializers.CharField(write_only=True,
                                     required=True,
                                     validators=[validate_password])
    password2 = serializers.CharField(write_only=True, required=True)
    email = serializers.EmailField(required=True)

    class Meta:
        model = CustomUserAkun
        fields = ('username', 'email', 'role', 'password', 'password2')

    def validate(self, attrs):
        if attrs['password'] is not None:
            if attrs['password'] != attrs['password2']:
                raise serializers.ValidationError(
                    {"password": "******"})
        return attrs

    def create(self, validated_data):
        user = CustomUserAkun.objects.create(
            username=validated_data['username'],
            role=validated_data['role'],
            email=validated_data['email'])
        user.set_password(validated_data['password'])
        user.save()
        return user
Esempio n. 9
0
class CreateUserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        style={'input_type': 'password'},
        write_only=True
    )
    username = fields.CharField(
        max_length=150,
        required=True,
        validators=[
            validators.UniqueValidator(queryset=User.objects.all()),
            UsernameValidator()
        ]
    )

    def validate(self, attrs):
        user = User(**attrs)
        password = attrs.get('password')

        try:
            validate_password(password, user)
        except ValidationError as e:
            raise serializers.ValidationError({'password': list(e.messages)})

        return attrs

    def create(self, validated_data):
        try:
            return User.objects.create_user(**validated_data)
        except Exception as e:
            self.fail('cannot create user: {}'.format(e))

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name', 'password')
Esempio n. 10
0
class Pipeline(serializers.ModelSerializer):
    uuid = serializers.UUIDField(
        read_only=True
    )
    name = serializers.CharField(
        min_length=2,
        max_length=255,
        required=True,
        allow_null=False,
        allow_blank=False,
        validators=[
            validators.UniqueValidator(
                queryset=PipelineModel.objects.all(),
                message='errorPipelineNameExists'
            )
        ],
        error_messages={
            'invalid': 'errorPipelineNameRequired',
            'blank': 'errorPipelineNameRequired',
            'required': 'errorPipelineNameRequired',
            'null': 'errorPipelineNameRequired',
            'max_length': 'errorPipelineNameTooLong',
            'min_length': 'errorPipelineNameTooShort',
        }
    )

    class Meta(object):
        model = PipelineModel
        fields = [
            'uuid',
            'name'
        ]
Esempio n. 11
0
class LinkSerializer(serializers.HyperlinkedModelSerializer):
    url_field_name = "selflink"

    class Meta:
        model = models.Link
        fields = ["selflink", "short", "owner", "target"]
        extra_kwargs = {"selflink": {"lookup_field": "short"}}

    short = serializers.CharField(
        min_length=6,
        max_length=32,
        default=serializers.CreateOnlyDefault(models.link_default_short),
        validators=[validators.UniqueValidator(queryset=models.Link.objects.all())],
    )
    owner = serializers.SlugRelatedField(read_only=True, slug_field="username")
    target = serializers.URLField(max_length=200, required=True)

    def save(self, **kwargs):
        # set the current user as default owner for all operations but allow explicit overwriting with
        # keyword arguments to `save(owner=…)`
        kwargs.setdefault("owner", self.context["request"].user)
        return super().save(**kwargs)

    def validate_short(self, value):
        """
        Check that short is not changed on update operations

        :param value: The new value
        :return: The new value in validated form
        """
        is_update = self.instance is not None
        if is_update and value != self.instance.short:
            raise serializers.ValidationError("field cannot be changed once created")
        return value
Esempio n. 12
0
class UserSerializer(serializers.ModelSerializer):
    name = serializers.CharField(validators=[
        validators.UniqueValidator(queryset=User.objects.all(),
                                   message='そのユーザは既にいます')
    ])

    class Meta:
        model = User
        fields = ('id', 'name', 'file', 'belongs')
        extra_kwargs = {
            'gravatar': {
                'read_only': True
            },
            'password': {
                'write_only': True
            },
        }

    def validate_belongs(self, values):
        request = self.context['request']
        for value in values:
            group = Group.objects.filter(id=value.id).first()
            if group and group.owner_id != request.user.id:
                raise serializers.ValidationError('このグループにユーザを追加する権限がありません')
        return values
Esempio n. 13
0
class GenreSerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(validators=[validators.UniqueValidator(
        queryset=Genre.objects.all())])

    class Meta:
        model = Genre
        exclude = ('id',)
class CustomUserSerializer(serializers.ModelSerializer):
    """
    We use this serializer for user registration. Most of the fields have
    `required=False`, but can be configured as needed. This serializer is used
    in `accounts.viewsets.CustomUserModelViewSet`.
    """

    email = serializers.CharField(write_only=True,
                                  validators=[
                                      validators.UniqueValidator(
                                          message='This email already exists',
                                          queryset=CustomUser.objects.all())
                                  ])
    password = serializers.CharField(write_only=True)
    birth_date = serializers.CharField(required=False)
    bio = serializers.CharField(required=False)
    gender = serializers.CharField(required=False)
    last_name = serializers.CharField(required=False)
    first_name = serializers.CharField(required=False)
    birth_date = serializers.CharField(required=False)

    class Meta:
        model = CustomUser
        fields = ('first_name', 'last_name', 'email', 'password', 'bio',
                  'gender', 'birth_date')
Esempio n. 15
0
class CategorySerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(validators=[validators.UniqueValidator(
        queryset=Category.objects.all())])

    class Meta:
        model = Category
        exclude = ('id',)
Esempio n. 16
0
class storageNestedWriteSerializer(storageSerializer):
    id = serializers.UUIDField(
        read_only=False,
        validators=[
            validators.UniqueValidator(queryset=IOQueue.objects.all())
        ])
    storagemedium = serializers.CharField(validators=[])

    class Meta:
        model = storage
        fields = storageSerializer.Meta.fields

    def create(self, validated_data):
        #print 'validated_data: %s' % repr(validated_data)
        storagemedium_data = eval(validated_data.pop('storagemedium'))
        Target_obj = StorageTargets.objects.get(
            id=storagemedium_data.pop('storagetarget'))
        storagemedium_data['storagetarget'] = Target_obj
        storageMedium_obj, created = storageMedium.objects.update_or_create(
            id=storagemedium_data['id'], defaults=storagemedium_data)
        ArchiveObject_obj = ArchiveObject.objects.get(
            ObjectUUID=validated_data.pop('archiveobject'))
        validated_data['archiveobject'] = ArchiveObject_obj
        storage_obj = storage.objects.create(storagemedium=storageMedium_obj,
                                             **validated_data)
        return storage_obj
Esempio n. 17
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if 'id' in self.fields:
            self.fields['id'].validators.append(
                validators.UniqueValidator(
                    queryset=self.Meta.model.objects.all()))
Esempio n. 18
0
class UserSignupSerializer(serializers.ModelSerializer):
    id = rest.HashidSerializerCharField(source_field="restauth.User.id", read_only=True)
    email = serializers.EmailField(
        validators=[validators.UniqueValidator(queryset=dj_auth.get_user_model().objects.all())],
    )
    profile = UserProfileSerializer(required=False)

    class Meta:
        model = dj_auth.get_user_model()
        fields = ("id", "email", "password", "jwt_token", "profile")
        read_only_fields = ("jwt_token",)
        extra_kwargs = {"password": {"write_only": True}}

    def validate_password(self, password):
        password_validation.validate_password(password)
        return password

    def create(self, validated_data):
        user = dj_auth.get_user_model().objects.create_user(validated_data["email"], validated_data["password"],)
        models.UserProfile.objects.create(user=user, **validated_data.pop("profile", {}))

        activation_token = tokens.account_activation_token.make_token(user)
        utils.user_notification_impl("account_activation", user=user, token=activation_token)

        return user
Esempio n. 19
0
class SCIMMemberSerializer(serializers.ModelSerializer):
    id = SCIMIdField('user', read_only=True)
    resource_schemas = ["urn:ietf:params:scim:schemas:core:2.0:User"]
    resource_type = 'User'
    detail_view_name = 'scim-user-detail'

    userName = serializers.CharField(source='remote_id', required=False)
    externalId = serializers.CharField(source='scim_external_id')

    name = NameSerializer()
    emails = EmailsField(
        source='email',
        allow_blank=False,
        validators=[validators.UniqueValidator(queryset=Member.objects.all())])
    active = serializers.BooleanField(source='is_active')
    groups = serializers.SerializerMethodField(read_only=True)
    schemas = SchemaSerializer(read_only=False)
    meta = MetaSerializer(required=False)

    def create(self, validated_data):
        validated_data['welcome_email_is_sent'] = True
        instance = super(SCIMMemberSerializer, self).create(validated_data)

        return instance

    def get_groups(self, obj):
        return UserGroupSerializer(obj.groups.exclude(name='Authenticated'),
                                   many=True,
                                   read_only=True).data

    class Meta(object):
        model = Member
        fields = ('id', 'externalId', 'userName', 'name', 'emails', 'active',
                  'groups', 'schemas', 'meta')
Esempio n. 20
0
class CategoryListSerializer(serializers.ModelSerializer):
    products = ProductListSerializer(
        many=True,
        required=False,
    )
    reference = serializers.CharField(
        validators=[
            validators.UniqueValidator(
                queryset=models.Category.objects.all(),
                message=_("A referência já está sendo utilizada")
            )
        ],
        label=_("Referência")
    )    

    class Meta:
        model = models.Category
        fields = [
            'pk',
            'name',
            'reference',
            'description',
            'amount',
            'minimum',
            'registration',
            'products'
        ]
        read_only_fields = [
            'pk',
            'amount',
            'registration',            
        ]
Esempio n. 21
0
 class Meta:
     model = User
     fields = ('username', 'email', 'password')
     extra_kwargs = {
         'username': {
             'validators':
             [validators.UniqueValidator(queryset=User.objects.all())]
         },
         'email': {
             'validators':
             [validators.UniqueValidator(queryset=User.objects.all())]
         },
         'password': {
             'write_only': True
         }
     }
Esempio n. 22
0
class RegisterSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        required=True,
        max_length=30,
        min_length=5,
        validators=[
            AuthenticationValidator.text_validator,
            validators.UniqueValidator(queryset=User.objects.all()),
        ],
        style={"placeholder": "Username"},
    )
    email = serializers.EmailField(
        required=True,
        style={
            "input_type": "email",
            "placeholder": "Email"
        },
    )
    password = serializers.CharField(
        required=True,
        max_length=30,
        min_length=5,
        validators=[
            AuthenticationValidator.text_validator,
        ],
        style={
            "input_type": "password",
            "placeholder": "Password"
        },
    )

    class Meta:
        model = User
        fields = ["username", "email", "password"]
class UserSerializer(EnhancedModelSerializer):
    first_name = serializers.CharField(required=True,
                                       allow_blank=False,
                                       allow_null=False)
    last_name = serializers.CharField(required=True,
                                      allow_blank=False,
                                      allow_null=False)
    full_name = serializers.CharField(read_only=True)
    email = serializers.EmailField(
        required=True,
        allow_blank=False,
        allow_null=False,
        validators=[validators.UniqueValidator(queryset=User.objects.all())])
    username = serializers.EmailField(read_only=True)
    is_active = serializers.BooleanField(default=True, read_only=True)
    is_admin = serializers.BooleanField(default=False, read_only=True)
    is_staff = serializers.BooleanField(default=False, read_only=True)
    is_superuser = serializers.BooleanField(default=False, read_only=True)
    last_login = serializers.DateTimeField(read_only=True)
    date_joined = serializers.DateTimeField(read_only=True)
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)
    timezone = serializers.CharField()
    profile_image = Base64ImageField(required=False)

    class Meta:
        model = User
        nested_fields = ('id', 'first_name', 'last_name', 'email', 'username',
                         'is_active', 'is_admin', 'is_superuser', 'is_staff',
                         'full_name', 'profile_image')
        fields = nested_fields + ('created_at', 'updated_at', 'last_login',
                                  'date_joined', 'timezone')
class UserRegistrationSerializer(serializers.ModelSerializer):
    first_name = serializers.CharField(required=True,
                                       allow_blank=False,
                                       allow_null=False)
    last_name = serializers.CharField(required=True,
                                      allow_blank=False,
                                      allow_null=False)
    email = serializers.EmailField(
        required=True,
        allow_blank=False,
        allow_null=False,
        validators=[validators.UniqueValidator(queryset=User.objects.all())])
    password = serializers.CharField(required=True,
                                     allow_blank=False,
                                     allow_null=False,
                                     style={'input_type': 'password'})

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')

    def validate(self, attrs):
        attrs.update(is_admin=False,
                     is_staff=False,
                     is_superuser=False,
                     is_active=True,
                     username=attrs['email'])
        return attrs
Esempio n. 25
0
class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    email = CustomEmailSerializer(validators=[validators.UniqueValidator(queryset=User.objects.all())])
    profile = ProfileSerializer(many=False)
    cars_count = serializers.IntegerField(default=0, read_only=True)

    def create(self, validated_data):
        profile = validated_data.pop("profile")
        password = validated_data.pop("password")
        user = User.objects.create(**validated_data)
        user.set_password(password)
        user.save()

        profile = Profile.objects.create(user=user, **profile)
        profile.save()

        return user

    def update(self, validated_data):
        email = validated_data["email"]
        profile_data = validated_data["profile"]

        user = User.objects.get(email=email)
        profile = user.profile
        profile.first_name = profile_data.get("first_name", profile.first_name)
        profile.last_name = profile_data.get("last_name", profile.last_name)
        profile.mobile = profile_data.get("mobile", profile.mobile)

    class Meta:
        model = User
        fields = ("id", "password", "email", "profile", "cars_count")
Esempio n. 26
0
class NewUserRegistrationSerializer(CurrentUserSerializer):

    email = serializers.EmailField(
        required=True,
        validators=[User.email_validator],
    )
    username = serializers.CharField(
        required=True,
        max_length=32,
        read_only=False,
        validators=[
            User.username_validator,
            validators.UniqueValidator(
                queryset=User.objects.all(),
                message="This username is taken.",
            ),
        ],
    )
    password = serializers.CharField(
        required=True,
        write_only=True,
        validators=[validate_password],
    )
    invite_key = serializers.UUIDField(
        required=True,
        write_only=True,
        validators=[invite_key_validator],
    )
    token = serializers.SerializerMethodField()

    class Meta(CurrentUserSerializer.Meta):
        fields = CurrentUserSerializer.Meta.fields + (
            'invite_key',
            'password',
            'token',
        )

    @staticmethod
    def get_token(user):
        return AuthToken.objects.create(user=user)

    def create(self, validated_data):

        invite_key = validated_data['invite_key']
        invite = Invite.objects.get(key=invite_key) if invite_key else None

        with transaction.atomic():

            if invite:
                invite.delete()

            user = User.objects.create_user(
                username=validated_data['username'],
                email=validated_data['email'],
                password=validated_data['password'],
                invited_by=invite.offered_by if invite else None,
            )

        return user
Esempio n. 27
0
class UserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=True, validators=[validators.UniqueValidator(queryset=User.objects.all())])
    username = serializers.CharField(required=True,
                                     validators=[validators.UniqueValidator(queryset=User.objects.all())])
    password = serializers.CharField(required=True, min_length=8)
    first_name = serializers.CharField(required=False, max_length=100)
    last_name = serializers.CharField(required=False, max_length=100)

    def create(self, validated_data):
        user = User.objects.create_user(validated_data['username'], email=validated_data['email'],
                                        password=validated_data['password'], first_name=validated_data['first_name'],
                                        last_name=validated_data['last_name'])
        return user

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'username', 'password', 'email')
Esempio n. 28
0
class UserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(
        validators=[validators.UniqueValidator(queryset=User.objects.all())])

    class Meta:
        model = User
        fields = ("id", "username", "email", "first_name", "last_name", "role")
        read_only_fields = ("username", "role")
class BusDriverSerializer(serializers.Serializer):
    id = serializers.CharField(required=False)
    driver_name = serializers.CharField()
    email = serializers.EmailField(validators=[
        validators.UniqueValidator(queryset=Users.objects.all(),
                                   message="このメールアドレスは既に使用されています.")
    ])
    password = serializers.CharField()
Esempio n. 30
0
class GenreSerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    slug = serializers.SlugField(
        validators=[validators.UniqueValidator(queryset=Genre.objects.all())])

    class Meta:
        fields = ('name', 'slug')
        lookup_field = 'slug'
        model = Genre