Exemplo n.º 1
0
    def test_api_object_get(self):
        url_name = "object-detail"
        StartupFactory(id=1)
        view_kwargs = {
            'app': 'accelerator',
            "model": "startup",
            "pk": 1,
        }
        self.response_401(self.get(url_name, **view_kwargs))
        startup_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(app_label='accelerator',
                                                 model='startup'),
            codename='view_startup',
        )
        basic_user = self.make_user('*****@*****.**')
        with self.login(basic_user):
            self.response_403(self.get(url_name, **view_kwargs))

        perm_user = self.make_user('*****@*****.**',
                                   perms=["mc.view_startup"])
        perm = PermissionFactory.create(codename='change_startup')
        view_perm = PermissionFactory.create(codename='view_startup')
        perm_user.user_permissions.add(perm)
        perm_user.user_permissions.add(startup_permission)
        perm_user.user_permissions.add(view_perm)
        perm_user.save()
        with self.login(perm_user):
            response = self.get(url_name, **view_kwargs)
            self.response_200(response)
            response_dict = json.loads(response.content)
            self.assertIn("is_visible", response_dict.keys())
Exemplo n.º 2
0
 def test_user_with_permissions_can_create_objects(self):
     url_name = "object-list"
     program_role = ProgramRoleFactory(id=1)
     startup_status = StartupStatusFactory(id=1)
     view_kwargs = {
         'app': 'accelerator',
         "model": "programrole",
     }
     self.response_401(self.get(url_name, **view_kwargs))
     program_role_permission, _ = Permission.objects.get_or_create(
         content_type=ContentType.objects.get(app_label='accelerator',
                                              model='programrole'),
         codename='add_programrole',
     )
     perm_user = self.make_user('*****@*****.**',
                                perms=["mc.add_programrole"])
     perm = PermissionFactory.create(codename='change_programrole')
     view_perm = PermissionFactory.create(codename='view_programrole')
     perm_user.user_permissions.add(perm)
     perm_user.user_permissions.add(program_role_permission)
     perm_user.user_permissions.add(view_perm)
     perm_user.save()
     self.assertFalse(
         ProgramRole.objects.filter(name="2011 - Final").exists())
     with self.login(perm_user):
         self.post(url_name,
                   data={
                       "name": "2011 - Final",
                       "program": program_role.id,
                       "user_role": startup_status.id
                   },
                   **view_kwargs)
         self.assertTrue(
             ProgramRole.objects.filter(name="2011 - Final").exists())
Exemplo n.º 3
0
    def test_api_object_list(self):
        StartupFactory(is_visible=1, organization__url_slug="test1")
        StartupFactory(is_visible=1, organization__url_slug="test2")
        StartupFactory(is_visible=1, organization__url_slug="test3")
        Permission.objects.get_or_create(
            content_type=ContentType.objects.get(app_label='accelerator',
                                                 model='startup'),
            codename='view_startup_stealth_mode_false')
        view_perm, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(app_label='accelerator',
                                                 model='startup'),
            codename='view_startup')
        url_name = "object-list"
        view_kwargs = {'app': 'accelerator', "model": "startup"}
        self.response_401(self.get(url_name, **view_kwargs))

        basic_user = self.make_user('*****@*****.**')
        with self.login(basic_user):
            self.response_403(self.get(url_name, **view_kwargs))

        perm_user = self.make_user('*****@*****.**',
                                   perms=["mc.view_startup"])
        perm_user.user_permissions.add(view_perm)
        perm_user.save()
        with self.login(perm_user):
            response = self.get(url_name, **view_kwargs)
            self.response_200(response)
            response_dict = json.loads(response.content)
            self.assertIn("short_pitch", response_dict['results'][0].keys())
            for startup in response_dict['results']:
                self.assertEqual(startup["is_visible"], 1)
        PermissionFactory.create(codename='change_startup')
        PermissionFactory.create(codename='delete_startup')
        view_perm = PermissionFactory.create(codename='view_startup')
Exemplo n.º 4
0
    def test_api_object_get_field_filter(self):
        startup_content_type = ContentType.objects.get(app_label='accelerator',
                                                       model='startup')
        stealth_perm = PermissionFactory(
            content_type=startup_content_type,
            codename='view_startup_stealth_mode_true')
        StartupFactory(id=3, is_visible=0)
        url_name = "object-detail"
        view_kwargs = {
            'app': 'accelerator',
            "model": "startup",
            "pk": 3,  # has stealth mode enabled
        }
        response = self.get(url_name, **view_kwargs)
        self.response_401(response)

        basic_user = self.make_user('*****@*****.**')
        with self.login(basic_user):
            response = self.get(url_name, **view_kwargs)
            self.response_403(response)

        perm_user = self.make_user('*****@*****.**',
                                   perms=["mc.view_startup"])
        perm = Permission.objects.get(codename='change_startup',
                                      content_type=startup_content_type)
        view_perm = PermissionFactory.create(codename='view_startup',
                                             content_type=startup_content_type)
        perm_user.save()
        with self.login(perm_user):
            self.response_403(self.get(url_name, **view_kwargs))

        correct_perm_user = self.make_user(
            '*****@*****.**',
            perms=[
                "mc.view_startup", "mc.change_startup",
                "mc.view_startup_stealth_mode_true"
            ])
        correct_perm_user.user_permissions.add(perm)
        correct_perm_user.user_permissions.add(view_perm)
        correct_perm_user.user_permissions.add(stealth_perm)
        correct_perm_user.save()
        with self.login(correct_perm_user):
            response = self.get(url_name, **view_kwargs)
            self.response_200(response)
            response_dict = json.loads(response.content)
            self.assertIn("is_visible", response_dict.keys())
Exemplo n.º 5
0
 def _grant_permissions(self,
                        user,
                        model_name,
                        permissions=['change', 'view', 'add']):
     for action in permissions:
         permission = PermissionFactory.create(
             codename='{action}_{model_name}'.format(action=action,
                                                     model_name=model_name))
         user.user_permissions.add(permission)
     user.save()
    def test_api_object_relation_link_is_valid(self):
        url_name = "object-list"
        view_kwargs = {'app': 'accelerator', "model": "startupteammember"}
        StartupTeamMemberFactory()
        User = get_user_model()
        perm = PermissionFactory.create(codename='change_user')
        user = User.objects.create_superuser("*****@*****.**", "password")
        startup_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startup'),
            codename='view_startup_stealth_mode_true',
            name='Can view Startups in Stealth Mode',
        )
        startup_member_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startupteammember'),
            codename='view_startupteammember',
        )
        user_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='simpleuser',
                model='user'),
            codename='view_user',
        )
        user.user_permissions.add(user_permission)
        user.user_permissions.add(perm)
        user.user_permissions.add(startup_permission)
        user.user_permissions.add(startup_member_permission)
        user.save()

        with self.login(email="*****@*****.**"):
            response = self.get(url_name, **view_kwargs)
            self.response_200(response)

            response_dict = json.loads(response.content)
            self.assertIn("user", response_dict['results'][0].keys())
            entrepreneur_id = response_dict['results'][0]['user']
            detail_args = {'app': 'simpleuser', "model": "user"}

            detail_args['pk'] = entrepreneur_id
            detail_response = self.get('object-detail', **detail_args)
            detail_json = json.loads(detail_response.content)
            self.assertEqual(detail_json['id'], entrepreneur_id)
 def test_api_list_contains_url_to_related_object(self):
     url_name = "object-list"
     view_kwargs = {'app': 'accelerator', "model": "startupteammember"}
     StartupTeamMemberFactory()
     User = get_user_model()
     user = User.objects.create_superuser("*****@*****.**", "password")
     perm = PermissionFactory.create(codename='change_user')
     startup_permission, _ = Permission.objects.get_or_create(
         content_type=ContentType.objects.get(
             app_label='accelerator',
             model='startup'),
         codename='view_startup_stealth_mode_true',
         name='Can view Startups in Stealth Mode',
     )
     startupteammember_permission, _ = Permission.objects.get_or_create(
         content_type=ContentType.objects.get(
             app_label='accelerator',
             model='startupteammember'),
         codename='view_startupteammember',
     )
     user.user_permissions.add(perm)
     user.user_permissions.add(startup_permission)
     user.user_permissions.add(startupteammember_permission)
     user.save()
     with self.login(email="*****@*****.**"):
         response = self.get(url_name, **view_kwargs)
         self.response_200(response)
         response_dict = json.loads(response.content)
         self.assertIn("user", response_dict['results'][0].keys())
         entrepreneur_id = response_dict['results'][0]['user']
         detail_args = {'app': 'simpleuser', "model": "user"}
         detail_args['pk'] = entrepreneur_id
         detail_url = reverse('object-detail', kwargs=detail_args)
         absolute_uri = response.wsgi_request.build_absolute_uri(
             detail_url)
         detail_args['pk'] = response_dict['results'][0]['user']
         returned_uri = response.wsgi_request.build_absolute_uri(
             reverse('object-detail',
                     kwargs=detail_args))
         self.assertEqual(
             returned_uri,
             absolute_uri)
Exemplo n.º 8
0
    def test_api_object_delete(self):
        StartupFactory(id=2)
        url_name = "object-detail"
        view_kwargs = {
            'app': 'accelerator',
            "model": "startup",
            "pk": 2,
        }
        self.response_401(self.get(url_name, **view_kwargs))

        basic_user = self.make_user('*****@*****.**')
        startup_delete_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(app_label='accelerator',
                                                 model='startup'),
            codename='delete_startup',
        )
        startup_view_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(app_label='accelerator',
                                                 model='startup'),
            codename='delete_startup',
        )
        with self.login(basic_user):
            response = self.get(url_name, **view_kwargs)
            self.response_403(response)
        perm_user = self.make_user('*****@*****.**',
                                   perms=[
                                       "mc.view_startup", "mc.change_startup",
                                       "mc.delete_startup"
                                   ])
        perm = PermissionFactory.create(codename='change_startup')
        perm_user.user_permissions.add(perm)
        perm_user.user_permissions.add(startup_delete_permission)
        perm_user.user_permissions.add(startup_view_permission)
        perm_user.save()
        with self.login(perm_user):
            self.delete(url_name, **view_kwargs)
            self.assertEqual(204, self.last_response.status_code)
    def test_oauth_auth_code_grant_workflow(self):
        # project setup
        basic_user = self.make_user(
            '*****@*****.**', perms=["mc.view_startup"])
        startup_content_type = ContentType.objects.get(app_label='accelerator',
                                                       model='startup')
        perm = PermissionFactory.create(content_type=startup_content_type,
                                        codename='view_startup')
        startup_member_permission, _ = Permission.objects.get_or_create(
            content_type=startup_content_type,
            codename='view_startup_stealth_mode_true',
            name='Can view Startups in Stealth Mode',
        )
        startup_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startupteammember'),
            codename='view_startupteammember',
        )
        basic_user.user_permissions.add(perm)
        basic_user.user_permissions.add(startup_permission)
        basic_user.user_permissions.add(startup_member_permission)
        basic_user.save()
        app = OAuth_App.objects.create(
            user=basic_user,
            name='Test666',
            client_type=OAuth_App.CLIENT_PUBLIC,
            authorization_grant_type=OAuth_App.GRANT_AUTHORIZATION_CODE,
            redirect_uris='http://thirdparty.com/exchange/',
        )

        # a user is directed to a link, and asked to login
        self.get(
            'oauth2_provider:authorize',
            data={
                'client_id': app.client_id,
                'response_type': 'code',
                "state": 'random_state_string',
            },
        )
        self.response_302()
        expected_redirect = (
            "{}?next={}"
            "%3Fclient_id%3D{}"
            "%26response_type%3D{}"
            "%26state%3D{}".format(
                self.reverse("auth_login"),
                self.reverse("oauth2_provider:authorize"),
                app.client_id,
                "code",
                "random_state_string",
            )
        )
        self.assertEqual(self.last_response.url, expected_redirect)

        # we login the user, and then proceed
        with self.login(basic_user):
            # with the login, we ask for the same page as before
            # the site asks whether the user would like to allow
            # the third party site to access data on this provider site
            self.get_check_200(
                "oauth2_provider:authorize",
                data={
                    "client_id": app.client_id,
                    "response_type": "code",
                    "state": "random_state_string",
                },
            )
            # the user, presumably, responds with a yes
            self.post(
                "oauth2_provider:authorize",
                data={
                    # from third party app
                    "client_id": app.client_id,
                    "response_type": "code",
                    "state": "random_state_string",
                    # put in form by Django
                    "redirect_uri": "http://thirdparty.com/exchange/",
                    "scope": "read write groups",
                    "allow": "Authorize",
                },
            )
            # the Django site will subsequently redirect to the third party
            # providing a code in the process
            self.response_302()
            token_code = (
                parse_qs(urlparse(self.last_response.url).query)['code'])

            # the third party site should use this code to ask for a token
            self.post(
                "oauth2_provider:token",
                data={
                    "client_id": app.client_id,
                    "client_secret": app.client_secret,
                    "code": token_code,
                    "redirect_uri": "http://thirdparty.com/exchange/",
                    "grant_type": "authorization_code",
                },
            )
            token_data = self.last_response.json()
            self.assertIn('access_token', token_data)
            self.assertIn('refresh_token', token_data)
            self.assertIn('token_type', token_data)
            self.assertIn('expires_in', token_data)

            # this token can be used to access data
            self.get_check_200(
                self.reverse(
                    "object-list", model='startup', app='accelerator'),
                extra={
                    "HTTP_AUTHORIZATION":
                        "{} {}".format(
                            token_data['token_type'],
                            token_data['access_token'],
                        ),
                },
            )
Exemplo n.º 10
0
    def test_oauth_password_grant_workflow(self):
        Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startup'),
            codename='view_startup'
        )
        basic_user = self.make_user(
            '*****@*****.**', perms=["mc.change_startup"])
        app = OAuth_App.objects.create(
            user=basic_user,
            name="Test666",
            client_type=OAuth_App.CLIENT_PUBLIC,
            authorization_grant_type=OAuth_App.GRANT_PASSWORD,
            redirect_uris="http://example.com",
        )
        startup_stealth_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startup'),
            codename='view_startup_stealth_mode_true',
            name='Can view Startups in Stealth Mode',
        )
        startup_member_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startupteammember'),
            codename='view_startupteammember',
        )
        startup_permission, _ = Permission.objects.get_or_create(
            content_type=ContentType.objects.get(
                app_label='accelerator',
                model='startup'),
            codename='view_startup',
        )

        perm = PermissionFactory.create(codename='change_startup')
        basic_user.user_permissions.add(perm)
        basic_user.user_permissions.add(startup_stealth_permission)
        basic_user.user_permissions.add(startup_permission)
        basic_user.user_permissions.add(startup_member_permission)
        basic_user.save()
        # a third party site prompts the user for username and password
        # and then sends that data to us
        token_request_data = {
            "grant_type": "password",
            "username": "******",
            "password": "******",
        }
        user_pass = "******".format(app.client_id, app.client_secret)
        auth_string = base64.b64encode(user_pass.encode("utf-8"))
        self.post(
            "oauth2_provider:token",
            data=token_request_data,
            extra={
                "HTTP_AUTHORIZATION":
                    "Basic {}".format(auth_string.decode("utf8")),
            },
        )
        self.response_200()

        # the site should return a token
        # the token shoule be used to consume data from the API
        content = json.loads(self.last_response.content.decode("utf-8"))
        access_token = content["access_token"]
        token_type = content["token_type"]
        self.get_check_200(
            self.reverse(
                "object-list", model='startup', app='accelerator'),
            extra={
                "HTTP_AUTHORIZATION":
                    "{} {}".format(token_type, access_token),
            },
        )