This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserializers.py
196 lines (141 loc) · 5.67 KB
/
serializers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import requests
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import update_last_login
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions, serializers
from rest_framework.exceptions import ValidationError
from .settings import api_settings
from .tokens import RefreshToken, SlidingToken, UntypedToken
if api_settings.BLACKLIST_AFTER_ROTATION:
from .token_blacklist.models import BlacklistedToken
class PasswordField(serializers.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("style", {})
kwargs["style"]["input_type"] = "password"
kwargs["write_only"] = True
super().__init__(*args, **kwargs)
class TokenObtainSerializer(serializers.Serializer):
username_field = get_user_model().USERNAME_FIELD
token_class = None
default_error_messages = {
"no_active_account": _("No active account found with the given credentials")
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["code"] = serializers.CharField()
def validate(self, attrs):
wechat_code = attrs["code"]
wechat_result = self.WeChatSSO(wechat_code)
self.create_or_get_user(wechat_result["openid"])
authenticate_kwargs = {
self.username_field: wechat_result["openid"],
"password": wechat_result["openid"],
}
try:
authenticate_kwargs["request"] = self.context["request"]
except KeyError:
pass
self.user = authenticate(**authenticate_kwargs)
if not api_settings.USER_AUTHENTICATION_RULE(self.user):
raise exceptions.AuthenticationFailed(
self.error_messages["no_active_account"],
"no_active_account",
)
return {}
@classmethod
def get_token(cls, user):
return cls.token_class.for_user(user)
def WeChatSSO(cls, code):
req_params = {
'appid': api_settings.WECHAT_APP_ID,
'secret': api_settings.WECHAT_APP_SECRET,
'js_code': code,
'grant_type': 'authorization_code'
}
url = 'https://api.weixin.qq.com/sns/jscode2session'
response = requests.get(url, params=req_params)
result = response.json()
if 'errcode' in result:
msg = _(result['errmsg'])
raise serializers.ValidationError(msg, code='authorization')
return result
def create_or_get_user(cls, openid):
user, _ = get_user_model().objects.get_or_create(username=openid, defaults={'password': openid})
user.set_password(openid)
user.save()
return user
class TokenObtainPairSerializer(TokenObtainSerializer):
token_class = RefreshToken
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data["refresh"] = str(refresh)
data["access"] = str(refresh.access_token)
if api_settings.UPDATE_LAST_LOGIN:
update_last_login(None, self.user)
return data
class TokenObtainSlidingSerializer(TokenObtainSerializer):
token_class = SlidingToken
def validate(self, attrs):
data = super().validate(attrs)
token = self.get_token(self.user)
data["token"] = str(token)
if api_settings.UPDATE_LAST_LOGIN:
update_last_login(None, self.user)
return data
class TokenRefreshSerializer(serializers.Serializer):
refresh = serializers.CharField()
access = serializers.CharField(read_only=True)
token_class = RefreshToken
def validate(self, attrs):
refresh = self.token_class(attrs["refresh"])
data = {"access": str(refresh.access_token)}
if api_settings.ROTATE_REFRESH_TOKENS:
if api_settings.BLACKLIST_AFTER_ROTATION:
try:
# Attempt to blacklist the given refresh token
refresh.blacklist()
except AttributeError:
# If blacklist app not installed, `blacklist` method will
# not be present
pass
refresh.set_jti()
refresh.set_exp()
refresh.set_iat()
data["refresh"] = str(refresh)
return data
class TokenRefreshSlidingSerializer(serializers.Serializer):
token = serializers.CharField()
token_class = SlidingToken
def validate(self, attrs):
token = self.token_class(attrs["token"])
# Check that the timestamp in the "refresh_exp" claim has not
# passed
token.check_exp(api_settings.SLIDING_TOKEN_REFRESH_EXP_CLAIM)
# Update the "exp" and "iat" claims
token.set_exp()
token.set_iat()
return {"token": str(token)}
class TokenVerifySerializer(serializers.Serializer):
token = serializers.CharField()
def validate(self, attrs):
token = UntypedToken(attrs["token"])
if (
api_settings.BLACKLIST_AFTER_ROTATION
and "rest_framework_simplejwt_wechat_sso.token_blacklist" in settings.INSTALLED_APPS
):
jti = token.get(api_settings.JTI_CLAIM)
if BlacklistedToken.objects.filter(token__jti=jti).exists():
raise ValidationError("Token is blacklisted")
return {}
class TokenBlacklistSerializer(serializers.Serializer):
refresh = serializers.CharField()
token_class = RefreshToken
def validate(self, attrs):
refresh = self.token_class(attrs["refresh"])
try:
refresh.blacklist()
except AttributeError:
pass
return {}