Beispiel #1
0
 def process_request(self, request):
     data = request.COOKIES.get("messages")
     storage = CookieStorage(request)
     try:
         storage._decode(data)
     except IndexError:
         del request.COOKIES['messages']
Beispiel #2
0
def messages_from_response(response):
    """Returns a list of the messages from the django MessageMiddleware
    package contained within the given response.  This is to be used during
    unit testing when trying to see if a message was set properly in a view.

    :param response: HttpResponse object, likely obtained through a
        test client.get() or client.post() call

    :returns: a list of tuples (message_string, message_level), one for each
        message in the response context
    """
    messages = []
    if hasattr(response, 'context') and response.context and \
            'messages' in response.context:
        messages = response.context['messages']
    elif hasattr(response, 'cookies'):
        # no "context" set-up or no messages item, check for message info in
        # the cookies
        morsel = response.cookies.get('messages')
        if not morsel:
            return []

        # use the decoder in the CookieStore to process and get a list of
        # messages
        from django.contrib.messages.storage.cookie import CookieStorage
        store = CookieStorage(FakeRequest())
        messages = store._decode(morsel.value)
    else:
        return []

    return [(m.message, m.level) for m in messages]
Beispiel #3
0
 def assertLoginSuccess(self, resp, user):
     self.assertEqual(
         urlsplit(resp["Location"])[2], django_settings.LOGIN_REDIRECT_URL)
     msg = la_settings.MESSAGE_LOGIN_SWITCH.format(
         username=user.__dict__[la_settings.USERNAME_FIELD])
     messages = CookieStorage(resp)._decode(resp.cookies["messages"].value)
     self.assertIn(msg, "".join([m.message for m in messages]))
    def test_user_cant_change_own_group(self):
        """
        User cant change a group he's a part of,
        even with can_change_permissions set to True.
        """
        group = self._get_group()
        staff_user = self.get_staff_user_with_no_permissions()
        staff_user.groups.add(group)
        endpoint = self.get_admin_url(PageUserGroup, 'change', group.pk)
        redirect_to = admin_reverse('index')

        data = model_to_dict(group)
        data['_continue'] = '1'
        data['name'] = 'New test group'

        self.add_permission(staff_user, 'change_pageusergroup')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        with self.login_user_context(staff_user):
            response = self.client.post(endpoint, data)
            self.assertRedirects(response, redirect_to)
            msgs = CookieStorage(response)._decode(
                response.cookies['messages'].value)
            self.assertTrue(msgs[0], PageUserGroup._meta.verbose_name)
            self.assertTrue(msgs[0], 'ID "%s"' % group.pk)
            self.assertFalse(self._group_exists('New test group'))
Beispiel #5
0
    def test_user_cant_change_others_group(self):
        """
        User cant change a group created by another user,
        even with can_change_permissions set to True.
        """
        admin = self.get_superuser()
        group = self._get_group(created_by=admin)
        staff_user = self.get_staff_user_with_no_permissions()
        endpoint = self.get_admin_url(PageUserGroup, 'change', group.pk)
        redirect_to = admin_reverse('index')

        data = model_to_dict(group)
        data['_continue'] = '1'
        data['name'] = 'New test group'

        self.add_permission(staff_user, 'change_pageusergroup')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        with self.login_user_context(staff_user):
            response = self.client.post(endpoint, data)
            # Since Django 1.11 404 results in redirect to the admin home
            if DJANGO_1_10:
                self.assertEqual(response.status_code, 404)
            else:
                self.assertRedirects(response, redirect_to)
                msgs = CookieStorage(response)._decode(
                    response.cookies['messages'].value)
                self.assertTrue(msgs[0], PageUserGroup._meta.verbose_name)
                self.assertTrue(msgs[0], 'ID "%s"' % group.pk)
            self.assertFalse(self._group_exists('New test group'))
    def test_user_cant_delete_others_group(self):
        """
        User cant delete a group created by another user,
        even with can_change_permissions set to True.
        """
        admin = self.get_superuser()
        group = self._get_group(created_by=admin)
        staff_user = self.get_staff_user_with_no_permissions()
        endpoint = self.get_admin_url(PageUserGroup, 'delete', group.pk)
        redirect_to = admin_reverse('index')
        data = {'post': 'yes'}

        self.add_permission(staff_user, 'delete_group')
        self.add_permission(staff_user, 'delete_pageusergroup')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        with self.login_user_context(staff_user):
            response = self.client.post(endpoint, data)
            self.assertRedirects(response, redirect_to)
            msgs = CookieStorage(response)._decode(
                response.cookies['messages'].value)
            self.assertTrue(msgs[0], PageUserGroup._meta.verbose_name)
            self.assertTrue(msgs[0], 'ID "%s"' % group.pk)
            self.assertTrue(self._group_exists())
    def test_user_cant_delete_others(self):
        """
        User cant delete a user created by another user,
        even with can_change_permissions set to True.
        """
        admin = self.get_superuser()
        staff_user = self.get_staff_user_with_no_permissions()
        staff_user_2 = self.get_staff_page_user(created_by=admin)
        endpoint = self.get_admin_url(PageUser, 'delete', staff_user_2.pk)
        redirect_to = admin_reverse('index')

        data = {'post': 'yes'}

        self.add_permission(staff_user, self._get_delete_perm())
        self.add_permission(staff_user, 'delete_pageuser')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        with self.login_user_context(staff_user):
            username = getattr(staff_user_2, staff_user_2.USERNAME_FIELD)
            response = self.client.post(endpoint, data)
            self.assertRedirects(response, redirect_to)
            msgs = CookieStorage(response)._decode(response.cookies['messages'].value)
            self.assertTrue(msgs[0], PageUser._meta.verbose_name)
            self.assertTrue(msgs[0], 'ID "%s"' % staff_user_2.pk)
            self.assertTrue(self._user_exists(username))
Beispiel #8
0
 def _setup_request_object(self):
     self.request = HttpRequest()
     self.request.user = User.objects.create_user(
         username="******", email="*****@*****.**"
     )
     self.request._messages = CookieStorage(self.request)
     CrequestMiddleware.set_request(self.request)
Beispiel #9
0
    def assertLoginError(self, resp):
        self.assertEqual(urlsplit(resp["Location"])[2], "/")

        messages = CookieStorage(resp)._decode(resp.cookies["messages"].value)
        self.assertIn(
            (40, "You do not have permission to do that."),
            [(m.level, m.message) for m in messages],
        )
Beispiel #10
0
    def test_no_message_on_visit(self):
        """Clear out messages from django-allauth on sign up."""
        user = self.make_user()
        self.client.cookies["messages"] = CookieStorage(request=None)._encode(
            [Message(messages.INFO, "Find me")])

        with self.login(user):
            response = self.get("core:start")

        self.assertResponseNotContains("Find me", response)
        assert response.cookies["messages"].value == ""
Beispiel #11
0
def get_flash_messages(response, empty=True):
    if "messages" not in response.cookies:
        return []
    # A RequestFactory will not run the messages middleware, and thus will
    # not delete the messages after retrieval.
    dummy_request = RequestFactory().get("/")
    dummy_request.COOKIES["messages"] = response.cookies["messages"].value
    msgs = list(CookieStorage(dummy_request))
    if empty:
        del response.client.cookies["messages"]
    return msgs
    def test_authenticate_wrong_counter(self):
        self.device.counter = 160
        self.device.save()
        request = RequestFactory().get('/dummy/')
        request._messages = CookieStorage(request)

        self.assertRaisesMessage(PermissionDenied, "Counter didn't increase.",
                                 self.backend.authenticate, request, self.user,
                                 self.server, self.state, self.fido2_response)

        self.assertQuerysetEqual(Authenticator.objects.values_list(
            'user', 'counter'), [(self.user.pk, 160)],
                                 transform=tuple)
Beispiel #13
0
    def test_authenticate_wrong_counter(self):
        user = User.objects.create_user('kryten')
        U2fDevice.objects.create(user=user,
                                 version='U2F_V2',
                                 key_handle=self.key_handle,
                                 public_key=self.public_key,
                                 counter=42)
        request = RequestFactory().get('/dummy/')
        request._messages = CookieStorage(request)

        self.assertRaisesMessage(PermissionDenied, "Counter didn't increase.",
                                 self.backend.authenticate, request, user,
                                 self.u2f_request, self.u2f_response)

        self.assertQuerysetEqual(U2fDevice.objects.values_list(
            'user', 'counter'), [(user.pk, 42)],
                                 transform=tuple)
Beispiel #14
0
    def test_user_cant_change_others(self):
        """
        User cant change a users created by another user,
        even with can_change_permissions set to True.
        """
        admin = self.get_superuser()
        staff_user = self.get_staff_user_with_no_permissions()
        staff_user_2 = self.get_staff_page_user(created_by=admin)
        endpoint = self.get_admin_url(PageUser, 'change', staff_user_2.pk)
        redirect_to = admin_reverse('index')

        data = model_to_dict(staff_user_2, exclude=['date_joined'])
        data['_continue'] = '1'
        data['date_joined_0'] = '2016-06-21'
        data['date_joined_1'] = '15:00:00'

        self.add_permission(staff_user, 'change_pageuser')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        if staff_user_2.USERNAME_FIELD != "email":
            username = "******"
        else:
            username = "******"

        data[staff_user_2.USERNAME_FIELD] = username

        with self.login_user_context(staff_user):
            response = self.client.post(endpoint, data)
            if DJANGO_1_10:
                self.assertEqual(response.status_code, 404)
            else:
                self.assertRedirects(response, redirect_to)
                msgs = CookieStorage(response)._decode(
                    response.cookies['messages'].value)
                self.assertTrue(msgs[0], PageUser._meta.verbose_name)
                self.assertTrue(msgs[0], 'ID "%s"' % staff_user_2.pk)
            self.assertFalse(self._user_exists(username))
Beispiel #15
0
    def test_successful_comment(self, mock_submit):
        mock_submit.return_value.status_code = 201
        mock_submit.return_value.text = '{"trackingNumber": "FAKE_TRACK_NUM"}'
        data = {
            'comment_on': 'FAKE_DOC_NUM',
            'general_comment': 'FAKE_COMMENT',
            'first_name': 'FAKE_FIRST',
            'last_name': 'FAKE_LAST'
        }
        response = self.client.post(reverse('reg_comment'), data)

        mock_submit.assert_called_with(QueryDict(urlencode(data)))
        self.assertEquals(
            urlparse(response['Location']).path,
            reverse('reg_comment:success'))
        # TODO: There may be a better way to get messages_list,
        # fix if possible
        messages_list = CookieStorage(response)._decode(
            response.cookies['messages'].value)
        self.assertEqual(len(messages_list), 1)
        self.assertEqual(messages_list[0].message, 'FAKE_TRACK_NUM')
        self.assertEqual(messages_list[0].level, SUCCESS)
Beispiel #16
0
    def test_user_cant_delete_others(self):
        """
        User cant delete a user created by another user,
        even with can_change_permissions set to True.
        """
        admin = self.get_superuser()
        staff_user = self.get_staff_user_with_no_permissions()
        staff_user_2 = self.get_staff_page_user(created_by=admin)
        endpoint = self.get_admin_url(PageUser, 'delete', staff_user_2.pk)
        redirect_to = admin_reverse('index')

        data = {'post': 'yes'}

        self.add_permission(staff_user, self._get_delete_perm())
        self.add_permission(staff_user, 'delete_pageuser')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        with self.login_user_context(staff_user):
            username = getattr(staff_user_2, staff_user_2.USERNAME_FIELD)
            response = self.client.post(endpoint, data)
            # The response is a 404 instead of a 403
            # because the queryset is limited to objects
            # that the user has permissions for.
            # This queryset is used to fetch the object
            # from the request, resulting in a 404.
            # Since Django 1.11 404 results in redirect to the admin home
            if DJANGO_1_10:
                self.assertEqual(response.status_code, 404)
            else:
                self.assertRedirects(response, redirect_to)
                msgs = CookieStorage(response)._decode(
                    response.cookies['messages'].value)
                self.assertTrue(msgs[0], PageUser._meta.verbose_name)
                self.assertTrue(msgs[0], 'ID "%s"' % staff_user_2.pk)
            self.assertTrue(self._user_exists(username))
Beispiel #17
0
    def test_user_cant_delete_own_group(self):
        """
        User cant delete a group he's a part of,
        even with can_change_permissions set to True.
        """
        group = self._get_group()
        staff_user = self.get_staff_user_with_no_permissions()
        staff_user.groups.add(group)
        endpoint = self.get_admin_url(PageUserGroup, 'delete', group.pk)
        redirect_to = admin_reverse('index')
        data = {'post': 'yes'}

        self.add_permission(staff_user, 'delete_group')
        self.add_permission(staff_user, 'delete_pageusergroup')
        self.add_page_permission(
            staff_user,
            self._permissions_page,
            can_change_permissions=True,
        )

        with self.login_user_context(staff_user):
            response = self.client.post(endpoint, data)
            # The response is a 404 instead of a 403
            # because the queryset is limited to objects
            # that the user has permissions for.
            # This queryset is used to fetch the object
            # from the request, resulting in a 404.
            # Since Django 1.11 404 results in redirect to the admin home
            if DJANGO_1_10:
                self.assertEqual(response.status_code, 404)
            else:
                self.assertRedirects(response, redirect_to)
                msgs = CookieStorage(response)._decode(
                    response.cookies['messages'].value)
                self.assertTrue(msgs[0], PageUserGroup._meta.verbose_name)
                self.assertTrue(msgs[0], 'ID "%s"' % group.pk)
            self.assertTrue(self._group_exists())
 def assertLoginError(self, resp):
     messages = CookieStorage(resp)._decode(resp.cookies['messages'].value)
     self.assertEqual([(m.level, m.message) for m in messages],
                      [(40, "Permision denied.")])
Beispiel #19
0
 def assertLoginError(self, resp):
     messages = CookieStorage(resp)._decode(resp.cookies['messages'].value)
     self.assertIn((40, u"You do not have permission to do that."),
                   [(m.level, m.message) for m in messages])
def get_messages_as_list(response):
    return CookieStorage(response)._decode(response.cookies['messages'].value)
Beispiel #21
0
def get_messages_from_cookie(cookies):
    request = HttpRequest()
    request.COOKIES = {CookieStorage.cookie_name: cookies.get(
        CookieStorage.cookie_name).value}
    return CookieStorage(request)
Beispiel #22
0
 def assertLoginSuccess(self, resp, user):
     self.assertEqual(
         urlsplit(resp['Location'])[2], django_settings.LOGIN_REDIRECT_URL)
     msg = la_settings.MESSAGE_LOGIN_SWITCH.format(username=user.username)
     messages = CookieStorage(resp)._decode(resp.cookies['messages'].value)
     self.assertIn(msg, "".join([m.message for m in messages]))