Пример #1
0
    def post(self, request):
        try:
            refresh_token = request.data["refresh_token"]
            token = RefreshToken(refresh_token)
            token.blacklist()

            return Response(status=status.HTTP_205_RESET_CONTENT)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #2
0
 def delete(self, request, *args, **kwargs):
     serializer = TokenDestroySchema(data=request.data)
     serializer.is_valid(raise_exception=True)
     try:
         token = RefreshToken(serializer.validated_data.get("refresh"))
         token.blacklist()
     except TokenError as e:
         raise InvalidToken(e.args[0])
     return Response(status=status.HTTP_205_RESET_CONTENT)
Пример #3
0
 def post(self, request):
     try:
         print(request.data)
         token = RefreshToken(request.data["refresh"])
         token.blacklist()
         return Response(status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         print(e)
         return Response({"detail": str(e)},
                         status=status.HTTP_400_BAD_REQUEST)
Пример #4
0
 def create(self, validated_data):
     try:
         token = RefreshToken(validated_data["refresh"])
         if token.payload["user_id"] == self.context["request"].user.id:
             token.blacklist()
             return validated_data
         else:
             raise TokenError
     except TokenError:
         raise NotAuthenticated(detail="Token is invalid or expired")
Пример #5
0
 def post(self, request):
     try:
         data = request.data['refresh_token']
         token = RefreshToken(data)
         token.blacklist()
         return Response({"masg": "successfully logged out"},
                         status=status.HTTP_200_OK)
     except:
         return Response({"msg": "token not found"},
                         status=status.HTTP_400_BAD_REQUEST)
Пример #6
0
    def post(self, request):
        try:
            refresh_token = request.data["refresh_token"]
            token = RefreshToken(refresh_token)
            print('token',  token)
            token.blacklist()

            return Response('log out successfully',status=status.HTTP_205_RESET_CONTENT)
        except Exception as e:
            return Response('invalid token, 404 error',status=status.HTTP_400_BAD_REQUEST)
Пример #7
0
def token_blacklist(request):
    """Blacklist the given refresh token
    """
    try:
        refresh_token = request.data["refresh_token"]
        token = RefreshToken(refresh_token)
        token.blacklist()
        return Response(status=status.HTTP_202_ACCEPTED)
    except Exception as e:
        return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #8
0
 def post(self, request):
     try:
         token = request.data['refresh_token']
         print(token)
         refresh_token = RefreshToken(token)
         refresh_token.blacklist()
         return Response(status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         print(e)
         return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #9
0
 def post(self, request):
     try:
         refresh_token = request.data["refresh_token"]
         access_token = request.data["access_token"]
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response("Successfull logout",
                         status=status.HTTP_205_RESET_CONTENT)
     except:
         return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #10
0
 def post(self, request):
     try:
         refresh_token = request.data['refresh_token']
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response(data={'message': 'OK'},
                         status=status.HTTP_204_NO_CONTENT)
     except TokenError as error:
         return Response(data={'error': str(error)},
                         status=status.HTTP_400_BAD_REQUEST)
 def post(self, request):
     try:
         refresh_token = request.data["refresh_token"]
         # On login the 1st refresh token generated with original access key is added to BLACKLISTED.TOKENS by default.This functions defines a way/method
         # to add upcoming refresh tokens generated using 'ROTATE_REFRESH_TOKENS':True to the BLACKLIST.
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response(status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #12
0
def logoutAndBlacklistRefreshTokenForUser(request):

    try:
        refresh_token = request.data["refresh_token"]
        token = RefreshToken(refresh_token)
        token.blacklist()
        return Response(status=status.HTTP_205_RESET_CONTENT)

    except:
        return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #13
0
 def post(self, request):
     try:
         refresh_token = request.data["refresh_token"]
         print(refresh_token)
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response(status=status.HTTP_200_OK)
     except Exception as e:
         print(e)
         return Response(status=status.HTTP_400_BAD_REQUEST)
    def post(self, request, *args, **kwargs):
        refresh_token = request.data['refresh']

        try:
            token = RefreshToken(refresh_token)
        except TokenError:
            return self.err_res.UNAUTHORIZED

        token.blacklist()

        return Response(status=status.HTTP_200_OK)
Пример #15
0
 def post(self, request):
     try:
         serializer = self.get_serializer(data=request.data)
         serializer.is_valid(raise_exception=True)
         validated_data = serializer.validated_data
         refresh_token = validated_data["refresh_token"]
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response(status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #16
0
 def post(self, request):
     try:
         refresh_token = request.data["refresh_token"]
         token = RefreshToken(refresh_token)
         token.blacklist()
         logout(request)
         return Response(data={'success': True},
                         status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         return Response(data={'success': False},
                         status=status.HTTP_400_BAD_REQUEST)
Пример #17
0
    def logout(self, request):
        try:
            request.user.auth_token.delete()
        except (AttributeError, ObjectDoesNotExist):
            pass

        if getattr(settings, 'REST_SESSION_LOGIN', True):
            django_logout(request)

        response = Response(
            {"detail": _("Successfully logged out.")},
            status=status.HTTP_200_OK
        )

        if getattr(settings, 'REST_USE_JWT', False):
            # NOTE: this import occurs here rather than at the top level
            # because JWT support is optional, and if `REST_USE_JWT` isn't
            # True we shouldn't need the dependency
            from rest_framework_simplejwt.exceptions import TokenError
            from rest_framework_simplejwt.tokens import RefreshToken
            from .jwt_auth import unset_jwt_cookies
            cookie_name = getattr(settings, 'JWT_AUTH_COOKIE', None)

            unset_jwt_cookies(response)

            if 'rest_framework_simplejwt.token_blacklist' in settings.INSTALLED_APPS:
                # add refresh token to blacklist
                try:
                    token = RefreshToken(request.data['refresh'])
                    token.blacklist()
                except KeyError:
                    response.data = {"detail": _("Refresh token was not included in request data.")}
                    response.status_code =status.HTTP_401_UNAUTHORIZED
                except (TokenError, AttributeError, TypeError) as error:
                    if hasattr(error, 'args'):
                        if 'Token is blacklisted' in error.args or 'Token is invalid or expired' in error.args:
                            response.data = {"detail": _(error.args[0])}
                            response.status_code = status.HTTP_401_UNAUTHORIZED
                        else:
                            response.data = {"detail": _("An error has occurred.")}
                            response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR

                    else:
                        response.data = {"detail": _("An error has occurred.")}
                        response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR

            elif not cookie_name:
                message = _(
                    "Neither cookies or blacklist are enabled, so the token "
                    "has not been deleted server side. Please make sure the token is deleted client side."
                )
                response.data = {"detail": message}
                response.status_code = status.HTTP_200_OK
        return response
Пример #18
0
    def post(self, request):
        try:
            refresh_token = request.META.get("HTTP_REFRESH")
            token = RefreshToken(refresh_token)
            token.blacklist()

            return Response(
                data={"message": "Successfully logged out of agora"},
                status=status.HTTP_205_RESET_CONTENT)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #19
0
def post_save_ban(sender, instance, **kwargs):
    instance.receiver.is_active = False
    instance.receiver.is_staff = False
    instance.receiver.is_superuser = False
    instance.receiver.groups.clear()
    for token in instance.receiver.outstandingtoken_set.all():
        try:
            refresh_token = RefreshToken(token.token)
            refresh_token.blacklist()
        except TokenError:
            continue
    instance.receiver.save()
Пример #20
0
 def post(self, request):
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     token = request.data.get('refresh_token')
     error_message = {"error": "Token is invalid or expired"}
     success_message = {"success": "Logout successfully"}
     try:
         token = RefreshToken(token)
         token.blacklist()
     except TokenError as error:
         return Response(error_message, status=status.HTTP_400_BAD_REQUEST)
     return Response(success_message, status=status.HTTP_200_OK)
Пример #21
0
 def post(self, request):
     try:
         print(1)
         refresh_token = request.data["refresh_token"]
         print(2)
         token = RefreshToken(refresh_token)
         print(3)
         token.blacklist()
         print(4)
         return Response({'success': '205'})
     except Exception as e:
         return Response({'error': '400'})
Пример #22
0
def currentUser(request):
    # this view handles delte user and also blacklists the user's refresh tokens to log them out as well  + get current_user
    if request.method == 'GET':
        user = request.user
        current_user_serializer = CurrentUserSerializer(user)
        return Response(current_user_serializer.data,
                        status=status.HTTP_202_ACCEPTED)

    if request.method == 'DELETE':  # delets current User
        try:
            user_serializer = RavenUserSerializer(request.user)
            # getting the user from the db
            raven_user = RavenUser.objects.get(
                email=user_serializer.data['email'])
            if raven_user:
                refresh_token = request.data['refresh_token']
                token = RefreshToken(refresh_token)
                token.blacklist()
                raven_user.delete()
                return Response({"message": "user deleted"},
                                status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response({"message": "user not found"},
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'PUT':  # updates (Edit) the currentUser data
        put_data = JSONParser().parse(request)
        user = request.user
        if 'update_password' in put_data and put_data[
                'update_password'] == True:  # if this evaluates to true then we need to update the password
            current_password = put_data['current_password']
            new_password = put_data['new_password']
            if user.check_password(current_password):
                user.set_password(new_password)
                # if the user only wants to update the password save and return message
                if not 'email' in put_data and not 'username' in put_data and not 'mode' in put_data:
                    user.save()
                    user_serializezr = RavenUserSerializer(
                        user, context={'request': request})
                    return Response(user_serializezr.data,
                                    status=status.HTTP_202_ACCEPTED)
            else:
                return Response({"message": "Wrong password !"},
                                status=status.HTTP_401_UNAUTHORIZED)
        # if user choses to update other fields
        edit_user_serializer = EditUserSerializer(user, data=put_data)
        if edit_user_serializer.is_valid():
            edit_user_serializer.save()
            user.save()
            return Response(edit_user_serializer.data,
                            status=status.HTTP_202_ACCEPTED)
        return Response(edit_user_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Пример #23
0
    def validate(self, attrs):
        refresh = RefreshToken(attrs["refresh"])

        try:
            # Attempt to blacklist the given refresh token
            refresh.blacklist()
        except AttributeError:
            # If blacklist app not installed, `blacklist` method will
            # not be present
            pass

        return {}
Пример #24
0
    def post(self, request):
        token = request.data.get('refresh')
        if not token:
            return HttpResponseBadRequest("Missing required parameter: 'refresh'")

        try:
            token = RefreshToken(token)
            token.blacklist()
        except TokenError as e:
            return HttpResponseBadRequest(str(e))

        return Response({'loggedOut': True})
Пример #25
0
 def post(self, request):
     r"""
     This method handles the POST request made to the server when users logsout from the webiste. The API retrives the token assined to the user and
     puts it on blaclkist when he logs out.
     """
     try:
         refresh_token = request.data["refresh_token"]
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response('logout', status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         return Response(status=status.HTTP_400_BAD_REQUEST)
def LogoutAllView(request):
    try:
        Refresh_token = request.data["refresh"]
        token = RefreshToken(Refresh_token)
        token.blacklist()
        tokens = OutstandingToken.objects.filter(user_id=request.user.id)
        for token in tokens:
            t, _ = BlacklistedToken.objects.get_or_create(token=token)
        return Response("logged out of all devices",
                        status=status.HTTP_205_RESET_CONTENT)
    except:
        return Response("Invalid Token", status=status.HTTP_400_BAD_REQUEST)
Пример #27
0
 def post(self, request):
     refresh_token = request.data.get('refresh')
     try:
         token = RefreshToken(refresh_token)
     except Exception:
         raise ServerException('유효하지 않은 Refresh 토큰입니다.')
     token.blacklist()
     logout(self.request)
     return Response({
         'logout': True,
         'message': '해당 Refresh 토큰은 이제 사용할 수 없습니다.'
     })
Пример #28
0
    def post(self, request):
        try:
            refresh_token = request.data["refresh_token"]
            token = RefreshToken(refresh_token)
            token.blacklist()

            return Response(status=status.HTTP_205_RESET_CONTENT,
                            data={'detail': "logged out"})

        except Exception:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={"detail": "refresh_token is not valid"})
Пример #29
0
 def post(self, request):
     try:
         logger.info(f'login: {str(request.user.username)}')
         refresh_token = request.data["refresh_token"]
         token = RefreshToken(refresh_token)
         token.blacklist()
         return Response({'info': 'Logget out'},
                         status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         logger.error(f'login: {str(request.user.username)} - {str(e)}')
         return Response({'error': str(e)},
                         status=status.HTTP_400_BAD_REQUEST)
Пример #30
0
 def post(self, request):
     try:
         refresh_token = request.data['refresh_token']
         token = RefreshToken(refresh_token)
         token.blacklist()
         OutstandingToken.objects.filter(
             expires_at__lte=aware_utcnow()).delete()
         # BlacklistedToken.objects.all().delete()
         return Response(status=status.HTTP_205_RESET_CONTENT)
     except Exception as e:
         return Response({"error": "Logged out"},
                         status=status.HTTP_400_BAD_REQUEST)