Completed
Push — master ( aa58e4...09baaa )
by Piotr
05:40
created

TokenCreateView   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 15
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 1
c 0
b 0
f 0
dl 0
loc 15
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A _action() 0 6 1
1
from django.contrib.auth import 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.tokens import default_token_generator
0 ignored issues
show
introduced by
Unable to import 'django.contrib.auth.tokens'
Loading history...
3
4
from rest_framework import generics, permissions, status, views
0 ignored issues
show
introduced by
Unable to import 'rest_framework'
Loading history...
5
from rest_framework.response import Response
0 ignored issues
show
introduced by
Unable to import 'rest_framework.response'
Loading history...
6
from rest_framework.reverse import reverse
0 ignored issues
show
introduced by
Unable to import 'rest_framework.reverse'
Loading history...
7
8
from djoser.conf import settings
9
from djoser.compat import get_user_email, get_user_email_field_name
10
11
from djoser import email, utils, signals
12
from djoser.compat import NoReverseMatch
13
14
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...
15
16
17
class RootView(views.APIView):
18
    """
19
    Root endpoint - use one of sub endpoints.
20
    """
21
    permission_classes = [permissions.AllowAny]
22
23
    def aggregate_djoser_urlpattern_names(self):
0 ignored issues
show
Coding Style Naming introduced by
The name aggregate_djoser_urlpattern_names does not conform to the method 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...
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...
24
        from djoser.urls import base, authtoken
25
        urlpattern_names = [pattern.name for pattern in base.urlpatterns]
26
        urlpattern_names += [pattern.name for pattern in authtoken.urlpatterns]
27
        urlpattern_names += self._get_jwt_urlpatterns()
28
29
        return urlpattern_names
30
31
    def get_urls_map(self, request, urlpattern_names, fmt):
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...
32
        urls_map = {}
33
        for urlpattern_name in urlpattern_names:
34
            try:
35
                url = reverse(urlpattern_name, request=request, format=fmt)
36
            except NoReverseMatch:
37
                url = ''
38
            urls_map[urlpattern_name] = url
39
        return urls_map
40
41
    def get(self, request, fmt=None):
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...
42
        urlpattern_names = self.aggregate_djoser_urlpattern_names()
43
        urls_map = self.get_urls_map(request, urlpattern_names, fmt)
44
        return Response(urls_map)
45
46
    def _get_jwt_urlpatterns(self):
0 ignored issues
show
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...
47
        try:
48
            from djoser.urls import jwt
49
            return [pattern.name for pattern in jwt.urlpatterns]
50
        except ModuleNotFoundError:
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'ModuleNotFoundError'
Loading history...
51
            return []
52
53
54
class UserCreateView(generics.CreateAPIView):
55 View Code Duplication
    """
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
56
    Use this endpoint to register new user.
57
    """
58
    serializer_class = settings.SERIALIZERS.user_registration
59
    permission_classes = (
60
        permissions.AllowAny,
61
    )
62
63
    def perform_create(self, serializer):
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...
64
        user = serializer.save()
65
        signals.user_registered.send(
66
            sender=self.__class__, user=user, request=self.request
67
        )
68
69
        context = {'user': user}
70
        to = [get_user_email(user)]
0 ignored issues
show
Coding Style Naming introduced by
The name to 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...
71
        if settings.SEND_ACTIVATION_EMAIL:
72
            email.ActivationEmail(self.request, context).send(to)
73
        elif settings.SEND_CONFIRMATION_EMAIL:
74
            email.ConfirmationEmail(self.request, context).send(to)
75
76
77
class TokenCreateView(utils.ActionViewMixin, generics.GenericAPIView):
78
    """
79
    Use this endpoint to obtain user authentication token.
80
    """
81
    serializer_class = settings.SERIALIZERS.login
82
    permission_classes = (
83
        permissions.AllowAny,
84
    )
85
86
    def _action(self, serializer):
87
        token = utils.login_user(self.request, serializer.user)
88
        token_serializer_class = settings.SERIALIZERS.token
89
        return Response(
90
            data=token_serializer_class(token).data,
91
            status=status.HTTP_200_OK,
92
        )
93
94
95
class TokenDestroyView(views.APIView):
96
    """
97
    Use this endpoint to logout user (remove user authentication token).
98
    """
99
    permission_classes = (
100
        permissions.IsAuthenticated,
101
    )
102
103
    def post(self, request):
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...
104
        utils.logout_user(request)
105
        return Response(status=status.HTTP_204_NO_CONTENT)
106
107
108
class PasswordResetView(utils.ActionViewMixin, generics.GenericAPIView):
109
    """
110
    Use this endpoint to send email to user with password reset link.
111
    """
112
    serializer_class = settings.SERIALIZERS.password_reset
113
    permission_classes = (
114
        permissions.AllowAny,
115
    )
116
117
    _users = None
118
119
    def _action(self, serializer):
120
        for user in self.get_users(serializer.data['email']):
121
            self.send_password_reset_email(user)
122
        return Response(status=status.HTTP_204_NO_CONTENT)
123
124
    def get_users(self, email):
0 ignored issues
show
Comprehensibility Bug introduced by
email is re-defining a name which is already available in the outer-scope (previously defined on line 11).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
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...
125
        if self._users is None:
126
            email_field_name = get_user_email_field_name(User)
127
            users = User._default_manager.filter(**{
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _default_manager 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...
128
                email_field_name + '__iexact': email
129
            })
130
            self._users = [
131
                u for u in users if u.is_active and u.has_usable_password()
132
            ]
133
        return self._users
134
135
    def send_password_reset_email(self, user):
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...
136
        context = {'user': user}
137
        to = [get_user_email(user)]
0 ignored issues
show
Coding Style Naming introduced by
The name to 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...
138
        email.PasswordResetEmail(self.request, context).send(to)
139
140
141
class SetPasswordView(utils.ActionViewMixin, generics.GenericAPIView):
142
    """
143
    Use this endpoint to change user password.
144
    """
145
    permission_classes = (
146
        permissions.IsAuthenticated,
147
    )
148
149
    def get_serializer_class(self):
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...
150
        if settings.SET_PASSWORD_RETYPE:
151
            return settings.SERIALIZERS.set_password_retype
152
        return settings.SERIALIZERS.set_password
153
154
    def _action(self, serializer):
155
        self.request.user.set_password(serializer.data['new_password'])
156
        self.request.user.save()
157
158
        if settings.LOGOUT_ON_PASSWORD_CHANGE:
159
            utils.logout_user(self.request)
160
161
        return Response(status=status.HTTP_204_NO_CONTENT)
162
163
164
class PasswordResetConfirmView(utils.ActionViewMixin, generics.GenericAPIView):
165
    """
166
    Use this endpoint to finish reset password process.
167
    """
168
    permission_classes = (
169
        permissions.AllowAny,
170
    )
171
    token_generator = default_token_generator
172
173
    def get_serializer_class(self):
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
        if settings.PASSWORD_RESET_CONFIRM_RETYPE:
175
            return settings.SERIALIZERS.password_reset_confirm_retype
176
        return settings.SERIALIZERS.password_reset_confirm
177
178
    def _action(self, serializer):
0 ignored issues
show
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...
179
        serializer.user.set_password(serializer.data['new_password'])
180
        serializer.user.save()
181
        return Response(status=status.HTTP_204_NO_CONTENT)
182
183
184
class ActivationView(utils.ActionViewMixin, generics.GenericAPIView):
185
    """
186 View Code Duplication
    Use this endpoint to activate user account.
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
187
    """
188
    serializer_class = settings.SERIALIZERS.activation
189
    permission_classes = (
190
        permissions.AllowAny,
191
    )
192
    token_generator = default_token_generator
193
194
    def _action(self, serializer):
195
        user = serializer.user
196
        user.is_active = True
197
        user.save()
198
199
        signals.user_activated.send(
200
            sender=self.__class__, user=user, request=self.request
201
        )
202
203
        if settings.SEND_CONFIRMATION_EMAIL:
204
            context = {'user': user}
205
            to = [get_user_email(user)]
0 ignored issues
show
Coding Style Naming introduced by
The name to 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...
206
            email.ConfirmationEmail(self.request, context).send(to)
207
208
        return Response(status=status.HTTP_204_NO_CONTENT)
209
210
211
class SetUsernameView(utils.ActionViewMixin, generics.GenericAPIView):
212
    """
213
    Use this endpoint to change user username.
214
    """
215
    permission_classes = (permissions.IsAuthenticated,)
216
217
    def get_serializer_class(self):
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...
218
        if settings.SET_USERNAME_RETYPE:
219
            return settings.SERIALIZERS.set_username_retype
220
        return settings.SERIALIZERS.set_username
221
222
    def _action(self, serializer):
223
        user = self.request.user
224
        new_username = serializer.data['new_' + User.USERNAME_FIELD]
225
226
        setattr(user, User.USERNAME_FIELD, new_username)
227
        if settings.SEND_ACTIVATION_EMAIL:
228
            user.is_active = False
229
            context = {'user': user}
230
            to = [get_user_email(user)]
0 ignored issues
show
Coding Style Naming introduced by
The name to 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...
231
            email.ActivationEmail(self.request, context).send(to)
232
        user.save()
233
234
        return Response(status=status.HTTP_204_NO_CONTENT)
235
236
237
class UserView(generics.RetrieveUpdateAPIView):
238
    """
239
    Use this endpoint to retrieve/update user.
240
    """
241
    model = User
242
    serializer_class = settings.SERIALIZERS.user
243
    permission_classes = (permissions.IsAuthenticated,)
244
245
    def get_object(self, *args, **kwargs):
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...
Unused Code introduced by
The argument args seems to be unused.
Loading history...
Unused Code introduced by
The argument kwargs seems to be unused.
Loading history...
246
        return self.request.user
247
248
    def perform_update(self, serializer):
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...
249
        super(UserView, self).perform_update(serializer)
250
        user = serializer.instance
251
        if settings.SEND_ACTIVATION_EMAIL and not user.is_active:
252
            context = {'user': user}
253
            to = [get_user_email(user)]
0 ignored issues
show
Coding Style Naming introduced by
The name to 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...
254
            email.ActivationEmail(self.request, context).send(to)
255