647b4550 by 周伟奇

token modify part4

1 parent df8b6833
......@@ -33,6 +33,29 @@ class OAuth2AuthenticationWithUser(OAuth2Authentication):
class MyJSONWebTokenAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, username):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model()
# username = jwt_get_username_from_payload(payload)
if not username:
msg = _('Invalid payload.')
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get_by_natural_key(username)
except User.DoesNotExist:
msg = _('Invalid signature.')
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user
def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
......@@ -43,25 +66,24 @@ class MyJSONWebTokenAuthentication(JSONWebTokenAuthentication):
return None
jwt_str = str(jwt_value, 'UTF-8')[-10:]
is_expired = rh.get_token(jwt_str)
if isinstance(is_expired, str):
rh.set_token(jwt_str)
username = rh.get_token(jwt_str)
if isinstance(username, str):
rh.set_token(jwt_str, username)
else:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg)
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
# msg = _('Signature has expired.')
# raise exceptions.AuthenticationFailed(msg)
pass
except jwt.DecodeError:
msg = _('Error decoding signature.')
raise exceptions.AuthenticationFailed(msg)
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
# try:
# payload = jwt_decode_handler(jwt_value)
# except jwt.ExpiredSignature:
# msg = _('Signature has expired.')
# raise exceptions.AuthenticationFailed(msg)
# except jwt.DecodeError:
# msg = _('Error decoding signature.')
# raise exceptions.AuthenticationFailed(msg)
# except jwt.InvalidTokenError:
# raise exceptions.AuthenticationFailed()
user = self.authenticate_credentials(payload)
user = self.authenticate_credentials(username)
return (user, jwt_value)
......
......@@ -51,7 +51,7 @@ class LoginView(ObtainJSONWebToken, GenericView):
'user_name': user.username,
'token': res.data.get('token'),
}
rh.set_token(res.data.get('token')[-10:])
rh.set_token(res.data.get('token')[-10:], user.username)
return response.ok(data=data)
......
......@@ -88,8 +88,8 @@ class RedisHandler:
def get_token_key(self, token_str):
return '{0}:token:{1}'.format(self.prefix, token_str)
def set_token(self, token_str, expires=1800):
return self.redis.set(self.get_token_key(token_str), 'token', expires)
def set_token(self, token_str, username, expires=1800):
return self.redis.set(self.get_token_key(token_str), username, expires)
def get_token(self, token_str):
return self.redis.get(self.get_token_key(token_str))
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!