1
|
|
|
from rest_framework import serializers |
|
|
|
|
2
|
|
|
|
3
|
|
|
from social_core import exceptions |
|
|
|
|
4
|
|
|
from social_django.utils import load_backend, load_strategy |
|
|
|
|
5
|
|
|
|
6
|
|
|
from djoser.conf import settings |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
class ProviderAuthSerializer(serializers.Serializer): |
|
|
|
|
10
|
|
|
# GET auth token |
11
|
|
|
token = serializers.CharField(read_only=True) |
12
|
|
|
user = serializers.CharField(read_only=True) |
13
|
|
|
|
14
|
|
|
def create(self, validated_data): |
|
|
|
|
15
|
|
|
user = validated_data['user'] |
16
|
|
|
return settings.SOCIAL_AUTH_TOKEN_STRATEGY.obtain(user) |
17
|
|
|
|
18
|
|
|
def validate(self, attrs): |
|
|
|
|
19
|
|
|
request = self.context['request'] |
20
|
|
|
if 'state' in request.GET: |
21
|
|
|
self._validate_state(request.GET['state']) |
22
|
|
|
|
23
|
|
|
strategy = load_strategy(request) |
24
|
|
|
redirect_uri = strategy.session_get('redirect_uri') |
25
|
|
|
|
26
|
|
|
backend_name = self.context['view'].kwargs['provider'] |
27
|
|
|
backend = load_backend( |
28
|
|
|
strategy, backend_name, redirect_uri=redirect_uri |
29
|
|
|
) |
30
|
|
|
|
31
|
|
|
try: |
32
|
|
|
user = backend.auth_complete() |
33
|
|
|
except exceptions.AuthException as e: |
|
|
|
|
34
|
|
|
raise serializers.ValidationError(str(e)) |
35
|
|
|
return {'user': user} |
36
|
|
|
|
37
|
|
|
def _validate_state(self, value): |
38
|
|
|
request = self.context['request'] |
39
|
|
|
strategy = load_strategy(request) |
40
|
|
|
redirect_uri = strategy.session_get('redirect_uri') |
41
|
|
|
|
42
|
|
|
backend_name = self.context['view'].kwargs['provider'] |
43
|
|
|
backend = load_backend( |
44
|
|
|
strategy, backend_name, redirect_uri=redirect_uri |
45
|
|
|
) |
46
|
|
|
|
47
|
|
|
try: |
48
|
|
|
backend.validate_state() |
49
|
|
|
except exceptions.AuthMissingParameter: |
50
|
|
|
raise serializers.ValidationError( |
51
|
|
|
'State could not be found in request data.' |
52
|
|
|
) |
53
|
|
|
except exceptions.AuthStateMissing: |
54
|
|
|
raise serializers.ValidationError( |
55
|
|
|
'State could not be found in server-side session data.' |
56
|
|
|
) |
57
|
|
|
except exceptions.AuthStateForbidden: |
58
|
|
|
raise serializers.ValidationError( |
59
|
|
|
'Invalid state has been provided.' |
60
|
|
|
) |
61
|
|
|
|
62
|
|
|
return value |
63
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.