Passed
Push — master ( cb96a6...03dbbf )
by Piotr
01:10
created

UserSerializer.update()   A

Complexity

Conditions 4

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.2
cc 4
1
from django.contrib.auth import authenticate, get_user_model
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
introduced by
Unable to import 'django.contrib.auth'
Loading history...
2
from django.db import IntegrityError, transaction
0 ignored issues
show
introduced by
Unable to import 'django.db'
Loading history...
3
4
from rest_framework import exceptions, serializers
0 ignored issues
show
introduced by
Unable to import 'rest_framework'
Loading history...
5
6
from djoser import constants, utils
7
from djoser.compat import (
8
    get_user_email, get_user_email_field_name, validate_password
9
)
10
from djoser.conf import settings
11
12
User = get_user_model()
0 ignored issues
show
Coding Style Naming introduced by
The name User does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
13
14
15
class UserSerializer(serializers.ModelSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
16
    class Meta:
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
introduced by
Old-style class defined.
Loading history...
Coding Style introduced by
This class has no __init__ method.
Loading history...
17
        model = User
18
        fields = tuple(User.REQUIRED_FIELDS) + (
19
            User._meta.pk.name,
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _meta was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
20
            User.USERNAME_FIELD,
21
        )
22
        read_only_fields = (User.USERNAME_FIELD,)
23
24
    def update(self, instance, validated_data):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
25
        email_field = get_user_email_field_name(User)
26
        if settings.SEND_ACTIVATION_EMAIL and email_field in validated_data:
27
            instance_email = get_user_email(instance)
28
            if instance_email != validated_data[email_field]:
29
                instance.is_active = False
30
                instance.save(update_fields=['is_active'])
31
        return super(UserSerializer, self).update(instance, validated_data)
32
33
34
class UserRegistrationSerializer(serializers.ModelSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
35
    password = serializers.CharField(
36
        style={'input_type': 'password'},
37
        write_only=True
38
    )
39
40
    default_error_messages = {
41
        'cannot_create_user': constants.CANNOT_CREATE_USER_ERROR,
42
    }
43
44
    class Meta:
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
introduced by
Old-style class defined.
Loading history...
Coding Style introduced by
This class has no __init__ method.
Loading history...
45
        model = User
46
        fields = tuple(User.REQUIRED_FIELDS) + (
47
            User.USERNAME_FIELD, User._meta.pk.name, 'password',
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _meta was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
48
        )
49
50
    def validate_password(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
51
        validate_password(value)
52
        return value
53
54
    def create(self, validated_data):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
55
        try:
56
            user = self.perform_create(validated_data)
57
        except IntegrityError:
58
            raise serializers.ValidationError(
59
                self.error_messages['cannot_create_user']
60
            )
61
62
        return user
63
64
    def perform_create(self, validated_data):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
65
        with transaction.atomic():
66
            user = User.objects.create_user(**validated_data)
67
            if settings.SEND_ACTIVATION_EMAIL:
68
                user.is_active = False
69
                user.save(update_fields=['is_active'])
70
        return user
71
72
73
class LoginSerializer(serializers.Serializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
74
    password = serializers.CharField(
75
        required=False, style={'input_type': 'password'}
76
    )
77
78
    default_error_messages = {
79
        'inactive_account': constants.INACTIVE_ACCOUNT_ERROR,
80
        'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR,
81
    }
82
83
    def __init__(self, *args, **kwargs):
84
        super(LoginSerializer, self).__init__(*args, **kwargs)
85
        self.user = None
86
        self.fields[User.USERNAME_FIELD] = serializers.CharField(
87
            required=False
88
        )
89
90
    def validate(self, attrs):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
91
        self.user = authenticate(
92
            username=attrs.get(User.USERNAME_FIELD),
93
            password=attrs.get('password')
94
        )
95
96
        self._validate_user_exists(self.user)
97
        self._validate_user_is_active(self.user)
98
        return attrs
99
100
    def _validate_user_exists(self, user):
101
        if not user:
102
            raise serializers.ValidationError(
103
                self.error_messages['invalid_credentials']
104
            )
105
106
    def _validate_user_is_active(self, user):
107
        if not user.is_active:
108
            raise serializers.ValidationError(
109
                self.error_messages['inactive_account']
110
            )
111
112
113
class PasswordResetSerializer(serializers.Serializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
114
    email = serializers.EmailField()
115
116
    default_error_messages = {
117
        'email_not_found': constants.EMAIL_NOT_FOUND
118
    }
119
120
    def validate_email(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
121
        users = self.context['view'].get_users(value)
122
        if settings.PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND and not users:
123
            raise serializers.ValidationError(
124
                self.error_messages['email_not_found']
125
            )
126
        return value
127
128
129
class UidAndTokenSerializer(serializers.Serializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
130
    uid = serializers.CharField()
131
    token = serializers.CharField()
132
133
    default_error_messages = {
134
        'invalid_token': constants.INVALID_TOKEN_ERROR,
135
        'invalid_uid': constants.INVALID_UID_ERROR,
136
    }
137
138
    def validate_uid(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
139
        try:
140
            uid = utils.decode_uid(value)
141
            self.user = User.objects.get(pk=uid)
0 ignored issues
show
Coding Style introduced by
The attribute user was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
142
        except (User.DoesNotExist, ValueError, TypeError, OverflowError):
143
            raise serializers.ValidationError(
144
                self.error_messages['invalid_uid']
145
            )
146
        return value
147
148
    def validate(self, attrs):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
149
        attrs = super(UidAndTokenSerializer, self).validate(attrs)
150
        is_token_valid = self.context['view'].token_generator.check_token(
151
            self.user, attrs['token']
152
        )
153
        if is_token_valid:
154
            return attrs
155
        raise serializers.ValidationError(self.error_messages['invalid_token'])
156
157
158
class ActivationSerializer(UidAndTokenSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
159
    default_error_messages = {
160
        'stale_token': constants.STALE_TOKEN_ERROR,
161
    }
162
163
    def validate(self, attrs):
164
        attrs = super(ActivationSerializer, self).validate(attrs)
165
        if not self.user.is_active:
166
            return attrs
167
        raise exceptions.PermissionDenied(self.error_messages['stale_token'])
168
169
170
class PasswordSerializer(serializers.Serializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
171
    new_password = serializers.CharField(style={'input_type': 'password'})
172
173
    def validate_new_password(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
174
        validate_password(value)
175
        return value
176
177
178
class PasswordRetypeSerializer(PasswordSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
179
    re_new_password = serializers.CharField(style={'input_type': 'password'})
180
181
    default_error_messages = {
182
        'password_mismatch': constants.PASSWORD_MISMATCH_ERROR,
183
    }
184
185
    def validate(self, attrs):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
186
        attrs = super(PasswordRetypeSerializer, self).validate(attrs)
187
        if attrs['new_password'] == attrs['re_new_password']:
188
            return attrs
189
        raise serializers.ValidationError(
190
            self.error_messages['password_mismatch']
191
        )
192
193
194
class CurrentPasswordSerializer(serializers.Serializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
195
    current_password = serializers.CharField(style={'input_type': 'password'})
196
197
    default_error_messages = {
198
        'invalid_password': constants.INVALID_PASSWORD_ERROR,
199
    }
200
201
    def validate_current_password(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
202
        is_password_valid = self.context['request'].user.check_password(value)
203
        if is_password_valid:
204
            return value
205
        raise serializers.ValidationError(
206
            self.error_messages['invalid_password']
207
        )
208
209
210
class SetPasswordSerializer(PasswordSerializer, CurrentPasswordSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
211
    pass
212
213
214
class SetPasswordRetypeSerializer(PasswordRetypeSerializer,
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
215
                                  CurrentPasswordSerializer):
216
    pass
217
218
219
class PasswordResetConfirmSerializer(UidAndTokenSerializer,
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
220
                                     PasswordSerializer):
221
    pass
222
223
224
class PasswordResetConfirmRetypeSerializer(UidAndTokenSerializer,
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
225
                                           PasswordRetypeSerializer):
226
    pass
227
228
229
class SetUsernameSerializer(serializers.ModelSerializer,
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
230
                            CurrentPasswordSerializer):
231
232
    class Meta(object):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
233
        model = User
234
        fields = (
235
            User.USERNAME_FIELD,
236
            'current_password',
237
        )
238
239
    def __init__(self, *args, **kwargs):
240
        """
241
        This method should probably be replaced by a better solution.
242
        Its purpose is to replace USERNAME_FIELD with 'new_' + USERNAME_FIELD
243
        so that the new field is being assigned a field for USERNAME_FIELD
244
        """
245
        super(SetUsernameSerializer, self).__init__(*args, **kwargs)
246
        username_field = User.USERNAME_FIELD
247
        self.fields['new_' + username_field] = self.fields.pop(username_field)
248
249
250
class SetUsernameRetypeSerializer(SetUsernameSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
251
    default_error_messages = {
252
        'username_mismatch': constants.USERNAME_MISMATCH_ERROR.format(
253
            User.USERNAME_FIELD
254
        ),
255
    }
256
257
    def __init__(self, *args, **kwargs):
258
        super(SetUsernameRetypeSerializer, self).__init__(*args, **kwargs)
259
        self.fields['re_new_' + User.USERNAME_FIELD] = serializers.CharField()
260
261
    def validate(self, attrs):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
262
        attrs = super(SetUsernameRetypeSerializer, self).validate(attrs)
263
        new_username = attrs[User.USERNAME_FIELD]
264
        if new_username != attrs['re_new_' + User.USERNAME_FIELD]:
265
            raise serializers.ValidationError(
266
                self.error_messages['username_mismatch'].format(
267
                    User.USERNAME_FIELD
268
                )
269
            )
270
        return attrs
271
272
273
class TokenSerializer(serializers.ModelSerializer):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
274
    auth_token = serializers.CharField(source='key')
275
276
    class Meta:
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
introduced by
Old-style class defined.
Loading history...
Coding Style introduced by
This class has no __init__ method.
Loading history...
277
        model = settings.TOKEN_MODEL
278
        fields = (
279
            'auth_token',
280
        )
281