Passed
Push — master ( c0402d...d29566 )
by Piotr
01:03
created

PasswordSerializer.validate()   A

Complexity

Conditions 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 3
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.core import exceptions as django_exceptions
0 ignored issues
show
introduced by
Unable to import 'django.core'
Loading history...
4
from django.db import IntegrityError, transaction
0 ignored issues
show
introduced by
Unable to import 'django.db'
Loading history...
5
6
from rest_framework import exceptions, serializers
0 ignored issues
show
introduced by
Unable to import 'rest_framework'
Loading history...
7
8
from djoser import constants, utils
9
from djoser.compat import get_user_email, get_user_email_field_name
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 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...
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(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...
51
        user = User(**attrs)
52
        password = attrs.get('password')
53
54
        try:
55
            validate_password(password, user)
56
        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...
57
            raise serializers.ValidationError({'password': list(e.messages)})
58
59
        return attrs
60
61
    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...
62
        try:
63
            user = self.perform_create(validated_data)
64
        except IntegrityError:
65
            self.fail('cannot_create_user')
66
67
        return user
68
69
    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...
70
        with transaction.atomic():
71
            user = User.objects.create_user(**validated_data)
72
            if settings.SEND_ACTIVATION_EMAIL:
73
                user.is_active = False
74
                user.save(update_fields=['is_active'])
75
        return user
76
77
78
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...
79
    password = serializers.CharField(
80
        required=False, style={'input_type': 'password'}
81
    )
82
83
    default_error_messages = {
84
        'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR,
85
        'inactive_account': constants.INACTIVE_ACCOUNT_ERROR,
86
    }
87
88
    def __init__(self, *args, **kwargs):
89
        super(TokenCreateSerializer, self).__init__(*args, **kwargs)
90
        self.user = None
91
        self.fields[User.USERNAME_FIELD] = serializers.CharField(
92
            required=False
93
        )
94
95
    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...
96
        self.user = authenticate(
97
            username=attrs.get(User.USERNAME_FIELD),
98
            password=attrs.get('password')
99
        )
100
101
        self._validate_user_exists(self.user)
102
        self._validate_user_is_active(self.user)
103
        return attrs
104
105
    def _validate_user_exists(self, user):
106
        if not user:
107
            self.fail('invalid_credentials')
108
109
    def _validate_user_is_active(self, user):
110
        if not user.is_active:
111
            self.fail('inactive_account')
112
113
114
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...
115
    email = serializers.EmailField()
116
117
    default_error_messages = {'email_not_found': constants.EMAIL_NOT_FOUND}
118
119
    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...
120
        users = self.context['view'].get_users(value)
121
        if settings.PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND and not users:
122
            self.fail('email_not_found')
123
        else:
124
            return value
125
126
127
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...
128
    uid = serializers.CharField()
129
    token = serializers.CharField()
130
131
    default_error_messages = {
132
        'invalid_token': constants.INVALID_TOKEN_ERROR,
133
        'invalid_uid': constants.INVALID_UID_ERROR,
134
    }
135
136
    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...
137
        try:
138
            uid = utils.decode_uid(value)
139
            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...
140
        except (User.DoesNotExist, ValueError, TypeError, OverflowError):
141
            self.fail('invalid_uid')
142
143
        return value
144
145
    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...
146
        attrs = super(UidAndTokenSerializer, self).validate(attrs)
147
        is_token_valid = self.context['view'].token_generator.check_token(
148
            self.user, attrs['token']
149
        )
150
        if is_token_valid:
151
            return attrs
152
        else:
153
            self.fail('invalid_token')
154
155
156
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...
157
    default_error_messages = {'stale_token': constants.STALE_TOKEN_ERROR}
158
159
    def validate(self, attrs):
160
        attrs = super(ActivationSerializer, self).validate(attrs)
161
        if not self.user.is_active:
162
            return attrs
163
        raise exceptions.PermissionDenied(self.error_messages['stale_token'])
164
165
166
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...
167
    new_password = serializers.CharField(style={'input_type': 'password'})
168
169
    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...
170
        user = self.context['request'].user or self.user
171
        assert user is not None
172
173
        try:
174
            validate_password(attrs['new_password'], user)
175
        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...
176
            raise serializers.ValidationError({
177
                'new_password': list(e.messages)
178
            })
179
        return super(PasswordSerializer, self).validate(attrs)
180
181
182
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...
183
    re_new_password = serializers.CharField(style={'input_type': 'password'})
184
185
    default_error_messages = {
186
        'password_mismatch': constants.PASSWORD_MISMATCH_ERROR,
187
    }
188
189
    def validate(self, attrs):
190
        attrs = super(PasswordRetypeSerializer, self).validate(attrs)
191
        if attrs['new_password'] == attrs['re_new_password']:
192
            return attrs
193
        else:
194
            self.fail('password_mismatch')
195
196
197
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...
198
    current_password = serializers.CharField(style={'input_type': 'password'})
199
200
    default_error_messages = {
201
        'invalid_password': constants.INVALID_PASSWORD_ERROR,
202
    }
203
204
    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...
205
        is_password_valid = self.context['request'].user.check_password(value)
206
        if is_password_valid:
207
            return value
208
        else:
209
            self.fail('invalid_password')
210
211
212
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...
213
    pass
214
215
216
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...
217
                                  CurrentPasswordSerializer):
218
    pass
219
220
221
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...
222
                                     PasswordSerializer):
223
    pass
224
225
226
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...
227
                                           PasswordRetypeSerializer):
228
    pass
229
230
231
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...
232
    pass
233
234
235
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...
236
                            CurrentPasswordSerializer):
237
238
    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...
239
        model = User
240
        fields = (User.USERNAME_FIELD, 'current_password')
241
242
    def __init__(self, *args, **kwargs):
243
        """
244
        This method should probably be replaced by a better solution.
245
        Its purpose is to replace USERNAME_FIELD with 'new_' + USERNAME_FIELD
246
        so that the new field is being assigned a field for USERNAME_FIELD
247
        """
248
        super(SetUsernameSerializer, self).__init__(*args, **kwargs)
249
        username_field = User.USERNAME_FIELD
250
        self.fields['new_' + username_field] = self.fields.pop(username_field)
251
252
253
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...
254
    default_error_messages = {
255
        'username_mismatch': constants.USERNAME_MISMATCH_ERROR.format(
256
            User.USERNAME_FIELD
257
        ),
258
    }
259
260
    def __init__(self, *args, **kwargs):
261
        super(SetUsernameRetypeSerializer, self).__init__(*args, **kwargs)
262
        self.fields['re_new_' + User.USERNAME_FIELD] = serializers.CharField()
263
264
    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...
265
        attrs = super(SetUsernameRetypeSerializer, self).validate(attrs)
266
        new_username = attrs[User.USERNAME_FIELD]
267
        if new_username != attrs['re_new_' + User.USERNAME_FIELD]:
268
            self.fail('username_mismatch')
269
        else:
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 = ('auth_token',)
279