def __call__(self, request):
        response = self.get_response(request)
        if not hasattr(request, 'user'):
            return response
        if request.user.is_authenticated():
            if response.status_code != 200:
                return response

            if 'JWT' in request.COOKIES:
                # 刷新JWT
                serializer = RefreshJSONWebTokenSerializer(
                    data={'token': request.COOKIES['JWT']})
                if serializer.is_valid():
                    jwt_and_user = serializer.object
                    if jwt_and_user['user'] == request.user:
                        jwt = jwt_and_user['token']
                    else:
                        jwt = jwt_encode_handler(
                            jwt_payload_handler(request.user))
                else:
                    # 旧JWT无法解析的话,创建新的JWT
                    jwt = jwt_encode_handler(jwt_payload_handler(request.user))
            else:
                # JWT还不在cookie里的话,创建新的JWT
                jwt = jwt_encode_handler(jwt_payload_handler(request.user))

            response.set_cookie('JWT', value=jwt, max_age=24 * 60 * 60)
        else:
            # 用户已经登出,清理掉JWT
            if 'JWT' in request.COOKIES:
                response.delete_cookie('JWT')
        return response
Esempio n. 2
0
 def mutate_and_get_payload(cls, root, info, **input):
     serializer = RefreshJSONWebTokenSerializer(data=input)
     if serializer.is_valid():
         return RefreshToken(success=True,
                             token=serializer.object['token'],
                             errors=None)
     else:
         raise GraphQLError(u'Non è possibile fare il refresh del ' +
                            u'token con le credenziali fornite.')
 def mutate_and_get_payload(cls, input, context, info):
     serializer = RefreshJSONWebTokenSerializer(data=input)
     if serializer.is_valid():
         return RefreshToken(success=True,
                             token=serializer.object['token'],
                             errors=None)
     else:
         return RefreshToken(
             success=False,
             token=None,
             errors=['email', 'Unable to login with provided credentials.'])
Esempio n. 4
0
 def mutate_and_get_payload(cls, input, context, info):
     serializer = RefreshJSONWebTokenSerializer(data=input)
     if serializer.is_valid():
         return RefreshToken(
             success=True,
             token=serializer.object['token'],
             errors=None
         )
     else:
         return RefreshToken(
             success=False,
             token=None,
             errors=['email', 'Unable to login with provided credentials.']
         )
Esempio n. 5
0
class RefreshToken:
    serializer = RefreshJSONWebTokenSerializer()

    def token_validation(self, token):
        """
        :param token:
        :return:
        """
        try:
            res = self.serializer.validate(
                {"token": token['token'].split(' ')[1]})
        except Exception as e:
            print(e)
            # logger.debug('Internal get user refresh token {}'.format(e))
            return False

        if 'token' in res.keys():
            return res['token']

        return False
class PasswordRecoveryViewSet(viewsets.ViewSet):
    """
    Reset password endpoint.
    """
    serializer_class = resident.PasswordRecoverySerializer
    permission_classes = [AllowAny]
    @swagger_auto_schema(request_body=resident.PasswordRecoverySerializer,responses={200: RefreshJSONWebTokenSerializer()})
    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            user = get_user_model().objects.get(email=request.data['email'])
            if(user.is_active == True):
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                current_site = get_current_site(request)
                mail_subject = 'Account Password Recovery'
                message = loader.get_template(
                'emails/forgotPassword.html').render(
                {
                    'name': user.first_name+' '+user.last_name,
                    'domain': current_site.domain,
                    'uid':urlsafe_base64_encode(force_bytes(user.pk)),
                    'token':PasswordResetTokenGenerator().make_token(user),
                }
                )
                to_email = user.email
                email = EmailMessage(
                    mail_subject, message, to=[to_email]
                )
                email.content_subtype = 'html'
                email.send()
                response_data = {
                    "token": token,
                }
                return Response(response_data, status=status.HTTP_200_OK)
            else:
                error = dict()
                error['email'] = 'Invalid email address.'
                return Response(error, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)