def post(self, request, format=None): ser = serializers.LoginSerializer(data=request.data) if ser.is_valid(): anonymous_basket = operations.get_anonymous_basket(request) user = ser.object # refuse to login logged in users, to avoid attaching sessions to # multiple users at the same time. if request.user.is_authenticated(): return Response( {'detail': 'Session is in use, log out first'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) request.user = user login_and_upgrade_session(request._request, user) # merge anonymous basket with authenticated basket. basket = operations.get_user_basket(user) if anonymous_basket is not None: self.merge_baskets(anonymous_basket, basket) operations.store_basket_in_session(basket, request.session) return Response() return Response(ser.errors, status=status.HTTP_401_UNAUTHORIZED)
def post(self, request, format=None): ser = self.serializer_class(data=request.data) if ser.is_valid(): anonymous_basket = operations.get_anonymous_basket(request) user = ser.instance # refuse to login logged in users, to avoid attaching sessions to # multiple users at the same time. if request.user.is_authenticated: return Response( {'detail': 'Session is in use, log out first'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) request.user = user login_and_upgrade_session(request._request, user) # merge anonymous basket with authenticated basket. basket = operations.get_user_basket(user) if anonymous_basket is not None: self.merge_baskets(anonymous_basket, basket) operations.store_basket_in_session(basket, request.session) return Response("") return Response(ser.errors, status=status.HTTP_401_UNAUTHORIZED)
def test_get_user_basket_with_multiple_baskets(self): user = User.objects.get(username="******") Basket.open.create(owner=user) Basket.open.create(owner=user) self.assertEqual(Basket.open.count(), 2) # get_user_basket will fix this automatically for us user_basket = get_user_basket(user) self.assertEqual(Basket.open.count(), 1) self.assertEqual(user_basket, Basket.open.first())