Example #1
0
 def testResetPassword(self):
     """
     Test creation of a user. No authentication
     """
     test_email = '*****@*****.**'
     view = UserEndpoint.as_view({'post': 'create'})
     request = self.factory.post(
         '/api/users/', {
             'email': test_email,
             'password': '******',
             'password_confirm': '1234567890',
             'terms': True,
         })
     request.user = AnonymousUser()
     response = view(request)
     response.render()
     qs = User.objects.get(email=test_email)
     view = UserEndpoint.as_view({'get': 'activate'},
                                 **UserEndpoint.activate.kwargs)
     token = UserValidateEmailRole.objects.get(user=qs).token
     url = '/api/users/activate/?token={}&email={}&subdomain=www'.format(
         token, test_email)
     request = self.factory.get(url, {})
     engine = import_module(settings.SESSION_ENGINE)
     request.session = engine.SessionStore()
     request.user = AnonymousUser()
     response = view(request)
     self.assertEquals(response.status_code, status.HTTP_302_FOUND)
Example #2
0
    def testCreateWeb(self):
        """
        Test creation of a user. No authentication
        """
        test_email = '*****@*****.**'
        view = UserEndpoint.as_view({'post': 'create'})
        request = self.factory.post(
            '/api/users/', {
                'email': test_email,
                'password': '******',
                'password_confirm': '1234567890',
                'terms': True,
            })
        request.user = AnonymousUser()

        response = view(request)
        self.assertIs(response.status_code, status.HTTP_201_CREATED)

        response.render()
        created_user = User.objects.get(email=test_email)
        serializer = WebUserSerializer(created_user)
        serialized_db = JSONRenderer().render({
            'success': True,
            'user': serializer.data
        })
        self.assertEqual(response.content, serialized_db)
        self.assertEqual(
            UserValidateEmailRole.objects.filter(user=created_user).count(), 1)
        self.assertEqual(
            UserProfile.objects.filter(user=created_user).count(), 1)
        self.assertEqual(
            UserNeedsToRegisterRole.objects.filter(user=created_user).count(),
            1)
        self.assertEqual(
            BitcoinWallet.objects.filter(user=created_user).count(), 1)
Example #3
0
 def test_login_without_referer_and_with_valid_cookie(self):
     from ..models import User
     alice = User.objects.create(email='*****@*****.**',
                                 username='******',
                                 is_active=True)
     alice.set_password('secret')
     alice.save()
     url = '/api/users/login/'
     data = {'email': alice.email, 'password': '******'}
     view = UserEndpoint.as_view({'post': 'login'},
                                 **UserEndpoint.login.kwargs)
     factory = APIRequestFactory(enforce_csrf_checks=True)
     csrf_token = 'cookiemonster'
     headers = {
         'wsgi.url_scheme': 'https',
         'HTTP_X_CSRFTOKEN': csrf_token,
     }
     # TODO when available, use secure parameter:
     # request = factory.post(url, data, secure=True)
     # as of 2015.08.03 it is on master:
     # https://github.com/tomchristie/django-rest-framework
     # in the meantime, we can use this nice trick from:
     # http://codeinthehole.com/writing/testing-https-handling-in-django/
     request = factory.post(url, data, **headers)
     request.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token
     engine = import_module(settings.SESSION_ENGINE)
     request.session = engine.SessionStore()
     response = view(request)
     self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
     self.assertInHTML(self.CSRF_FAILED_MSG, response.content)
     self.assertInHTML(self.MISSING_REFERER_MSG, response.content)
Example #4
0
    def test_user_email_case_insensitivity(self):
        """
        Test creating a user with an email for which there is already an
        existing user with the same email, regardless of the case.

        """
        email = '*****@*****.**'
        User.objects.create(email=email)
        view = UserEndpoint.as_view({'post': 'create'})
        request = self.factory.post(
            '/api/users/', {
                'email': email.upper(),
                'password': '******',
                'password_confirm': '1234567890',
                'terms': True,
            })
        request.user = AnonymousUser()
        response = view(request)
        # check that the response is as expected
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(len(response.data), 2)
        self.assertIn('errors', response.data)
        self.assertEqual(len(response.data['errors']), 1)
        self.assertIn('email', response.data['errors'])
        self.assertListEqual(
            response.data['errors']['email'],
            ['An account with this email/username already exists.'])
        self.assertIn('success', response.data)
        self.assertFalse(response.data['success'])
        self.assertFalse(User.objects.filter(email=email.upper()).exists())
Example #5
0
 def test_login_with_valid_referer_and_invalid_cookie(self):
     from ..models import User
     alice = User.objects.create(email='*****@*****.**',
                                 username='******',
                                 is_active=True)
     alice.set_password('secret')
     alice.save()
     url = '/api/users/login/'
     data = {'email': alice.email, 'password': '******'}
     view = UserEndpoint.as_view({'post': 'login'},
                                 **UserEndpoint.login.kwargs)
     factory = APIRequestFactory(enforce_csrf_checks=True)
     host = 'testserver:80'  # TODO if possible, set this programmatically
     good_referer = 'https://{}/'.format(host)
     headers = {
         'wsgi.url_scheme': 'https',
         'HTTP_REFERER': good_referer,
         'HTTP_X_CSRFTOKEN': 'chocolatecookie',
     }
     # TODO when available, use secure parameter:
     # request = factory.post(url, data, secure=True)
     # as of 2015.08.03 it is on master:
     # https://github.com/tomchristie/django-rest-framework
     # in the meantime, we can use this nice trick from:
     # http://codeinthehole.com/writing/testing-https-handling-in-django/
     request = factory.post(url, data, **headers)
     request.COOKIES[settings.CSRF_COOKIE_NAME] = 'vanillacookie'
     engine = import_module(settings.SESSION_ENGINE)
     request.session = engine.SessionStore()
     response = view(request)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertDictEqual(response.data, {'success': True})
Example #6
0
    def testUnauthenticatedUser(self):
        # HTTP GET actions
        request = self.factory.get('/api/0.1/users/')
        for action in self.ACTIONS_GET:
            view = UserEndpoint.as_view({'get': action})
            response = view(request)
            self.assertEqual(response.status_code,
                             status.HTTP_401_UNAUTHORIZED)

        # HTTP POST actions
        request = self.factory.post('api/0.1/users/', {})
        for action in self.ACTIONS_POST:
            view = UserEndpoint.as_view({'post': action})
            response = view(request)
            self.assertNotIn(
                response.status_code,
                [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
Example #7
0
    def testRetrieveOtherWeb(self):
        """
        Test that a user cannot retrieve other users.
        """
        view = UserEndpoint.as_view({'get': 'retrieve'})
        url = '/api/users/{0}/'.format(self.other_user.id)
        request = self.factory.get(url)
        force_authenticate(request, user=self.web_user)

        response = view(request, pk=self.other_user.pk)
        self.assertIs(response.status_code, status.HTTP_404_NOT_FOUND)

        response.render()
        self.assertEqual(response.content, '{"success":false}')
Example #8
0
 def test_request_reset_password(self):
     from ..models import User
     alice = User.objects.create(email='*****@*****.**',
                                 username='******',
                                 is_active=True)
     alice.set_password('secret')
     alice.save()
     url = '/api/users/request_reset_password/'
     data = {'email': alice.email}
     view = UserEndpoint.as_view(
         {'post': 'request_reset_password'},
         **UserEndpoint.request_reset_password.kwargs)
     request = self.factory.post(url, data)
     force_authenticate(request, user=alice)
     response = view(request)
     self.assertIs(response.status_code, status.HTTP_200_OK)
Example #9
0
    def testRetrieveWeb(self):
        """
        Test that a user can only retrieve himself.
        """
        view = UserEndpoint.as_view({'get': 'retrieve'})
        url = '/api/users/{0}/'.format(self.web_user.id)
        request = self.factory.get(url)

        force_authenticate(request, user=self.web_user)

        response = view(request, pk=self.web_user.pk)
        self.assertIs(response.status_code, status.HTTP_200_OK)

        response.render()
        qs = User.objects.get(pk=self.web_user.pk)
        serializer = WebUserSerializer(qs, context={'request': request})
        serialized_db = JSONRenderer().render({
            'success': True,
            'user': serializer.data
        })
        self.assertEqual(response.content, serialized_db)
Example #10
0
 def test_login_with_invalid_referer_without_cookie(self):
     from ..models import User
     alice = User.objects.create(email='*****@*****.**',
                                 username='******',
                                 is_active=True)
     alice.set_password('secret')
     alice.save()
     url = '/api/users/login/'
     data = {'email': alice.email, 'password': '******'}
     view = UserEndpoint.as_view({'post': 'login'},
                                 **UserEndpoint.login.kwargs)
     factory = APIRequestFactory(enforce_csrf_checks=True)
     host = 'testserver:80'  # TODO if possible, set this programmatically
     good_referer = 'https://{}/'.format(host)
     bad_referer = 'https://XYZ{}/'.format(host)
     headers = {
         'wsgi.url_scheme': 'https',
         'HTTP_REFERER': bad_referer,
     }
     # TODO when available, use secure parameter:
     # request = factory.post(url, data, secure=True)
     # as of 2015.08.03 it is on master:
     # https://github.com/tomchristie/django-rest-framework
     # in the meantime, we can use this nice trick from:
     # http://codeinthehole.com/writing/testing-https-handling-in-django/
     request = factory.post(url, data, **headers)
     engine = import_module(settings.SESSION_ENGINE)
     request.session = engine.SessionStore()
     with self.settings(DEBUG=True):
         response = view(request)
         self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
         self.assertInHTML(self.CSRF_FAILED_MSG, response.content)
         self.assertInHTML(self.REASON_FOR_FAILURE_MSG, response.content)
         self.assertInHTML(
             self.INVALID_REFERER_MSG.format(bad_referer=bad_referer,
                                             good_referer=good_referer),
             response.content)
Example #11
0
    def testListWeb(self):
        """
        Test that a web user can only see himself.
        He should not have access to the other users in the db.
        """
        view = UserEndpoint.as_view({'get': 'list'})
        request = self.factory.get('/api/users/')
        force_authenticate(request, user=self.web_user)

        response = view(request)
        self.assertIs(response.status_code, status.HTTP_200_OK)

        # render the response so that we get the serialized json
        response.render()
        # get serialize the user form the db
        qs = User.objects.filter(pk=self.web_user.pk)
        serializer = WebUserSerializer(qs,
                                       many=True,
                                       context={'request': request})
        serialized_db = JSONRenderer().render({
            'success': True,
            'users': serializer.data
        })
        self.assertEqual(response.content, serialized_db)
    def test_execute_pending_actions(self):
        piece, editions = self.create_piece(self.user1,
                                            self.digitalwork_user1,
                                            self.thumbnail_user1,
                                            num_editions=2)
        edition = editions[0]

        # transfer to user3, who is not in the system
        self.create_transfer(self.user1, self.user3_email, edition.bitcoin_id,
                             self.password)
        ownership_transfer = OwnershipTransfer.objects.get(edition=edition)

        # check user and roles
        try:
            user3 = User.objects.get(email=self.user3_email)
        except User.DoesNotExist:
            self.assertFalse(True, 'User was not created')

        user3_roles = Role.objects.filter(user=user3)
        self.assertEqual(len(user3_roles), 2)

        validate_role = UserValidateEmailRole.objects.get(user=user3)
        self.assertIsNone(validate_role.datetime_response)

        try:
            UserNeedsToRegisterRole.objects.get(user=user3,
                                                type="UserNeedsToRegisterRole")
        except UserNeedsToRegisterRole.DoesNotExist:
            self.assertFalse(True, 'UserNeedsToRegisterRole was not created')

        # check pending ownership
        self.assertEqual(ownership_transfer.edition.pending_new_owner, user3)
        self.assertEqual(ownership_transfer.edition.owner, self.user1)

        # check acls
        acl_user1 = ActionControl.objects.get(
            user=self.user1,
            piece=ownership_transfer.edition.parent,
            edition=ownership_transfer.edition)
        acl_user3 = ActionControl.objects.get(
            user=user3,
            piece=ownership_transfer.edition.parent,
            edition=ownership_transfer.edition)
        self.assertTrue(acl_user1.acl_withdraw_transfer)
        self.assertFalse(acl_user1.acl_unshare)
        self.assertTrue(acl_user3.acl_transfer)

        token = UserValidateEmailRole.objects.get(user=user3).token

        # signup & activate user3
        view = UserEndpoint.as_view({'post': 'create'})
        request = self.factory.post(
            '/api/users/', {
                'email': self.user3_email,
                'password': '******',
                'password_confirm': '1234567890',
                'terms': True,
                'token': token
            })
        engine = import_module(settings.SESSION_ENGINE)
        request.session = engine.SessionStore()
        request.user = AnonymousUser()

        response = view(request)
        self.assertIs(response.status_code, status.HTTP_201_CREATED)

        # check user roles
        validate_role = UserValidateEmailRole.objects.get(user=user3)
        self.assertIsNotNone(validate_role.datetime_response)
        with self.assertRaises(UserNeedsToRegisterRole.DoesNotExist):
            UserNeedsToRegisterRole.objects.get(user=user3,
                                                type="UserNeedsToRegisterRole")

        # check pending ownership
        ownership_transfer = OwnershipTransfer.objects.get(edition=edition)
        self.assertIsNone(ownership_transfer.edition.pending_new_owner)
        self.assertEqual(ownership_transfer.edition.owner, user3)

        # check acls
        acl_user1 = ActionControl.objects.get(
            user=self.user1,
            piece=ownership_transfer.edition.parent,
            edition=ownership_transfer.edition)
        acl_user3 = ActionControl.objects.get(
            user=user3,
            piece=ownership_transfer.edition.parent,
            edition=ownership_transfer.edition)
        self.assertFalse(acl_user1.acl_withdraw_transfer)
        self.assertTrue(acl_user1.acl_unshare)
        self.assertTrue(acl_user3.acl_transfer)
Example #13
0
 def create_user_needs_to_register(email):
     return UserEndpoint._createNewUser(email, '0' * 10, invited=True)
Example #14
0
 def create_user(email, password='******', application=None):
     # TODO create user differently -- no need to send an email for instance
     return UserEndpoint._createNewUser(email,
                                        password,
                                        application=application)