Example #1
0
class BadgeUserProfileSerializerV1(serializers.Serializer):
    first_name = StripTagsCharField(max_length=30, allow_blank=True)
    last_name = StripTagsCharField(max_length=30, allow_blank=True)
    email = serializers.EmailField(source='primary_email', required=False)
    current_password = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=False)
    password = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=False, validators=[PasswordValidator()])
    slug = serializers.CharField(source='entity_id', read_only=True)
    agreed_terms_version = serializers.IntegerField(required=False)
    marketing_opt_in = serializers.BooleanField(required=False)
    user_permissions = serializers.SerializerMethodField(required=False)
    faculty = FacultySerializerV1(many=True,  allow_null=True)
    institution = InstitutionSerializerV1(read_only=True)

    class Meta:
        apispec_definition = ('BadgeUser', {})

    def get_user_permissions(self, obj):
        perms = obj.user_permissions.all() | Permission.objects.filter(group__user=obj)
        perms = list(x.codename for x in perms)
        if obj.is_staff:
            perms.insert(0, 'is_staff')
        if obj.is_superuser:
            perms.insert(0,'is_superuser')
        return json.dumps(perms)

    def create(self, validated_data):
        user = BadgeUser.objects.create(
            email=validated_data['primary_email'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
            plaintext_password=validated_data['password'],
            marketing_opt_in=validated_data.get('marketing_opt_in', False),
            request=self.context.get('request', None),
        )
        return user

    def update(self, user, validated_data):
        first_name = validated_data.get('first_name')
        last_name = validated_data.get('last_name')
        password = validated_data.get('password')
        current_password = validated_data.get('current_password')

        if first_name:
            user.first_name = first_name
        if last_name:
            user.last_name = last_name

        if password:
            if not current_password:
                raise serializers.ValidationError({'currrent_password': "******"})
            if user.check_password(current_password):
                user.set_password(password)
                notify_on_password_change(user)
            else:
                raise serializers.ValidationError({'currrent_password': "******"})

        if 'agreed_terms_version' in validated_data:
            user.agreed_terms_version = validated_data.get('agreed_terms_version')

        if 'marketing_opt_in' in validated_data:
            user.marketing_opt_in = validated_data.get('marketing_opt_in')

        user.save()
        return user

    def to_representation(self, instance):
        representation = super(BadgeUserProfileSerializerV1, self).to_representation(instance)

        latest = TermsVersion.cached.cached_latest()
        if latest:
            representation['latest_terms_version'] = latest.version
            if latest.version != instance.agreed_terms_version:
                representation['latest_terms_description'] = latest.short_description

        return representation
Example #2
0
class BadgeUserProfileSerializerV1(serializers.Serializer):
    first_name = StripTagsCharField(max_length=30, allow_blank=True)
    last_name = StripTagsCharField(max_length=30, allow_blank=True)
    email = serializers.EmailField(source='primary_email',
                                   required=False,
                                   allow_blank=True,
                                   allow_null=True)
    url = serializers.ListField(read_only=True, source='cached_verified_urls')
    telephone = serializers.ListField(read_only=True,
                                      source='cached_verified_phone_numbers')
    current_password = serializers.CharField(style={'input_type': 'password'},
                                             write_only=True,
                                             required=False)
    password = serializers.CharField(style={'input_type': 'password'},
                                     write_only=True,
                                     required=False,
                                     validators=[PasswordValidator()])
    slug = serializers.CharField(source='entity_id', read_only=True)
    agreed_terms_version = serializers.IntegerField(required=False)
    marketing_opt_in = serializers.BooleanField(required=False)
    has_password_set = serializers.SerializerMethodField()
    source = serializers.CharField(write_only=True, required=False)

    def get_has_password_set(self, obj):
        return is_password_usable(obj.password)

    class Meta:
        apispec_definition = ('BadgeUser', {
            'properties':
            OrderedDict([
                ('source', {
                    'type': "string",
                    'format': "string",
                    'description': "Ex: mozilla",
                }),
            ])
        })

    def create(self, validated_data):
        user = BadgeUser.objects.create(
            email=validated_data.get('primary_email'),
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
            plaintext_password=validated_data['password'],
            marketing_opt_in=validated_data.get('marketing_opt_in', False),
            request=self.context.get('request', None),
            source=validated_data.get('source', ''),
        )
        return user

    def update(self, user, validated_data):
        first_name = validated_data.get('first_name')
        last_name = validated_data.get('last_name')
        password = validated_data.get('password')
        current_password = validated_data.get('current_password')

        if first_name:
            user.first_name = first_name
        if last_name:
            user.last_name = last_name

        if password:
            if not current_password:
                raise serializers.ValidationError(
                    {'current_password': "******"})
            if user.check_password(current_password):
                user.set_password(password)
                notify_on_password_change(user)
            else:
                raise serializers.ValidationError(
                    {'current_password': "******"})

        if 'agreed_terms_version' in validated_data:
            user.agreed_terms_version = validated_data.get(
                'agreed_terms_version')

        if 'marketing_opt_in' in validated_data:
            user.marketing_opt_in = validated_data.get('marketing_opt_in')

        user.save()
        return user

    def to_representation(self, instance):
        representation = super(BadgeUserProfileSerializerV1,
                               self).to_representation(instance)

        latest = TermsVersion.cached.cached_latest()
        if latest:
            representation['latest_terms_version'] = latest.version
            if latest.version != instance.agreed_terms_version:
                representation[
                    'latest_terms_description'] = latest.short_description

        return representation
Example #3
0
class BadgeUserSerializerV2(DetailSerializerV2):
    firstName = StripTagsCharField(source='first_name',
                                   max_length=30,
                                   allow_blank=True)
    lastName = StripTagsCharField(source='last_name',
                                  max_length=30,
                                  allow_blank=True)
    password = serializers.CharField(style={'input_type': 'password'},
                                     write_only=True,
                                     required=False,
                                     validators=[PasswordValidator()])
    currentPassword = serializers.CharField(style={'input_type': 'password'},
                                            write_only=True,
                                            required=False)
    emails = BadgeUserEmailSerializerV2(many=True,
                                        source='email_items',
                                        required=False)
    agreedTermsVersion = serializers.IntegerField(
        source='agreed_terms_version', required=False)
    marketingOptIn = serializers.BooleanField(source='marketing_opt_in',
                                              required=False)

    class Meta(DetailSerializerV2.Meta):
        model = BadgeUser
        apispec_definition = ('BadgeUser', {
            'properties':
            OrderedDict([
                ('entityId', {
                    'type': "string",
                    'format': "string",
                    'description': "Unique identifier for this BadgeUser",
                }),
                ('entityType', {
                    'type': "string",
                    'format': "string",
                    'description': "\"BadgeUser\"",
                }),
                ('firstName', {
                    'type': "string",
                    'format': "string",
                    'description': "Given name",
                }),
                ('lastName', {
                    'type': "string",
                    'format': "string",
                    'description': "Family name",
                }),
            ]),
        })

    def update(self, instance, validated_data):
        password = validated_data.pop(
            'password') if 'password' in validated_data else None
        current_password = validated_data.pop(
            'currentPassword') if 'currentPassword' in validated_data else None
        super(BadgeUserSerializerV2, self).update(instance, validated_data)

        if password:
            if not current_password:
                raise serializers.ValidationError(
                    {'currrent_password': "******"})
            if instance.check_password(current_password):
                instance.set_password(password)
                notify_on_password_change(instance)
            else:
                raise serializers.ValidationError(
                    {'currrent_password': "******"})

        instance.badgrapp = BadgrApp.objects.get_current(
            request=self.context.get('request', None))

        instance.save()
        return instance

    def to_representation(self, instance):
        representation = super(BadgeUserSerializerV2,
                               self).to_representation(instance)

        latest = TermsVersion.cached.cached_latest()
        if latest:
            representation['latestTermsVersion'] = latest.version
            if latest.version != instance.agreed_terms_version:
                representation[
                    'latestTermsDescription'] = latest.short_description

        if not self.context.get('isSelf'):
            fields_shown_only_to_self = ['emails']
            for f in fields_shown_only_to_self:
                if f in representation['result'][0]:
                    del representation['result'][0][f]
        return representation
class BadgeUserSerializerV2(DetailSerializerV2):
    firstName = StripTagsCharField(source='first_name', max_length=30, allow_blank=True)
    lastName = StripTagsCharField(source='last_name', max_length=30, allow_blank=True)
    password = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=False, validators=[PasswordValidator()])
    currentPassword = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=False)
    emails = BadgeUserEmailSerializerV2(many=True, source='email_items', required=False)
    url = serializers.ListField(read_only=True, source='cached_verified_urls')
    telephone = serializers.ListField(read_only=True, source='cached_verified_phone_numbers')
    agreedTermsVersion = serializers.IntegerField(source='agreed_terms_version', required=False)
    hasAgreedToLatestTermsVersion = serializers.SerializerMethodField(read_only=True)
    marketingOptIn = serializers.BooleanField(source='marketing_opt_in', required=False)
    badgrDomain = serializers.CharField(read_only=True, max_length=255, source='badgrapp')
    hasPasswordSet = serializers.SerializerMethodField('get_has_password_set')
    recipient = serializers.SerializerMethodField(read_only=True)

    def get_has_password_set(self, obj):
        return is_password_usable(obj.password)

    def get_recipient(self, obj):
        primary_email = next((e for e in obj.cached_emails() if e.primary), None)
        if primary_email:
            return dict(type='email', identity=primary_email.email)
        identifier = obj.userrecipientidentifier_set.filter(verified=True).order_by('pk').first()
        if identifier:
            return dict(type=identifier.type, identity=identifier.identifier)
        return None

    def get_hasAgreedToLatestTermsVersion(self, obj):
        latest = TermsVersion.cached.cached_latest()
        return obj.agreed_terms_version == latest.version

    class Meta(DetailSerializerV2.Meta):
        model = BadgeUser
        apispec_definition = ('BadgeUser', {
            'properties': OrderedDict([
                ('entityId', {
                    'type': "string",
                    'format': "string",
                    'description': "Unique identifier for this BadgeUser",
                }),
                ('entityType', {
                    'type': "string",
                    'format': "string",
                    'description': "\"BadgeUser\"",
                }),
                ('firstName', {
                    'type': "string",
                    'format': "string",
                    'description': "Given name",
                }),
                ('lastName', {
                    'type': "string",
                    'format': "string",
                    'description': "Family name",
                }),
            ]),
        })

    def update(self, instance, validated_data):
        password = validated_data.pop('password') if 'password' in validated_data else None
        current_password = validated_data.pop('currentPassword') if 'currentPassword' in validated_data else None
        super(BadgeUserSerializerV2, self).update(instance, validated_data)

        if password:
            if not current_password:
                raise serializers.ValidationError({'current_password': "******"})
            if instance.check_password(current_password):
                instance.set_password(password)
                notify_on_password_change(instance)
            else:
                raise serializers.ValidationError({'current_password': "******"})

        instance.badgrapp = BadgrApp.objects.get_current(request=self.context.get('request', None))

        instance.save()
        return instance

    def to_representation(self, instance):
        representation = super(BadgeUserSerializerV2, self).to_representation(instance)

        latest = TermsVersion.cached.cached_latest()
        if latest:
            representation['latestTermsVersion'] = latest.version
            if latest.version != instance.agreed_terms_version:
                representation['latestTermsDescription'] = latest.short_description

        if not self.context.get('isSelf'):
            fields_shown_only_to_self = ['emails']
            for f in fields_shown_only_to_self:
                if f in representation['result'][0]:
                    del representation['result'][0][f]
        return representation