class UserSerializer(serializers.Serializer): profile = UserProfileSerializer(required=False, partial=True) id = serializers.ReadOnlyField() last_login = serializers.ReadOnlyField() first_name = serializers.CharField() last_name = serializers.CharField() username = serializers.CharField() password = serializers.CharField() # pbkdf2_sha256$30000$UEvGw0rZNxuo$Jqb8dK3W50lGnVxjSEwitfzbloLXPgLV6UHXSetBMFU = email = serializers.EmailField() def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) profile_data['user'] = user Profile.objects.create(**profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile # Update User data instance.username = validated_data.get('username', instance.username) # instance.password = validated_data.get('password', instance.password) instance.password = make_password(validated_data.get('password')) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.save() # Update UserProfile data if not instance.profile: Profile.objects.create(user=instance, **profile_data) instance.profile.title = profile_data.get('title', profile.title) instance.profile.avatar = profile_data.get('avatar', profile.avatar) instance.profile.history = profile_data.get('history', profile.history) instance.profile.status_active = profile_data.get('status_active', profile.status_active) instance.profile.num_of_likes = profile_data.get('num_of_likes', profile.num_of_likes) instance.profile.status_logged = profile_data.get('status_logged', profile.status_logged) instance.profile.num_of_articles = profile_data.get('num_of_articles', profile.num_of_articles) profile.save() # Check if the password has changed password = validated_data.get('password', None) if password: instance.set_password(password) instance.save() # update_session_auth_hash(self.context.get('request'), instance) return instance def validate_username(self, username): if (self.instance is None or self.instance.username != username) \ and User.objects.filter(username=username).exists(): raise ValidationError("El nombre de usuario {0} ya está siendo utilizado".format(username)) return username def validate_email(self, email): if (self.instance is None or self.instance.email != email) \ and User.objects.filter(email=email).exists(): raise ValidationError("El e-mail {0} ya está siendo utilizado".format(email)) return email.lower()
class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length=200) first_name = serializers.CharField(max_length=200, required=False) last_name = serializers.CharField(max_length=200, required=False) email = serializers.EmailField(required=False) password = serializers.CharField(max_length=200, write_only=True)
class UserSerializer(serializers.ModelSerializer): # category = serializers.PrimaryKeyRelatedField(queryset=UserCategory.objects.all()) category = CategorySerializer() auth = AuthUserSerializer(read_only=True) email = serializers.EmailField(source='auth.email', allow_blank=True) username = serializers.CharField(source='auth.username') fullname = serializers.CharField(source='auth.last_name') password = serializers.CharField(source='auth.password', write_only=True, allow_null=True, allow_blank=True) enable_tasks = serializers.CharField(allow_blank=True) # 重置用户密码 @staticmethod def reset_password(instance, password): if isinstance(instance, AuthUser) and password and password != '': instance.set_password(password) # 创建用户 def create(self, validated_data): with transaction.atomic(): # 处理目录 category_data = validated_data.pop('category') validated_data['category'] = CategorySerializer().create( category_data) # 处理 auth for related_obj_name in self.Meta.related_fields: data = validated_data.pop(related_obj_name) if related_obj_name == 'auth': related_instance = AuthUser() else: continue if 'password' in data: self.reset_password(related_instance, data.pop('password')) # Same as default update implementation for attr_name, value in data.items(): setattr(related_instance, attr_name, value) related_instance.save() validated_data['auth'] = related_instance return super(UserSerializer, self).create(validated_data) # 更新用户 def update(self, instance, validated_data): # 处理目录 if 'category' in validated_data: category_data = validated_data.pop('category') validated_data['category'] = CategorySerializer().create( category_data) # auth for related_obj_name in self.Meta.related_fields: data = validated_data.pop(related_obj_name) related_instance = getattr(instance, related_obj_name) if 'password' in data: self.reset_password(related_instance, data.pop('password')) # Same as default update implementation for attr_name, value in data.items(): setattr(related_instance, attr_name, value) related_instance.save() return super(UserSerializer, self).update(instance, validated_data) class Meta: model = User fields = ('url', 'id', 'auth', 'category', 'username', 'fullname', 'email', 'enable_tasks', 'password') related_fields = ['auth'] extra_kwargs = {'password': {'write_only': True}}
class PhoneSendOTPSerializers(serializers.Serializer): email = serializers.EmailField(required=False) phone = serializers.IntegerField(required=False)
class MemberInfoSerializer(serializers.Serializer): name = serializers.CharField(max_length=200) email = serializers.EmailField() cpf = serializers.CharField(max_length=11, required=False, validators=[cpf_validator])
class EmailListField(serializers.ListField): child = serializers.EmailField()
class RequestResetPassSerializer(serializers.Serializer): email = serializers.EmailField(required=True, help_text='Email of the user.')
class ResendEmailSerializer(serializers.Serializer): email = serializers.EmailField(required=True)
class ValidateRegistrationSerializer(serializers.Serializer): email = serializers.EmailField(label='Registration E-Mail Address', validators=[email_does_exist]) username = serializers.CharField(label='Username', required=False) code = serializers.CharField(label='Validation code', write_only=True, validators=[code_is_valid]) password = serializers.CharField(label='password', write_only=True) password_repeat = serializers.CharField(label='password_repeat', write_only=True) first_name = serializers.CharField(label='First name') last_name = serializers.CharField(label='Last name') street = serializers.CharField(required=False, label='Street') address_appendix = serializers.CharField(required=False, label='Address appendix') city = serializers.CharField(required=False, label='City') country = serializers.CharField(required=False, label='Country') zip_code = serializers.CharField(required=False, label='Zip code') phone = serializers.CharField(required=False, label='Phone') mobile = serializers.CharField(required=False, label='Mobile') date_of_birth = serializers.CharField(required=False, label='Date of birth') request_membership = serializers.BooleanField(default=False) licence = serializers.FileField(required=False, label='Licence') avatar = serializers.ImageField(required=False, label='Avatar') def validate(self, data): code = data.get('code') email = data.get('email') user = User.objects.get(email=email) reg_profile = Registration.objects.get(code=code) if reg_profile != user.registration: raise ValidationError( message='Dieser Code gehört nicht zu dieser Email!') if data.get('password') != data.get('password_repeat'): raise ValidationError(message='Passwörter stimmen nicht überein!') return data def save(self, validated_data): email = validated_data.get('email') user = User.objects.get(email=email) user.username = validated_data.get('email') user.first_name = validated_data.get('first_name') user.last_name = validated_data.get('last_name') user.is_active = True user.set_password(validated_data.get('password')) user.street = validated_data.get('street') user.address_appendix = validated_data.get('address_appendix ') user.city = validated_data.get('city') user.country = validated_data.get('country') user.zip_code = validated_data.get('zip_code') user.phone = validated_data.get('phone') user.mobile = validated_data.get('mobile') user.date_of_birth = validated_data.get('date_of_birth') user.licence = validated_data.get('licence') user.avatar = validated_data.get('avatar') user.request_membership = validated_data.get('request_membership') user.registration.code_used = True user.save() user.registration.save() # post_user_registration_validation.send(sender=User, user=user) return user
class ResetPasswordEmailRequestSerializer(serializers.Serializer): email = serializers.EmailField(min_length=2) redirect_url = serializers.CharField(max_length=500, required=False) class Meta: fields = ['email']
class UserLoginSerializer(serializers.Serializer): """ Serializer for validating expected email/password credentials for login request. """ email = serializers.EmailField(max_length=300, required=True) password = serializers.CharField(required=True, write_only=True)
class CreatorSerializer(CreatorMinimalSerializer): phone = serializers.CharField(allow_blank=True, default="") email = serializers.EmailField(allow_blank=True, default="") dateOfBirth = serializers.DateField(read_only=True) location = serializers.SlugRelatedField(slug_field='name', queryset=Location.objects.all()) tags = serializers.SlugRelatedField(slug_field="name", read_only=True, many=True) class Meta: model = Creator fields = ('id', 'username', 'email', 'phone', 'avatar', 'location', 'comments', 'dateOfBirth', 'bio', 'followers', 'following_count', 'projects_count', 'members_count', 'tags') read_only_fields = [ "id", "projects_count", "following_count", "dateOfBirth", "tags" ] def validate_email(self, email): if (len(email) == 0 and len(self.initial_data.get("phone", "")) == 0): raise serializers.ValidationError( _("you must provide either email or phone number")) if (Creator.objects.filter(email=email).count() > 0 and email != ""): if email == self.context.get("request").user.email: return email raise serializers.ValidationError( _("a user with that email address already exists")) if (self.context.get("request").user.email): raise serializers.ValidationError( _("to edit this field mail [email protected]")) return email def validate_phone(self, phone): if (len(phone) == 0 and len(self.initial_data.get("email", "")) == 0): raise serializers.ValidationError( _("you must provide either email or phone number")) if re.search(r'^\+\d{9,15}$', phone) == None and phone != "": raise serializers.ValidationError( _("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed." )) if (Creator.objects.filter(phone=phone).count() > 0 and phone != ""): if phone == self.context.get("request").user.phone: return phone raise serializers.ValidationError( _("a user with that phone number already exists")) if (self.context.get("request").user.phone): raise serializers.ValidationError( _("to edit this field mail [email protected]")) return phone def update(self, user, validated_data): creator = super().update(user, validated_data) phone_number = PhoneNumber.objects.filter(user=creator) email_address = EmailAddress.objects.filter(user=creator) if (len(phone_number) < 1): setup_user_phone(creator) if (len(email_address) < 1): setup_user_email(self.context.get("request"), creator, []) return creator
class CustomRegisterSerializer(RegisterSerializer): phone = serializers.CharField(allow_blank=True, default="") email = serializers.EmailField(allow_blank=True, default="") dateOfBirth = serializers.DateField() location = serializers.SlugRelatedField(slug_field='name', queryset=Location.objects.all()) bio = serializers.CharField(allow_blank=True, default="", max_length=255) subscribe = serializers.BooleanField(default=False) def validate_email(self, email): if (len(email) == 0 and len(self.initial_data.get("phone", "")) == 0): raise serializers.ValidationError( _("you must provide either email or phone number")) if (Creator.objects.filter(email=email).count() > 0 and email != ""): raise serializers.ValidationError( _("A user with that email address already exists")) return email def validate_phone(self, phone): if (len(phone) == 0 and len(self.initial_data.get("email", "")) == 0): raise serializers.ValidationError( _("you must provide either email or phone number")) if re.search(r'^\+\d{9,15}$', phone) == None and phone != "": raise serializers.ValidationError( _("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed." )) if (Creator.objects.filter(phone=phone).count() > 0 and phone != ""): raise serializers.ValidationError( _("A user with that phone number already exists")) return phone def validate_dateOfBirth(self, dateOfBirth): if ((date.today() - dateOfBirth).days < 0): raise serializers.ValidationError( _("Date of Birth must be less than today's date")) return dateOfBirth def validate_location(self, location): if (len(location.name) < 1): raise serializers.ValidationError(_("Location is required")) return location def get_cleaned_data(self): data_dict = super().get_cleaned_data() data_dict['phone'] = self.validated_data.get('phone', '') data_dict['dateOfBirth'] = self.validated_data.get('dateOfBirth', '') data_dict['location'] = self.validated_data.get('location', '') data_dict['bio'] = self.validated_data.get('bio', '') data_dict['subscribe'] = self.validated_data.get('subscribe', '') return data_dict def save(self, request): creator = super().save(request) setup_user_phone(creator) return creator
class OrganizationSignupSerializer(serializers.Serializer): first_name: serializers.Field = serializers.CharField(max_length=128) email: serializers.Field = serializers.EmailField(validators=[ validators.UniqueValidator( queryset=User.objects.all(), message="There is already an account with this email address.") ]) password: serializers.Field = serializers.CharField(allow_null=True) organization_name: serializers.Field = serializers.CharField( max_length=128, required=False, allow_blank=True) email_opt_in: serializers.Field = serializers.BooleanField(default=True) def validate_password(self, value): if value is not None: password_validation.validate_password(value) return value def create(self, validated_data, **kwargs): is_instance_first_user: bool = not User.objects.exists() organization_name = validated_data.pop("organization_name", validated_data["first_name"]) self._organization, self._team, self._user = User.objects.bootstrap( organization_name=organization_name, create_team=self.create_team, **validated_data, ) user = self._user # Temp (due to FF-release [`new-onboarding-2822`]): Activate the setup/onboarding process if applicable if self.enable_new_onboarding(user): self._organization.setup_section_2_completed = False self._organization.save() login( self.context["request"], user, backend="django.contrib.auth.backends.ModelBackend", ) report_user_signed_up( user.distinct_id, is_instance_first_user=is_instance_first_user, is_organization_first_user=True, new_onboarding_enabled=( not self._organization.setup_section_2_completed), backend_processor="OrganizationSignupSerializer", ) return user def create_team(self, organization: Organization, user: User) -> Team: if self.enable_new_onboarding(user): return create_demo_team(organization=organization) else: return Team.objects.create_with_data(user=user, organization=organization) def to_representation(self, instance) -> Dict: data = UserBasicSerializer(instance=instance).data data[ "redirect_url"] = "/personalization" if self.enable_new_onboarding( ) else "/ingestion" return data def enable_new_onboarding(self, user: Optional[User] = None) -> bool: if user is None: user = self._user return posthoganalytics.feature_enabled( "new-onboarding-2822", user.distinct_id) or settings.DEBUG
class OTPSerializer(serializers.Serializer): """ This Serializer is for sending OTP & verifying destination via otp. is_login: Set is_login true if trying to login via OTP destination: Required. Place where sending OTP email: Fallback in case of destination is a mobile number verify_otp: OTP in the 2nd step of flow Examples -------- 1. Request an OTP for verifying >>> OTPSerializer(data={"destination": "*****@*****.**"}) Or for mobile number as destination >>> OTPSerializer(data={"destination": "88xx6xx5xx", >>> "email": "*****@*****.**"}) 2. Send OTP to verify >>> OTPSerializer(data={"destination": "*****@*****.**", >>> "verify_otp": 2930432}) Or for mobile number as destination >>> OTPSerializer(data={"destination": "88xx6xx5xx", >>> "email": "*****@*****.**", >>> "verify_otp": 2930433}) For log in, just add is_login to request >>> OTPSerializer(data={"destination": "*****@*****.**", >>> "is_login": True}) >>> OTPSerializer(data={"destination": "88xx6xx5xx", >>> "email": "*****@*****.**", >>> "verify_otp": 2930433, "is_login": True}) Author: Himanshu Shankar (https://himanshus.com) """ email = serializers.EmailField(required=False) is_login = serializers.BooleanField(default=False) verify_otp = serializers.CharField(required=False) destination = serializers.CharField(required=True) def get_user(self, prop: str, destination: str) -> User: """ Provides current user on the basis of property and destination provided. Parameters ---------- prop: str Can be M or E destination: str Provides value of property Returns ------- user: User """ from .models import User from .variables import MOBILE if prop == MOBILE: try: user = User.objects.get(mobile=destination) except User.DoesNotExist: user = None else: try: user = User.objects.get(email=destination) except User.DoesNotExist: user = None return user def validate(self, attrs: dict) -> dict: """ Performs custom validation to check if any user exists with provided details. Parameters ---------- attrs: dict Returns ------- attrs: dict Raises ------ NotFound: If user is not found ValidationError: Email field not provided """ from django.core.validators import EmailValidator, ValidationError from rest_framework.exceptions import NotFound from .variables import EMAIL, MOBILE validator = EmailValidator() try: validator(attrs["destination"]) except ValidationError: attrs["prop"] = MOBILE else: attrs["prop"] = EMAIL user = self.get_user(attrs.get("prop"), attrs.get("destination")) if not user: if attrs["is_login"]: raise NotFound(_("No user exists with provided details")) if "email" not in attrs.keys() and "verify_otp" not in attrs.keys( ): raise serializers.ValidationError( _("email field is compulsory while verifying a" " non-existing user's OTP.")) else: attrs["email"] = user.email attrs["user"] = user return attrs
class EmailSerializer(serializers.ModelSerializer): email = serializers.EmailField() class Meta: model = CustomUser fields = ("email", )
class PasswordResetSerializer(serializers.Serializer): """This serializer is for password reset API. Params otp: OTP received on your email/mobile email: Email of the user whose password you're trying to reset password: new password for the user """ otp = serializers.CharField(required=True) email = serializers.EmailField(required=True) password = serializers.CharField(required=True) def get_user(self, destination: str) -> User: """Provides current user on the basis of property and destination provided. Parameters ---------- destination: str Provides value of property Returns ------- user: User """ from .models import User try: user = User.objects.get(email=destination) except User.DoesNotExist: user = None return user def validate(self, attrs: dict) -> dict: """Performs custom validation to check if any user exists with provided email. Parameters ---------- attrs: dict Returns ------- attrs: dict Raises ------ NotFound: If user is not found ValidationError: Email field not provided """ from django.core.validators import EmailValidator from rest_framework.exceptions import NotFound validator = EmailValidator() validator(attrs.get("email")) user = self.get_user(attrs.get("email")) if not user: raise NotFound(_("User with the provided email does not exist.")) return attrs
class PeopleImportSerializer(serializers.Serializer): index = serializers.IntegerField(min_value=0, required=True) name = serializers.CharField(max_length=128, allow_blank=True, required=False) _id = serializers.CharField(max_length=64, allow_blank=True, required=False) guid = serializers.CharField(max_length=64, allow_blank=True, required=False) has_died = serializers.BooleanField(default=False, required=False) balance = serializers.CharField(max_length=64, allow_blank=True, required=False) picture = serializers.CharField(max_length=256, allow_blank=True, required=False) age = serializers.IntegerField(min_value=0, required=False) eyeColor = serializers.CharField(max_length=32, allow_blank=True, required=False) gender = serializers.CharField(max_length=16, allow_blank=True, required=False) email = serializers.EmailField(max_length=64, allow_blank=True, required=False) phone = serializers.CharField(max_length=32, allow_blank=True, required=False) address = serializers.CharField(max_length=256, allow_blank=True, required=False) about = serializers.CharField(allow_blank=True, required=False) registered = serializers.DateTimeField(input_formats=[ 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]] [+HH:MM|-HH:MM|Z]', '%Y-%m-%dT%H:%M:%S %z', 'iso-8601' ], required=False) greeting = serializers.CharField(allow_blank=True, required=False) company_id = serializers.IntegerField(required=False) favourite_fruits = StringListField(required=False) favourite_vegetables = StringListField(required=False) tags = StringListField(required=False) friends = serializers.ListField(required=False) favouriteFood = StringListField(required=False) def create(self, validated_data): friends_list = None favorite_food = None company_id = None if 'friends' in validated_data: friends_list = validated_data.pop('friends') if 'favouriteFood' in validated_data: favorite_food = validated_data.pop('favouriteFood') if 'company_id' in validated_data: company_id = validated_data.pop('company_id') person, created = People.objects.update_or_create( index=validated_data['index'], defaults=validated_data) if person.favourite_vegetables is None: person.favourite_vegetables = [] if person.favourite_fruits is None: person.favourite_fruits = [] # if created: # person.save() if company_id: company, created = Companies.objects.get_or_create( index=company_id) if created: company.save() person.company = company for food in favorite_food: if food.strip(',. ').lower() in VEGETABLES_SET: person.favourite_vegetables.append(food) else: person.favourite_fruits.append(food) for friend_data in friends_list: friend, created = People.objects.get_or_create(**friend_data) if created: friend.save() if person.index != friend.index: person.friends.add(friend) person.save() return person def update(self, instance, validated_data): for key, value in validated_data.items(): setattr(instance, key, value) instance.save() return instance
class EmailSerializer(serializers.Serializer): to_email = serializers.EmailField(required=True) from_email = serializers.EmailField(required=True) reply_to = serializers.EmailField(required=False) body = serializers.CharField(required=True) subject = serializers.CharField(max_length=200)
class RegistrationSerializer(serializers.ModelSerializer): """This class handles serializing and deserializing of Registration objects""" firstName = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly provide us with your First name" }) lastName = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly provide us with your Last name", }) dateOfBirth = serializers.DateField( required=True, error_messages={ "required": "Hello, Kindly provide us with your date of birth", }) phoneNumber = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly provide us with a working Phone Number that we can contact you on", }) phoneNumberOwner = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly let us know who owns this Phone number", }) email = serializers.EmailField( required=True, error_messages={ "required": "Hello, Kindly provide us with a working Email that we can contact you on", }) emailOwner = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly let us know who owns this Email", }) nextOfKin1Title = serializers.CharField(required=True, error_messages={ "required": "Hello, How are you related", }) nextOfKin1Name = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly provide us with the Name of your Next of kin", }) nextOfKin1Number = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly provide us with the Phone number of your next of kin", }) tribe = serializers.CharField(required=True, error_messages={ "required": "Hello, Kindly let us know your Tribe", }) homeChurch = serializers.CharField( required=True, error_messages={ "required": "Hello, Kindly let us know where you fellowship from", }) sponsored = serializers.CharField( required=True, error_messages={ "required": "Hello, Are you sponsered by Compassion", }) class Meta: model = Registration fields = ('firstName', 'lastName', 'dateOfBirth', 'phoneNumber', 'phoneNumberOwner', 'email', 'emailOwner', 'nextOfKin1Title', 'nextOfKin1Name', 'nextOfKin1Number', 'tribe', 'homeChurch', 'sponsored') read_only_fields = ('createdBy', 'publish_status', 'createdAt', 'updatedAt', 'delete_status')
class UserProjectRoleSerializer(serializers.ModelSerializer): name = serializers.CharField(source='user.get_full_name') email = serializers.EmailField(source='user.email') exo_role = serializers.CharField(read_only=True) class Meta: model = UserProjectRole fields = ['name', 'email', 'exo_role', 'status', 'pk'] def validate_email(self, value): exo_role = self.context.get('request').data.get('exo_role') if exo_role == settings.EXO_ROLE_CODE_SPRINT_OTHER: is_superuser = get_user_model().objects.filter( email=value, is_superuser=True).exists() if not is_superuser: raise ValidationError('User must have superuser perms.') return value def create(self, validated_data): exo_role = self.context.get('request').data.get('exo_role') project = validated_data.get('project') user_from = validated_data.get('user_from') user_data = validated_data.get('user') name = user_data.get('get_full_name') email = user_data.get('email') if exo_role == settings.EXO_ROLE_CODE_SPRINT_PARTICIPANT: new_user = project.add_user_project_member(user_from=user_from, name=name, email=email) elif exo_role == settings.EXO_ROLE_CODE_SPRINT_OBSERVER: new_user = project.add_user_project_supervisor(user_from=user_from, name=name, email=email) elif exo_role == settings.EXO_ROLE_CODE_SPRINT_OTHER: new_user = project.add_user_project_staff(user_from=user_from, name=name, email=email) elif exo_role == settings.EXO_ROLE_CODE_DELIVERY_MANAGER: new_user = project.add_user_project_delivery_manager( user_from=user_from, name=name, email=email) return project.users_roles.filter_by_user(new_user) \ .filter_by_exo_role_code(exo_role).get() def update(self, instance, validated_data): user = instance.user user_data = validated_data.get('user') email = user_data.get('email') email_valid = EmailAddress.objects.add_user_email(user, email) if email_valid: email_address = EmailAddress.objects.get(email=email) email_address.set_primary() user.refresh_from_db() user.full_name = user_data.get('get_full_name') user.short_name = user_data.get('get_full_name').split(' ')[0] user.save() else: new_user = get_user_model().objects.get(emailaddress__email=email) instance.user = new_user instance.save() return instance
class ModeratorSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'full_name', 'id', 'permission_group', ]) id = IDField(source='_id', required=False, allow_null=True) type = TypeField() full_name = ser.CharField( source='fullname', required=False, label='Full name', help_text='Display name used in the general user interface', max_length=186) permission_group = ser.CharField(required=True) email = ser.EmailField(required=False, write_only=True, validators=[validate_email]) class Meta: type_ = 'moderators' def get_absolute_url(self, obj): return absolute_reverse( 'moderators:provider-moderator-detail', kwargs={ 'provider_id': self.context['request'].parser_context['kwargs']['version'], 'moderator_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'], }, ) def create(self, validated_data): auth = get_user_auth(self.context['request']) user_id = validated_data.pop('_id', '') address = validated_data.pop('email', '') provider = self.context['provider'] context = { 'referrer': auth.user, } if user_id and address: raise ValidationError('Cannot specify both "id" and "email".') user = None if user_id: user = OSFUser.load(user_id) elif address: try: email = Email.objects.get(address=address.lower()) except Email.DoesNotExist: full_name = validated_data.pop('fullname', '') if not full_name: raise ValidationError( '"full_name" is required when adding a moderator via email.' ) user = OSFUser.create_unregistered(full_name, email=address) user.add_unclaimed_record( provider, referrer=auth.user, given_name=full_name, email=address, ) user.save() claim_url = user.get_claim_url(provider._id, external=True) context['claim_url'] = claim_url else: user = email.user else: raise ValidationError('Must specify either "id" or "email".') if not user: raise ValidationError('Unable to find specified user.') context['user'] = user context['provider'] = provider if bool(get_perms(user, provider)): raise ValidationError('Specified user is already a moderator.') if 'claim_url' in context: template = mails.CONFIRM_EMAIL_MODERATION(provider) else: template = mails.MODERATOR_ADDED(provider) perm_group = validated_data.pop('permission_group', '') if perm_group not in REVIEW_GROUPS: raise ValidationError('Unrecognized permission_group') context[ 'notification_settings_url'] = '{}reviews/preprints/{}/notifications'.format( DOMAIN, provider._id) context['provider_name'] = provider.name context['is_reviews_moderator_notification'] = True context['is_admin'] = perm_group == ADMIN provider.add_to_group(user, perm_group) setattr(user, 'permission_group', perm_group) # Allows reserialization mails.send_mail(user.username, template, mimetype='html', **context) return user def update(self, instance, validated_data): provider = self.context['provider'] perm_group = validated_data.get('permission_group') if perm_group == instance.permission_group: return instance try: provider.remove_from_group(instance, instance.permission_group, unsubscribe=False) except ValueError as e: raise ValidationError(str(e)) provider.add_to_group(instance, perm_group) setattr(instance, 'permission_group', perm_group) return instance
class PhoneOTPSerializers(serializers.Serializer): email = serializers.EmailField(required=False) phone = serializers.IntegerField(required=False) otp_sent = serializers.CharField()
class UpdateUserSerializer(serializers.Serializer): def __init__(self, *args, **kwargs): serializers.Serializer.__init__(self, *args, **kwargs) self.user_id = self.context['user_id'] first_name = serializers.CharField( max_length=200, validators=[ RegexValidator( r'^[a-zA-Z\'\- ]+$', "Please enter a valid first name. It can only contain the following characters: -\and a space." ) ], error_messages={ 'required': "Please enter your first name", 'max_length': "Your first name cannot exceed 200 characters" }) last_name = serializers.CharField( max_length=200, validators=[ RegexValidator( r'^[a-zA-Z\'\- ]+$', "Please enter a valid first name. It can only contain the following characters: -\and a space." ) ], error_messages={ 'required': "Please enter your name", 'max_length': "Your name cannot exceed 200 characters" }) pseudo = serializers.CharField(max_length=20, error_messages={ 'required': "Please enter your pseudo", 'max_length': "Your name cannot exceed 20 characters" }) email = serializers.EmailField( max_length=200, error_messages={ 'required': "Please enter your email", 'invalid': "Please enter a valid email address in the format: [email protected]", 'max_length': "Your email cannot exceed 200 characters" }) password = serializers.CharField( max_length=200, error_messages={ 'max_length': "Your password cannot exceed 200 characters." }) def validate_email(self, value): user = User.objects.filter(email=value, is_active=True).first() current_user = User.objects.get(public_id=self.user_id, is_active=True) if user and current_user.id != user.id: raise ValidationError("An account already uses this email address") return value def validate_password(self, value): user = User.objects.get(public_id=self.user_id, is_active=True) password_match = check_password(value, user.password) if not password_match: raise ValidationError("Your account password was not recognized") return value
class PeopleSerializer(serializers.Serializer): """ Serializer for people object """ display_name = serializers.CharField(max_length=200) email_address = serializers.EmailField(max_length=200) title = serializers.CharField(max_length=200)
class UserSubscriptionSerializer(serializers.Serializer): first_name = serializers.CharField( max_length=30, validators=[ RegexValidator( r'^[a-zA-ZàâäôéèëêïîçùûüÿæœÀÂÄÔÉÈËÊÏΟÇÙÛÜÆŒàèéìíîòóùúÀÈÉÌÍÎÒÓÙÚáéíñóúüÁÉÍÑÓÚÜ\'\- ]+$', "Please enter a valid first name. It can only contain the following special characters: -\' and space" ) ], error_messages={ 'required': "Please enter your first name", 'max_length': "Your first name cannot exceed 30 characters" }) last_name = serializers.CharField( max_length=30, validators=[ RegexValidator( r'^[a-zA-ZàâäôéèëêïîçùûüÿæœÀÂÄÔÉÈËÊÏΟÇÙÛÜÆŒàèéìíîòóùúÀÈÉÌÍÎÒÓÙÚáéíñóúüÁÉÍÑÓÚÜ\'\- ]+$', "Please enter a valid name. It can only contain the following special characters: -\' and a space." ) ], error_messages={ 'required': "Please enter your name", 'max_length': "Your name cannot exceed 30 characters" }) email = serializers.EmailField( max_length=200, error_messages={ 'required': "Please enter your email", 'invalid': "Please enter a valid email address in the format: [email protected]", 'max_length': "Your email cannot exceed 200 characters" }) password = serializers.CharField( max_length=200, validators=[ RegexValidator( r'^(?=.*\d).{8,}$', "Your password must contain at least eight characters, one number and one letter." ) ], error_messages={ 'required': "Please enter your password", 'max_length': "Your password cannot exceed 200 characters." }) confirm_password = serializers.CharField( error_messages={'required': "Please confirm your password"}) def __init__(self, *args, **kwargs): serializers.Serializer.__init__(self, *args, **kwargs) def validate_email(self, value): user = User.objects.filter(email=value, is_active=True).first() if user: raise ValidationError("An account already uses this email address") return value def validate_confirm_password(self, value): # Check if password is matching with his confirmation password = self.initial_data['password'] if value != password: raise ValidationError( "Your password confirmation must be the same as your password") return value
class EmailAuthSerializer(AbstractBaseAliasAuthenticationSerializer): @property def alias_type(self): return 'email' email = serializers.EmailField()
class ResetPasswordEmailRequestSerializer(serializers.Serializer): email = serializers.EmailField(min_length=2) class Meta: fields = ['email']
class FBCreateSerializer(serializers.Serializer): name = serializers.CharField(max_length=50, allow_blank=False) phone = serializers.RegexField(regex='\d+', allow_blank=False) email = serializers.EmailField(allow_blank=False) message = serializers.CharField(allow_blank=False)
class UserSerializerWithToken(serializers.ModelSerializer): CITIZEN = "citizen" AUTHORITY = "authority" TYPE_CHOICES = [ (CITIZEN, "citizen"), (AUTHORITY, "authority"), ] email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField(required=True, min_length=8, write_only=True) first_name = serializers.CharField(required=True, min_length=2) last_name = serializers.CharField(required=True, min_length=2) userType = serializers.ChoiceField(choices=TYPE_CHOICES, required=True) municipality = serializers.CharField(max_length=100, required=False) address = serializers.CharField(required=False) lng = serializers.DecimalField(max_digits=20, decimal_places=10, required=False) lat = serializers.DecimalField(max_digits=20, decimal_places=10, required=False) birthDate = serializers.DateField(required=False) img = serializers.ImageField(required=False) token = serializers.SerializerMethodField() def get_token(self, object): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(object) token = jwt_encode_handler(payload) return token def create(self, validated_data): print(validated_data) if validated_data['userType'] == "citizen": user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], password=validated_data['password'], email=validated_data['email'], userType=validated_data['userType'], municipality=validated_data['municipality'], address=validated_data['address'], lng=validated_data['lng'], lat=validated_data['lat'], birthDate=validated_data['birthDate'], ) else: user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], password=validated_data['password'], email=validated_data['email'], userType=validated_data['userType'], ) user.save() return user class Meta: model = User fields = "__all__"