Passed
Pull Request — master (#259)
by Piotr
01:50
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.contrib.auth.password_validation import validate_password
0 ignored issues
show
introduced by
Unable to import 'django.contrib.auth.password_validation'
Loading history...
3
from django.contrib.auth.tokens import default_token_generator
0 ignored issues
show
introduced by
Unable to import 'django.contrib.auth.tokens'
Loading history...
4
from django.core import exceptions as django_exceptions
0 ignored issues
show
introduced by
Unable to import 'django.core'
Loading history...
5
6
from rest_framework import serializers
0 ignored issues
show
introduced by
Unable to import 'rest_framework'
Loading history...
7
8
from djoser import constants, utils
9
from djoser.conf import settings
10
11
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...
12
13
14
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...
15
    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...
16
        model = User
17
        fields = [
18
            User._meta.pk.name, User.get_email_field_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...
19
            User.USERNAME_FIELD
20
        ]
21
        read_only_fields = [User.USERNAME_FIELD]
22
23
24
class UserCreateSerializer(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...
25
    password = serializers.CharField(
26
        style={'input_type': 'password'},
27
        write_only=True
28
    )
29
30
    default_error_messages = {
31
        'cannot_create_user': constants.CANNOT_CREATE_USER_ERROR,
32
    }
33
34
    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...
35
        model = User
36
        fields = [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...
37
38
    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...
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...
39
        user = User(**attrs)
40
        password = attrs.get('password')
41
42
        try:
43
            validate_password(password, user)
44
        except django_exceptions.ValidationError as e:
0 ignored issues
show
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[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...
45
            raise serializers.ValidationError({'password': list(e.messages)})
46
47
        return attrs
48
49
50
class TokenCreateSerializer(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...
51
    password = serializers.CharField(
52
        required=False, style={'input_type': 'password'}
53
    )
54
55
    default_error_messages = {
56
        'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR,
57
        'inactive_account': constants.INACTIVE_ACCOUNT_ERROR,
58
    }
59
60
    def __init__(self, *args, **kwargs):
61
        super(TokenCreateSerializer, self).__init__(*args, **kwargs)
62
        self.fields[User.USERNAME_FIELD] = serializers.CharField(
63
            required=False
64
        )
65
66
    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...
67
        attrs['user'] = authenticate(
68
            username=attrs.get(User.USERNAME_FIELD),
69
            password=attrs.get('password')
70
        )
71
72
        self._validate_user_exists(attrs['user'])
73
        self._validate_user_is_active(attrs['user'])
74
        return attrs
75
76
    def _validate_user_exists(self, user):
77
        if not user:
78
            self.fail('invalid_credentials')
79
80
    def _validate_user_is_active(self, user):
81
        if not user.is_active:
82
            self.fail('inactive_account')
83
84
85
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...
86
    email = serializers.EmailField()
87
88
    default_error_messages = {'email_not_found': constants.EMAIL_NOT_FOUND}
89
90
    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...
91
        users = utils.get_users_for_email(value)
92
        if settings.PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND and not users:
93
            self.fail('email_not_found')
94
        else:
95
            return value
96
97
98
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...
99
    uid = serializers.CharField()
100
    token = serializers.CharField()
101
102
    default_error_messages = {
103
        'invalid_token': constants.INVALID_TOKEN_ERROR,
104
        'invalid_uid': constants.INVALID_UID_ERROR,
105
    }
106
107
    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...
108
        attrs = super(UidAndTokenSerializer, self).validate(attrs)
109
        try:
110
            uid = utils.decode_uid(attrs['uid'])
111
            user = User.objects.get(pk=uid)
112
        except (User.DoesNotExist, ValueError, TypeError, OverflowError):
113
            self.fail('invalid_uid')
114
115
        is_token_valid = default_token_generator.check_token(
116
            user, attrs['token']
117
        )
118
        if is_token_valid:
119
            attrs['user'] = user
120
            return attrs
121
        else:
122
            self.fail('invalid_token')
123
124
125
class UserActivateSerializer(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...
126
    default_error_messages = {'stale_token': constants.STALE_TOKEN_ERROR}
127
128
    def validate(self, attrs):
129
        attrs = super(UserActivateSerializer, self).validate(attrs)
130
        if not attrs['user'].is_active:
131
            return attrs
132
        raise self.fail('stale_token')
133
134
135
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...
136
    new_password = serializers.CharField(style={'input_type': 'password'})
137
138
    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...
139
        user = self.context['request'].user or self.user
140
        assert user is not None
141
142
        try:
143
            validate_password(attrs['new_password'], user)
144
        except django_exceptions.ValidationError as e:
0 ignored issues
show
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[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...
145
            raise serializers.ValidationError({
146
                'new_password': list(e.messages)
147
            })
148
        return super(PasswordSerializer, self).validate(attrs)
149
150
151
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...
152
    re_new_password = serializers.CharField(style={'input_type': 'password'})
153
154
    default_error_messages = {
155
        'password_mismatch': constants.PASSWORD_MISMATCH_ERROR,
156
    }
157
158
    def validate(self, attrs):
159
        attrs = super(PasswordRetypeSerializer, self).validate(attrs)
160
        if attrs['new_password'] == attrs['re_new_password']:
161
            return attrs
162
        else:
163
            self.fail('password_mismatch')
164
165
166
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...
167
    current_password = serializers.CharField(style={'input_type': 'password'})
168
169
    default_error_messages = {
170
        'invalid_password': constants.INVALID_PASSWORD_ERROR,
171
    }
172
173
    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...
174
        is_password_valid = self.context['request'].user.check_password(value)
175
        if is_password_valid:
176
            return value
177
        else:
178
            self.fail('invalid_password')
179
180
181
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...
182
    pass
183
184
185
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...
186
                                  CurrentPasswordSerializer):
187
    pass
188
189
190
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...
191
                                     PasswordSerializer):
192
    pass
193
194
195
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...
196
                                           PasswordRetypeSerializer):
197
    pass
198
199
200
class UserDeleteSerializer(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...
201
    pass
202
203
204
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...
205
                            CurrentPasswordSerializer):
206
207
    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...
208
        model = User
209
        fields = (User.USERNAME_FIELD, 'current_password')
210
211
212
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...
213
    default_error_messages = {
214
        'username_mismatch': constants.USERNAME_MISMATCH_ERROR.format(
215
            User.USERNAME_FIELD
216
        ),
217
    }
218
219
    def __init__(self, *args, **kwargs):
220
        super(SetUsernameRetypeSerializer, self).__init__(*args, **kwargs)
221
        self.fields['re_' + User.USERNAME_FIELD] = serializers.CharField()
222
223
    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...
224
        attrs = super(SetUsernameRetypeSerializer, self).validate(attrs)
225
        new_username = attrs[User.USERNAME_FIELD]
226
        if new_username != attrs['re_' + User.USERNAME_FIELD]:
227
            self.fail('username_mismatch')
228
        else:
229
            return attrs
230
231
232
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...
233
    auth_token = serializers.CharField(source='key')
234
235
    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...
236
        model = settings.TOKEN_MODEL
237
        fields = ('auth_token',)
238