예제 #1
0
    def test_does_need_refresh(self):
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            expires_at=datetime.utcfromtimestamp(time.time() - 200).replace(tzinfo=pytz.utc),
        )

        # mock a successful call to the provider to refresh tokens
        responses.add(
            responses.Response(
                responses.POST,
                self.provider.auto_refresh_url,
                body=json.dumps({
                    'access_token': 'refreshed_access_token',
                    'expires_in': 3600,
                    'refresh_token': 'refreshed_refresh_token'
                })
            )
        )

        old_expiry = external_account.expires_at
        self.provider.account = external_account
        self.provider.refresh_oauth_key(force=False)
        external_account.reload()

        assert_equal(external_account.oauth_key, 'refreshed_access_token')
        assert_equal(external_account.refresh_token, 'refreshed_refresh_token')
        assert_not_equal(external_account.expires_at, old_expiry)
        assert_true(external_account.expires_at > old_expiry)
예제 #2
0
파일: test_oauth.py 프로젝트: leb2dg/osf.io
    def test_does_not_need_refresh(self):
        self.provider.refresh_time = 1
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            refresh_token='old_refresh',
            expires_at=datetime.utcfromtimestamp(time.time() + 200).replace(tzinfo=pytz.utc),
        )

        # mock a successful call to the provider to refresh tokens
        httpretty.register_uri(
            httpretty.POST,
            self.provider.auto_refresh_url,
            body=json.dumps({
                'err_msg': 'Should not be hit'
            }),
            status=500
        )

        # .reload() has the side effect of rounding the microsends down to 3 significant figures
        # (e.g. DT(YMDHMS, 365420) becomes DT(YMDHMS, 365000)),
        # but must occur after possible refresh to reload tokens.
        # Doing so before allows the `old_expiry == EA.expires_at` comparison to work.
        external_account.reload()
        old_expiry = external_account.expires_at
        self.provider.account = external_account
        self.provider.refresh_oauth_key(force=False)
        external_account.reload()

        assert_equal(external_account.oauth_key, 'old_key')
        assert_equal(external_account.refresh_token, 'old_refresh')
        assert_equal(external_account.expires_at, old_expiry)
예제 #3
0
    def setUp(self):
        super(TestCallbackView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()
        self.institution = InstitutionFactory()

        self.provider = MockOAuth2Provider(self.external_account)

        self.user.affiliated_institutions.add(self.institution)

        app = flask.Flask(__name__)
        make_url_map(app)
        app.config['SECRET_KEY'] = 'aaaaa'
        self.ctx = app.test_request_context()
        self.ctx.push()

        self.request = RequestFactory().get('/fake_path')
        add_session_to_request(self.request)
        self.view0 = views.ConnectView()
        self.view0 = setup_user_view(self.view0, self.request, user=self.user)
        self.view0.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }

        self.view = views.CallbackView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }
예제 #4
0
    def test_does_need_refresh(self):
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            expires_at=datetime.utcfromtimestamp(time.time() -
                                                 200).replace(tzinfo=pytz.utc),
        )

        # mock a successful call to the provider to refresh tokens
        httpretty.register_uri(httpretty.POST,
                               self.provider.auto_refresh_url,
                               body=json.dumps({
                                   'access_token':
                                   'refreshed_access_token',
                                   'expires_in':
                                   3600,
                                   'refresh_token':
                                   'refreshed_refresh_token'
                               }))

        old_expiry = external_account.expires_at
        self.provider.account = external_account
        self.provider.refresh_oauth_key(force=False)
        external_account.reload()

        assert_equal(external_account.oauth_key, 'refreshed_access_token')
        assert_equal(external_account.refresh_token, 'refreshed_refresh_token')
        assert_not_equal(external_account.expires_at, old_expiry)
        assert_true(external_account.expires_at > old_expiry)
예제 #5
0
    def test_multiple_users_associated(self):
        # Create only one ExternalAccount for multiple OSF users
        #
        # For some providers (ex: GitHub), the act of completing the OAuth flow
        # revokes previously generated credentials. In addition, there is often no
        # way to know the user's id on the external service until after the flow
        # has completed.
        #
        # Having only one ExternalAccount instance per account on the external
        # service means that connecting subsequent OSF users to the same external
        # account will not invalidate the credentials used by the OSF for users
        # already associated.
        user_a = UserFactory()
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
        )
        user_a.external_accounts.add(external_account)
        user_a.save()

        user_b = UserFactory()

        # Mock the exchange of the code for an access token
        _prepare_mock_oauth2_handshake_response()

        # Fake a request context for the callback
        with self.app.app.test_request_context(
                path="/oauth/callback/mock2/",
                query_string="code=mock_code&state=mock_state"
        ) as ctx:

            # make sure the user is logged in
            authenticate(user=user_b, access_token=None, response=None)

            session.data['oauth_states'] = {
                self.provider.short_name: {
                    'state': 'mock_state',
                },
            }
            session.save()

            # do the key exchange
            self.provider.auth_callback(user=user_b)

        user_a.reload()
        user_b.reload()
        external_account.reload()

        assert_equal(
            list(user_a.external_accounts.values_list('pk', flat=True)),
            list(user_b.external_accounts.values_list('pk', flat=True)),
        )

        assert_equal(
            ExternalAccount.objects.all().count(),
            1
        )
예제 #6
0
    def test_multiple_users_associated(self):
        # Create only one ExternalAccount for multiple OSF users
        #
        # For some providers (ex: GitHub), the act of completing the OAuth flow
        # revokes previously generated credentials. In addition, there is often no
        # way to know the user's id on the external service until after the flow
        # has completed.
        #
        # Having only one ExternalAccount instance per account on the external
        # service means that connecting subsequent OSF users to the same external
        # account will not invalidate the credentials used by the OSF for users
        # already associated.
        user_a = UserFactory()
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
        )
        user_a.external_accounts.add(external_account)
        user_a.save()

        user_b = UserFactory()

        # Mock the exchange of the code for an access token
        _prepare_mock_oauth2_handshake_response()

        # Fake a request context for the callback
        with self.app.app.test_request_context(
                path="/oauth/callback/mock2/",
                query_string="code=mock_code&state=mock_state"
        ) as ctx:

            # make sure the user is logged in
            authenticate(user=user_b, access_token=None, response=None)

            session.data['oauth_states'] = {
                self.provider.short_name: {
                    'state': 'mock_state',
                },
            }
            session.save()

            # do the key exchange
            self.provider.auth_callback(user=user_b)

        user_a.reload()
        user_b.reload()
        external_account.reload()

        assert_equal(
            list(user_a.external_accounts.values_list('pk', flat=True)),
            list(user_b.external_accounts.values_list('pk', flat=True)),
        )

        assert_equal(
            ExternalAccount.find().count(),
            1
        )
예제 #7
0
class TestNoInstitutionAddonAllowView(AdminTestCase):
    def setUp(self):
        super(TestNoInstitutionAddonAllowView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonNoInstitutionFactoryOption(
        )
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.AddonAllowView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.rdm_addon_option.provider,
            'institution_id': MAGIC_INSTITUTION_ID,
            'allowed': '1',
        }

    def tearDown(self):
        super(TestNoInstitutionAddonAllowView, self).tearDown()
        if self.user.external_accounts.filter(
                pk=self.external_account.id).exists():
            self.user.external_accounts.remove(self.external_account)
        self.user.delete()
        self.rdm_addon_option.external_accounts.remove(self.external_account)
        self.rdm_addon_option.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_active = True
        self.request.user.is_registered = True
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_get(self, *args, **kwargs):
        rdm_addon_option = utils.get_rdm_addon_option(
            MAGIC_INSTITUTION_ID, self.view.kwargs['addon_name'])
        nt.assert_true(rdm_addon_option.is_allowed)
        nt.assert_equal(rdm_addon_option.provider,
                        self.view.kwargs['addon_name'])

    def test_get_disallowed(self, *args, **kwargs):
        self.view.kwargs['allowed'] = False
        self.view.get(self.request, *args, **self.view.kwargs)
        rdm_addon_option = utils.get_rdm_addon_option(
            MAGIC_INSTITUTION_ID, self.view.kwargs['addon_name'])
        nt.assert_equal(rdm_addon_option.is_allowed, False)
        nt.assert_equal(rdm_addon_option.provider,
                        self.view.kwargs['addon_name'])
        nt.assert_equal(
            self.user.external_accounts.filter(
                pk=self.external_account.id).exists(), False)
예제 #8
0
    def test_callback_wrong_user(self):
        # Reject temporary credentials not assigned to the user
        #
        # This prohibits users from associating their external account with
        # another user's OSF account by using XSS or similar attack vector to
        # complete the OAuth flow using the logged-in user but their own account
        # on the external service.
        #
        # If the OSF were to allow login via OAuth with the provider in question,
        # this would allow attackers to hijack OSF accounts with a simple script
        # injection.

        # mock a successful call to the provider to exchange temp keys for
        #   permanent keys
        responses.add(
            responses.Response(
                responses.POST,
                'http://mock1a.com/callback',
                body='oauth_token=perm_token'
                     '&oauth_token_secret=perm_secret'
                     '&oauth_callback_confirmed=true',
            )
        )

        user = UserFactory()
        account = ExternalAccountFactory(
            provider='mock1a',
            provider_name='Mock 1A',
            oauth_key='temp_key',
            oauth_secret='temp_secret'
        )
        account.save()
        # associate this ExternalAccount instance with the user
        user.external_accounts.add(account)
        user.save()

        malicious_user = UserFactory()

        # Fake a request context for the callback
        with self.app.app.test_request_context(
                path='/oauth/callback/mock1a/',
                query_string='oauth_token=temp_key&oauth_verifier=mock_verifier'
        ):
            # make sure the user is logged in
            authenticate(user=malicious_user, access_token=None, response=None)

            with assert_raises(PermissionsError):
                # do the key exchange
                self.provider.auth_callback(user=malicious_user)
예제 #9
0
    def test_callback_wrong_user(self):
        # Reject temporary credentials not assigned to the user
        #
        # This prohibits users from associating their external account with
        # another user's OSF account by using XSS or similar attack vector to
        # complete the OAuth flow using the logged-in user but their own account
        # on the external service.
        #
        # If the OSF were to allow login via OAuth with the provider in question,
        # this would allow attackers to hijack OSF accounts with a simple script
        # injection.

        # mock a successful call to the provider to exchange temp keys for
        #   permanent keys
        responses.add(
            responses.Response(
                responses.POST,
                'http://mock1a.com/callback',
                body='oauth_token=perm_token'
                     '&oauth_token_secret=perm_secret'
                     '&oauth_callback_confirmed=true',
            )
        )

        user = UserFactory()
        account = ExternalAccountFactory(
            provider="mock1a",
            provider_name='Mock 1A',
            oauth_key="temp_key",
            oauth_secret="temp_secret"
        )
        account.save()
        # associate this ExternalAccount instance with the user
        user.external_accounts.add(account)
        user.save()

        malicious_user = UserFactory()

        # Fake a request context for the callback
        with self.app.app.test_request_context(
                path="/oauth/callback/mock1a/",
                query_string="oauth_token=temp_key&oauth_verifier=mock_verifier"
        ):
            # make sure the user is logged in
            authenticate(user=malicious_user, access_token=None, response=None)

            with assert_raises(PermissionsError):
                # do the key exchange
                self.provider.auth_callback(user=malicious_user)
예제 #10
0
    def test_refresh_with_broken_provider(self):
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            expires_at=datetime.utcfromtimestamp(time.time() - 200).replace(tzinfo=pytz.utc)
        )
        self.provider.client_id = None
        self.provider.client_secret = None
        self.provider.account = external_account

        # mock a successful call to the provider to refresh tokens
        httpretty.register_uri(
            httpretty.POST,
            self.provider.auto_refresh_url,
            body=json.dumps({
                'err_msg': 'Should not be hit'
            }),
            status=500
        )

        ret = self.provider.refresh_oauth_key(force=False)
        assert_false(ret)
예제 #11
0
    def test_force_refresh_with_expired_credentials(self):
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            expires_at=datetime.utcfromtimestamp(time.time() - 10000).replace(tzinfo=pytz.utc)  # Causes has_expired_credentials to be True
        )
        self.provider.account = external_account

        # mock a failing call to the provider to refresh tokens
        responses.add(
            responses.Response(
                responses.POST,
                self.provider.auto_refresh_url,
                body=json.dumps({
                    'error': 'invalid_grant',
                }),
                status=401
            )
        )

        with assert_raises(OAuth2Error):
            self.provider.refresh_oauth_key(force=True)
예제 #12
0
    def test_refresh_with_expired_credentials(self):
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            expires_at=datetime.utcfromtimestamp(time.time() - 10000).replace(tzinfo=pytz.utc)  # Causes has_expired_credentials to be True
        )
        self.provider.account = external_account

        # mock a successful call to the provider to refresh tokens
        responses.add(
            responses.Response(
                responses.POST,
                self.provider.auto_refresh_url,
                body=json.dumps({
                    'err': 'Should not be hit'
                }),
                status=500
            )
        )

        ret = self.provider.refresh_oauth_key(force=False)
        assert_false(ret)
예제 #13
0
    def setUp(self):
        super(TestConnectView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()
        self.institution = InstitutionFactory()

        self.user.affiliated_institutions.add(self.institution)

        self.provider = MockOAuth2Provider(self.external_account)

        self.request = RequestFactory().get('/fake_path')
        add_session_to_request(self.request)
        self.view = views.ConnectView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }
예제 #14
0
    def setUp(self):
        super(TestNoInstitutionAddonForceView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonNoInstitutionFactoryOption(
        )
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.AddonForceView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.rdm_addon_option.provider,
            'institution_id': MAGIC_INSTITUTION_ID,
            'forced': '1',
        }
예제 #15
0
    def setUp(self):
        super(TestOAuthView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonOptionFactory()
        self.rdm_addon_option.provider = self.external_account.provider
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.affiliated_institutions.add(self.rdm_addon_option.institution)
        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.OAuthView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'external_account_id': self.external_account._id,
            'institution_id': self.rdm_addon_option.institution.id,
        }
예제 #16
0
    def test_does_not_need_refresh(self):
        self.provider.refresh_time = 1
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
            oauth_key='old_key',
            oauth_secret='old_secret',
            refresh_token='old_refresh',
            expires_at=datetime.utcfromtimestamp(time.time() +
                                                 200).replace(tzinfo=pytz.utc),
        )

        # mock a successful call to the provider to refresh tokens
        httpretty.register_uri(httpretty.POST,
                               self.provider.auto_refresh_url,
                               body=json.dumps(
                                   {'err_msg': 'Should not be hit'}),
                               status=500)

        # .reload() has the side effect of rounding the microsends down to 3 significant figures
        # (e.g. DT(YMDHMS, 365420) becomes DT(YMDHMS, 365000)),
        # but must occur after possible refresh to reload tokens.
        # Doing so before allows the `old_expiry == EA.expires_at` comparison to work.
        external_account.reload()
        old_expiry = external_account.expires_at
        self.provider.account = external_account
        self.provider.refresh_oauth_key(force=False)
        external_account.reload()

        assert_equal(external_account.oauth_key, 'old_key')
        assert_equal(external_account.refresh_token, 'old_refresh')
        assert_equal(external_account.expires_at, old_expiry)
예제 #17
0
def create_external_account(host='foo.bar.baz', token='doremi-abc-123'):
    """Creates external account for Dataverse with fields populated the same
    way as `dataverse_add_user_account`"""

    return ExternalAccountFactory(
        provider='dataverse',
        provider_name='Dataverse',
        display_name=host,
        oauth_key=host,
        oauth_secret=token,
        # Note: provider_id in the addon is currently the same as oauth_secret,
        # but here we will let it be generated by sequence to avoid
        # running into duplicate modular ODM entries.
    )
예제 #18
0
    def test_disconnect_with_multiple_connected(self):
        # Disconnect an account connected to multiple users from one user
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
        )
        self.user.external_accounts.add(external_account)
        self.user.save()

        other_user = UserFactory()
        other_user.external_accounts.add(external_account)
        other_user.save()

        response = self.app.delete(
            api_url_for('oauth_disconnect',
                        external_account_id=external_account._id),
            auth=self.user.auth
        )

        # Request succeeded
        assert_equal(
            response.status_code,
            http.OK,
        )

        self.user.reload()

        # External account has been disassociated with the user
        assert_not_in(
            external_account,
            self.user.external_accounts.all(),
        )

        # External account is still in the database
        assert_equal(ExternalAccount.find().count(), 1)

        other_user.reload()

        # External account is still associated with the other user
        assert_in(
            external_account,
            other_user.external_accounts.all(),
        )
예제 #19
0
    def test_disconnect(self):
        # Disconnect an external account from a user
        external_account = ExternalAccountFactory(
            provider='mock2',
            provider_id='mock_provider_id',
            provider_name='Mock Provider',
        )
        self.user.external_accounts.add(external_account)
        self.user.save()

        # If the external account isn't attached, this test has no meaning
        assert_equal(ExternalAccount.find().count(), 1)
        assert_in(
            external_account,
            self.user.external_accounts.all(),
        )

        response = self.app.delete(
            api_url_for('oauth_disconnect',
                        external_account_id=external_account._id),
            auth=self.user.auth
        )

        # Request succeeded
        assert_equal(
            response.status_code,
            http.OK,
        )

        self.user.reload()
        # external_account.reload()

        # External account has been disassociated with the user
        assert_not_in(
            external_account,
            self.user.external_accounts.all(),
        )

        # External account is still in the database
        assert_equal(ExternalAccount.find().count(), 1)
예제 #20
0
class TestConnectView(AdminTestCase):
    def setUp(self):
        super(TestConnectView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()
        self.institution = InstitutionFactory()

        self.user.affiliated_institutions.add(self.institution)

        self.provider = MockOAuth2Provider(self.external_account)

        self.request = RequestFactory().get('/fake_path')
        add_session_to_request(self.request)
        self.view = views.ConnectView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }

    def tearDown(self):
        super(TestConnectView, self).tearDown()
        self.user.affiliated_institutions.remove(self.institution)
        self.user.delete()
        self.institution.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_affiliated_institution_user_login(self):
        """test user unaffiliated institution login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        self.view.kwargs = {'institution_id': self.institution.id + 1}
        nt.assert_equal(self.view.test_func(), False)

    def test_get(self, *args, **kwargs):
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        res = self.view.get(self.request, *args, **self.view.kwargs)
        nt.assert_equal(res.status_code, 302)
예제 #21
0
class TestCallbackView(AdminTestCase):
    def setUp(self):
        super(TestCallbackView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()
        self.institution = InstitutionFactory()

        self.provider = MockOAuth2Provider(self.external_account)

        self.user.affiliated_institutions.add(self.institution)

        app = flask.Flask(__name__)
        make_url_map(app)
        app.config['SECRET_KEY'] = 'aaaaa'
        self.ctx = app.test_request_context()
        self.ctx.push()

        self.request = RequestFactory().get('/fake_path')
        add_session_to_request(self.request)
        self.view0 = views.ConnectView()
        self.view0 = setup_user_view(self.view0, self.request, user=self.user)
        self.view0.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }

        self.view = views.CallbackView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }

    def tearDown(self):
        super(TestCallbackView, self).tearDown()
        self.user.affiliated_institutions.remove(self.institution)
        self.user.delete()
        self.institution.delete()
        self.external_account.delete()
        try:
            self.ctx.pop()
        except AssertionError:
            pass

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)
예제 #22
0
class TestAddonForceView(AdminTestCase):
    def setUp(self):
        super(TestAddonForceView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonOptionFactory()
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.affiliated_institutions.add(
            self.rdm_addon_option.institution)
        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.AddonForceView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.rdm_addon_option.provider,
            'institution_id': self.rdm_addon_option.institution.id,
            'forced': '1',
        }

    def tearDown(self):
        super(TestAddonForceView, self).tearDown()
        institution = self.rdm_addon_option.institution
        self.user.affiliated_institutions.remove(institution)
        if self.user.external_accounts.filter(
                pk=self.external_account.id).exists():
            self.user.external_accounts.remove(self.external_account)
        self.user.delete()
        self.rdm_addon_option.external_accounts.remove(self.external_account)
        self.rdm_addon_option.delete()
        institution.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_affiliated_institution_user_login(self):
        """test user unaffiliated institution login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        self.view.kwargs = {
            'institution_id': self.rdm_addon_option.institution.id + 1
        }
        nt.assert_equal(self.view.test_func(), False)

    def test_get(self, *args, **kwargs):
        self.view.get(self.request, *args, **self.view.kwargs)
        rdm_addon_option = utils.get_rdm_addon_option(
            self.rdm_addon_option.institution.id,
            self.view.kwargs['addon_name'])
        nt.assert_true(rdm_addon_option.is_forced)
        nt.assert_equal(rdm_addon_option.provider,
                        self.view.kwargs['addon_name'])

    def test_get_not_forced(self, *args, **kwargs):
        self.view.kwargs['forced'] = False
        self.view.get(self.request, *args, **self.view.kwargs)
        rdm_addon_option = utils.get_rdm_addon_option(
            self.rdm_addon_option.institution.id,
            self.view.kwargs['addon_name'])
        nt.assert_equal(rdm_addon_option.is_forced, False)
        nt.assert_equal(rdm_addon_option.provider,
                        self.view.kwargs['addon_name'])
        nt.assert_true(
            self.user.external_accounts.filter(
                pk=self.external_account.id).exists())
예제 #23
0
class TestAccountsView(AdminTestCase):
    def setUp(self):
        super(TestAccountsView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonOptionFactory()
        self.rdm_addon_option.provider = self.external_account.provider
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.affiliated_institutions.add(self.rdm_addon_option.institution)
        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.AccountsView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.rdm_addon_option.institution.id,
        }

    def tearDown(self):
        super(TestAccountsView, self).tearDown()
        institution = self.rdm_addon_option.institution
        self.user.affiliated_institutions.remove(institution)
        if self.user.external_accounts.filter(pk=self.external_account.id).exists():
            self.user.external_accounts.remove(self.external_account)
        self.user.delete()
        if self.rdm_addon_option.external_accounts.filter(pk=self.external_account.id).exists():
            self.rdm_addon_option.external_accounts.remove(self.external_account)
        self.rdm_addon_option.delete()
        institution.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_affiliated_institution_user_login(self):
        """test user unaffiliated institution login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        self.view.kwargs = {'institution_id': self.rdm_addon_option.institution.id + 1}
        nt.assert_equal(self.view.test_func(), False)

    def test_get(self, *args, **kwargs):
        res = self.view.get(self.request, *args, **self.view.kwargs)
        nt.assert_equal(res.status_code, 200)
        content = json.loads(res.content)
        nt.assert_equal(len(content['accounts']), 1)

    def test_post_empty(self, *args, **kwargs):
        self.request = RequestFactory().post(
            '/fake',
            data=json.dumps({}),
            content_type='application/json'
        )
        self.view.kwargs['addon_name'] = 'dummy'
        res = self.view.post(self.request, *args, **self.view.kwargs)
        nt.assert_equal(res.status_code, 400)

    def test_post_fake_s3_account(self, *args, **kwargs):
        self.request = RequestFactory().post(
            '/fake',
            data=json.dumps({'access_key': 'aaa', 'secret_key': 'bbb'}),
            content_type='application/json'
        )
        self.view.kwargs['addon_name'] = 's3'
        res = self.view.post(self.request, *args, **self.view.kwargs)
        nt.assert_equal(res.status_code, 400)
예제 #24
0
class TestOAuthView(AdminTestCase):
    def setUp(self):
        super(TestOAuthView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonOptionFactory()
        self.rdm_addon_option.provider = self.external_account.provider
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.affiliated_institutions.add(self.rdm_addon_option.institution)
        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.OAuthView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'external_account_id': self.external_account._id,
            'institution_id': self.rdm_addon_option.institution.id,
        }

    def tearDown(self):
        super(TestOAuthView, self).tearDown()
        institution = self.rdm_addon_option.institution
        self.user.affiliated_institutions.remove(institution)
        if self.user.external_accounts.filter(pk=self.external_account.id).exists():
            self.user.external_accounts.remove(self.external_account)
        self.user.delete()
        if self.rdm_addon_option.external_accounts.filter(pk=self.external_account.id).exists():
            self.rdm_addon_option.external_accounts.remove(self.external_account)
        self.rdm_addon_option.delete()
        institution.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login """
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_affiliated_institution_user_login(self):
        """test unaffiliated institution user login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        self.view.kwargs['institution_id'] = self.rdm_addon_option.institution.id + 1
        nt.assert_equal(self.view.test_func(), False)
        self.view.kwargs['institution_id'] = self.rdm_addon_option.institution.id

    def test_delete(self, *args, **kwargs):
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_equal(self.user.external_accounts.count(), 1)
        nt.assert_equal(self.rdm_addon_option.external_accounts.count(), 1)
        self.view.delete(self.request, *args, **self.view.kwargs)
        nt.assert_equal(self.user.external_accounts.count(), 0)
        nt.assert_equal(self.rdm_addon_option.external_accounts.count(), 0)

    def test_delete_dummy(self, *args, **kwargs):
        self.view.kwargs['external_account_id'] = self.external_account._id + 'dummy'
        with self.assertRaises(Http404):
            self.view.delete(self.request, *args, **self.view.kwargs)
        self.view.kwargs['external_account_id'] = self.external_account._id

    def test_delete_empty(self, *args, **kwargs):
        self.rdm_addon_option.external_accounts.remove(self.external_account)
        with self.assertRaises(Http404):
            self.view.delete(self.request, *args, **self.view.kwargs)