Passed
Pull Request — master (#259)
by Piotr
01:23
created

PasswordUpdateSerializer   A

Complexity

Total Complexity 0

Size/Duplication

Total Lines 2
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 2
rs 10
wmc 0
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...
2
from django.contrib.auth.password_validation import validate_password
3
from django.contrib.auth.tokens import default_token_generator
4
from django.core import exceptions as django_exceptions
5
6
from rest_framework import serializers
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
    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...
31
        model = User
32
        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...
33
34
    def validate(self, attrs):
35
        user = User(**attrs)
36
        password = attrs.get('password')
37
38
        try:
39
            validate_password(password, user)
40
        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...
41
            raise serializers.ValidationError({'password': list(e.messages)})
42
43
        return attrs
44
45
46
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
47
    password = serializers.CharField(
48
        required=False, style={'input_type': 'password'}
49
    )
50
51
    default_error_messages = {
52
        'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR,
53
        'inactive_account': constants.INACTIVE_ACCOUNT_ERROR,
54
    }
55
56
    def __init__(self, *args, **kwargs):
57
        super(TokenCreateSerializer, self).__init__(*args, **kwargs)
58
        self.fields[User.USERNAME_FIELD] = serializers.CharField(
59
            required=False
60
        )
61
62
    def validate(self, attrs):
63
        attrs['user'] = authenticate(
64
            username=attrs.get(User.USERNAME_FIELD),
65
            password=attrs.get('password')
66
        )
67
68
        self._validate_user_exists(attrs['user'])
69
        self._validate_user_is_active(attrs['user'])
70
        return attrs
71
72
    def _validate_user_exists(self, user):
73
        if not user:
74
            self.fail('invalid_credentials')
75
76
    def _validate_user_is_active(self, user):
77
        if not user.is_active:
78
            self.fail('inactive_account')
79
80
81
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
82
    email = serializers.EmailField()
83
84
    default_error_messages = {'email_not_found': constants.EMAIL_NOT_FOUND}
85
86
    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...
87
        users = utils.get_users_for_email(value)
88
        if settings.PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND and not users:
89
            self.fail('email_not_found')
90
        else:
91
            return value
92
93
94
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
95
    uid = serializers.CharField()
96
    token = serializers.CharField()
97
98
    default_error_messages = {
99
        'invalid_token': constants.INVALID_TOKEN_ERROR,
100
        'invalid_uid': constants.INVALID_UID_ERROR,
101
    }
102
103
    def validate(self, attrs):
104
        attrs = super(UidAndTokenSerializer, self).validate(attrs)
105
        try:
106
            uid = utils.decode_uid(attrs['uid'])
107
            user = User.objects.get(pk=uid)
108
        except (User.DoesNotExist, ValueError, TypeError, OverflowError):
109
            self.fail('invalid_uid')
110
111
        is_token_valid = default_token_generator.check_token(
112
            user, attrs['token']
113
        )
114
        if is_token_valid:
115
            attrs['user'] = user
116
            return attrs
117
        else:
118
            self.fail('invalid_token')
119
120
121
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
122
    default_error_messages = {'stale_token': constants.STALE_TOKEN_ERROR}
123
124
    def validate(self, attrs):
125
        attrs = super(UserActivateSerializer, self).validate(attrs)
126
        if not attrs['user'].is_active:
127
            return attrs
128
        raise self.fail('stale_token')
129
130
131
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
132
    new_password = serializers.CharField(style={'input_type': 'password'})
133
134
    def validate(self, attrs):
135
        user = self.context['request'].user or self.user
0 ignored issues
show
Bug introduced by
The Instance of PasswordSerializer does not seem to have a member named user.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
136
        assert user is not None
137
138
        try:
139
            validate_password(attrs['new_password'], user)
140
        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...
141
            raise serializers.ValidationError({
142
                'new_password': list(e.messages)
143
            })
144
        return super(PasswordSerializer, self).validate(attrs)
145
146
147
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
148
    re_new_password = serializers.CharField(style={'input_type': 'password'})
149
150
    default_error_messages = {
151
        'password_mismatch': constants.PASSWORD_MISMATCH_ERROR,
152
    }
153
154
    def validate(self, attrs):
155
        attrs = super(PasswordRetypeSerializer, self).validate(attrs)
156
        if attrs['new_password'] == attrs['re_new_password']:
157
            return attrs
158
        else:
159
            self.fail('password_mismatch')
160
161
162
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
163
    current_password = serializers.CharField(style={'input_type': 'password'})
164
165
    default_error_messages = {
166
        'invalid_password': constants.INVALID_PASSWORD_ERROR,
167
    }
168
169
    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...
170
        is_password_valid = self.context['request'].user.check_password(value)
171
        if is_password_valid:
172
            return value
173
        else:
174
            self.fail('invalid_password')
175
176
177
class PasswordUpdateSerializer(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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
178
    pass
179
180
181
class PasswordUpdateRetypeSerializer(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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
182
                                  CurrentPasswordSerializer):
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (add 3 spaces).
Loading history...
183
    pass
184
185
186
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
187
                                     PasswordSerializer):
188
    pass
189
190
191
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
192
                                           PasswordRetypeSerializer):
193
    pass
194
195
196
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...
Bug introduced by
The method create which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
Bug introduced by
The method update which was declared abstract in the super-class BaseSerializer
was not overridden.

Methods which raise NotImplementedError should be overridden in concrete child classes.

Loading history...
197
    pass
198
199
200
class UsernameUpdateSerializer(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...
201
                            CurrentPasswordSerializer):
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (add 3 spaces).
Loading history...
202
203
    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...
204
        model = User
205
        fields = (User.USERNAME_FIELD, 'current_password')
206
207
208
class UsernameUpdateRetypeSerializer(UsernameUpdateSerializer):
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...
209
    default_error_messages = {
210
        'username_mismatch': constants.USERNAME_MISMATCH_ERROR.format(
0 ignored issues
show
Bug introduced by
The Instance of __proxy__ does not seem to have a member named format.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
211
            User.USERNAME_FIELD
212
        ),
213
    }
214
215
    def __init__(self, *args, **kwargs):
216
        super(UsernameUpdateRetypeSerializer, self).__init__(*args, **kwargs)
217
        self.fields['re_' + User.USERNAME_FIELD] = serializers.CharField()
218
219
    def validate(self, attrs):
220
        attrs = super(UsernameUpdateRetypeSerializer, self).validate(attrs)
221
        new_username = attrs[User.USERNAME_FIELD]
222
        if new_username != attrs['re_' + User.USERNAME_FIELD]:
223
            self.fail('username_mismatch')
224
        else:
225
            return attrs
226
227
228
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...
229
    auth_token = serializers.CharField(source='key')
230
231
    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...
232
        model = settings.TOKEN_MODEL
233
        fields = ('auth_token',)
234