Ejemplo n.º 1
0
    def test_specify_scopes(self):
        """
        Validates whether requested scopes are assigned
        """
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        time.sleep(180)
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        self.assertIn('access_token', json.loads(response.content))
        access_token = json.loads(response.content)['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertListEqual(sorted(response_content['roles']),
                             ['manage', 'read', 'write'])

        time.sleep(180)
        data['scope'] = 'read write'
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        access_token = response_content['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('roles', response_content)
        self.assertListEqual(sorted(response_content['roles']),
                             ['read', 'write'])

        time.sleep(180)
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******',
            'scope': 'read write manage'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_scope', HttpBadRequestException)
Ejemplo n.º 2
0
    def test_grandtype_headers(self):
        """
        Validates whether not sending a grant_type will fail the call and the grant_type is checked
        """
        from api.oauth2.tokenview import OAuth2TokenView

        time.sleep(180)
        request = self.factory.post('/', HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_request', HttpBadRequestException)

        time.sleep(180)
        data = {'grant_type': 'foobar'}
        request = self.factory.post('/', HTTP_X_REAL_IP='127.0.0.1', data=data)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'unsupported_grant_type', HttpBadRequestException)
Ejemplo n.º 3
0
    def test_grandtype_headers(self):
        """
        Validates whether not sending a grant_type will fail the call and the grant_type is checked
        """
        from api.oauth2.tokenview import OAuth2TokenView

        time.sleep(180)
        request = self.factory.post('/', HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_request', HttpBadRequestException)

        time.sleep(180)
        data = {'grant_type': 'foobar'}
        request = self.factory.post('/', HTTP_X_REAL_IP='127.0.0.1', data=data)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'unsupported_grant_type', HttpBadRequestException)
Ejemplo n.º 4
0
    def test_specify_scopes(self):
        """
        Validates whether requested scopes are assigned
        """
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        time.sleep(180)
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        self.assertIn('access_token', json.loads(response.content))
        access_token = json.loads(response.content)['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertListEqual(sorted(response_content['roles']), ['manage', 'read', 'write'])

        time.sleep(180)
        data['scope'] = 'read write'
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        access_token = response_content['access_token']

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('roles', response_content)
        self.assertListEqual(sorted(response_content['roles']), ['read', 'write'])

        time.sleep(180)
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******',
                'scope': 'read write manage'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_scope', HttpBadRequestException)
Ejemplo n.º 5
0
    def test_authentication_backend(self):
        """
        Validates the Authentication backend
        """
        from django.contrib.auth.models import User as DUser
        from api.oauth2.tokenview import OAuth2TokenView
        from api.oauth2.backend import OAuth2Backend

        time.sleep(180)
        backend = OAuth2Backend()
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        access_token = response_content['access_token']
        request = self.factory.get('/')
        response = backend.authenticate(request)
        self.assertIsNone(response)

        time.sleep(180)
        header = 'Bearer foobar'
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        with self.assertRaises(HttpUnauthorizedException) as context:
            backend.authenticate(request)
        self.assertEqual(context.exception.status_code, 401)
        self.assertEqual(str(context.exception.error), 'invalid_token')

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        user, extra = backend.authenticate(request)
        self.assertIsInstance(user, DUser)
        self.assertIsNone(extra)
        self.assertEqual(request.token.access_token, access_token)
        self.assertEqual(request.client.user.username, 'admin')

        time.sleep(180)
        user = UserList.get_user_by_username('admin')
        user.is_active = False
        user.save()
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        with self.assertRaises(HttpUnauthorizedException) as context:
            backend.authenticate(request)
        self.assertEqual(context.exception.status_code, 401)
        self.assertEqual(str(context.exception.error), 'inactive_user')
        user.is_active = True
        user.save()

        time.sleep(int(response_content['expires_in']))
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        with self.assertRaises(HttpUnauthorizedException) as context:
            backend.authenticate(request)
        self.assertEqual(context.exception.status_code, 401)
        self.assertEqual(str(context.exception.error), 'token_expired')
Ejemplo n.º 6
0
    def test_authentication_backend(self):
        """
        Validates the Authentication backend
        """
        from django.contrib.auth.models import User as DUser
        from api.oauth2.tokenview import OAuth2TokenView
        from api.oauth2.backend import OAuth2Backend

        time.sleep(180)
        backend = OAuth2Backend()
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        access_token = response_content['access_token']
        request = self.factory.get('/')
        response = backend.authenticate(request)
        self.assertIsNone(response)

        time.sleep(180)
        header = 'Bearer foobar'
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        with self.assertRaises(HttpUnauthorizedException) as context:
            backend.authenticate(request)
        self.assertEqual(context.exception.status_code, 401)
        self.assertEqual(str(context.exception.error), 'invalid_token')

        time.sleep(180)
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        user, extra = backend.authenticate(request)
        self.assertIsInstance(user, DUser)
        self.assertIsNone(extra)
        self.assertEqual(request.token.access_token, access_token)
        self.assertEqual(request.client.user.username, 'admin')

        time.sleep(180)
        user = UserList.get_user_by_username('admin')
        user.is_active = False
        user.save()
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        with self.assertRaises(HttpUnauthorizedException) as context:
            backend.authenticate(request)
        self.assertEqual(context.exception.status_code, 401)
        self.assertEqual(str(context.exception.error), 'inactive_user')
        user.is_active = True
        user.save()

        time.sleep(int(response_content['expires_in']))
        request = self.factory.get('/', HTTP_AUTHORIZATION=header)
        with self.assertRaises(HttpUnauthorizedException) as context:
            backend.authenticate(request)
        self.assertEqual(context.exception.status_code, 401)
        self.assertEqual(str(context.exception.error), 'token_expired')
Ejemplo n.º 7
0
    def test_resource_owner_password_credentials(self):
        """
        Validates the Resource Owner Password Credentials
        """
        from api.oauth2.tokenview import OAuth2TokenView

        time.sleep(180)
        data = {'grant_type': 'password'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_request', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******', 'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_client', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******', 'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'inactive_user', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******', 'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'unauthorized_client', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******', 'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        result = {
            'access_token': response_content['access_token'],
            'token_type': 'bearer',
            'expires_in': 86400
        }
        self.assertDictEqual(response_content, result)
Ejemplo n.º 8
0
    def test_resource_owner_password_credentials(self):
        """
        Validates the Resource Owner Password Credentials
        """
        from api.oauth2.tokenview import OAuth2TokenView

        time.sleep(180)
        data = {'grant_type': 'password'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_request', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******',
                     'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_client', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******',
                     'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'inactive_user', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******',
                     'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'unauthorized_client', HttpBadRequestException)

        time.sleep(180)
        data.update({'username': '******',
                     'password': '******'})
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        result = {'access_token': response_content['access_token'],
                  'token_type': 'bearer',
                  'expires_in': 86400}
        self.assertDictEqual(response_content, result)
Ejemplo n.º 9
0
    def test_client_credentials(self):
        """
        Validates the Client Credentials
        """
        from api.oauth2.tokenview import OAuth2TokenView

        time.sleep(180)
        data = {'grant_type': 'client_credentials'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'missing_header', HttpBadRequestException)

        time.sleep(180)
        header = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format('foo', 'bar')))
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.2', HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_client', HttpBadRequestException)

        time.sleep(180)
        admin_na = UserList.get_user_by_username('admin_na')
        admin_na_client = Client()
        admin_na_client.ovs_type = 'USER'
        admin_na_client.grant_type = 'PASSWORD'
        admin_na_client.client_secret = OAuth2Toolbox.create_hash(64)
        admin_na_client.user = admin_na
        admin_na_client.save()
        header = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(admin_na_client.guid, admin_na_client.client_secret)))
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.3', HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_grant', HttpBadRequestException)

        time.sleep(180)
        admin_na_client.grant_type = 'CLIENT_CREDENTIALS'
        admin_na_client.save()
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.4', HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'inactive_user', HttpBadRequestException)

        time.sleep(180)
        admin = UserList.get_user_by_username('admin')
        admin_client = Client()
        admin_client.ovs_type = 'USER'
        admin_client.grant_type = 'CLIENT_CREDENTIALS'
        admin_client.client_secret = OAuth2Toolbox.create_hash(64)
        admin_client.user = admin
        admin_client.save()
        header = 'Basic {0}'.format(base64.encodestring('{0}:foobar'.format(admin_client.guid)))
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.5', HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400, 'invalid_client', HttpBadRequestException)

        time.sleep(180)
        header = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(admin_client.guid, admin_client.client_secret)))
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.6', HTTP_AUTHORIZATION=header)
        response = OAuth2TokenView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        result = {'access_token': response_content['access_token'],
                  'token_type': 'bearer',
                  'expires_in': 3600}
        self.assertDictEqual(response_content, result)
Ejemplo n.º 10
0
    def test_metadata(self):
        """
        Validates the authentication related information at the API root's metadata.
        - The 'roles' key is already checked in the Scope-related tests
        """
        from ovs.dal.lists.bearertokenlist import BearerTokenList
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        def _raise_exception(argument):
            _ = argument
            raise RuntimeError('foobar')

        result_data = {
            'authenticated': False,
            'authentication_state': None,
            'username': None,
            'userguid': None
        }

        time.sleep(180)
        data = {
            'grant_type': 'password',
            'username': '******',
            'password': '******'
        }
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('expires_in', response_content)
        self.assertIn('access_token', response_content)

        time.sleep(180)
        expiry = int(response_content['expires_in'])
        access_token = response_content['access_token']
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1')
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'unauthenticated'}.items()),
            response_content)

        time.sleep(180)
        header = 'Basic foobar'
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'invalid_authorization_type'
                  }.items()), response_content)

        time.sleep(180)
        header = 'Bearer foobar'
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'invalid_token'}.items()),
            response_content)

        time.sleep(180)
        user = UserList.get_user_by_username('admin')
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(
                result_data.items() + {
                    'authenticated': True,
                    'authentication_state': 'authenticated',
                    'username': user.username,
                    'userguid': user.guid
                }.items()), response_content)

        time.sleep(180)
        user.is_active = False
        user.save()
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'inactive_user'}.items()),
            response_content)
        user.is_active = True
        user.save()

        time.sleep(180)
        original_method = BearerTokenList.get_by_access_token
        BearerTokenList.get_by_access_token = staticmethod(_raise_exception)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'unexpected_exception'}.items()),
            response_content)

        time.sleep(180)
        BearerTokenList.get_by_access_token = staticmethod(original_method)
        time.sleep(expiry)
        request = self.factory.get('/',
                                   HTTP_X_REAL_IP='127.0.0.1',
                                   HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(
            dict(result_data.items() +
                 {'authentication_state': 'token_expired'}.items()),
            response_content)
Ejemplo n.º 11
0
    def test_client_credentials(self):
        """
        Validates the Client Credentials
        """
        from api.oauth2.tokenview import OAuth2TokenView

        time.sleep(180)
        data = {'grant_type': 'client_credentials'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'missing_header', HttpBadRequestException)

        time.sleep(180)
        header = 'Basic {0}'.format(
            base64.encodestring('{0}:{1}'.format('foo', 'bar')))
        request = self.factory.post('/',
                                    data=data,
                                    HTTP_X_REAL_IP='127.0.0.2',
                                    HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_client', HttpBadRequestException)

        time.sleep(180)
        admin_na = UserList.get_user_by_username('admin_na')
        admin_na_client = Client()
        admin_na_client.ovs_type = 'USER'
        admin_na_client.grant_type = 'PASSWORD'
        admin_na_client.client_secret = OAuth2Toolbox.create_hash(64)
        admin_na_client.user = admin_na
        admin_na_client.save()
        header = 'Basic {0}'.format(
            base64.encodestring('{0}:{1}'.format(
                admin_na_client.guid, admin_na_client.client_secret)))
        request = self.factory.post('/',
                                    data=data,
                                    HTTP_X_REAL_IP='127.0.0.3',
                                    HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_grant', HttpBadRequestException)

        time.sleep(180)
        admin_na_client.grant_type = 'CLIENT_CREDENTIALS'
        admin_na_client.save()
        request = self.factory.post('/',
                                    data=data,
                                    HTTP_X_REAL_IP='127.0.0.4',
                                    HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'inactive_user', HttpBadRequestException)

        time.sleep(180)
        admin = UserList.get_user_by_username('admin')
        admin_client = Client()
        admin_client.ovs_type = 'USER'
        admin_client.grant_type = 'CLIENT_CREDENTIALS'
        admin_client.client_secret = OAuth2Toolbox.create_hash(64)
        admin_client.user = admin
        admin_client.save()
        header = 'Basic {0}'.format(
            base64.encodestring('{0}:foobar'.format(admin_client.guid)))
        request = self.factory.post('/',
                                    data=data,
                                    HTTP_X_REAL_IP='127.0.0.5',
                                    HTTP_AUTHORIZATION=header)
        self._assert_failure(OAuth2TokenView.as_view(), request, 400,
                             'invalid_client', HttpBadRequestException)

        time.sleep(180)
        header = 'Basic {0}'.format(
            base64.encodestring('{0}:{1}'.format(admin_client.guid,
                                                 admin_client.client_secret)))
        request = self.factory.post('/',
                                    data=data,
                                    HTTP_X_REAL_IP='127.0.0.6',
                                    HTTP_AUTHORIZATION=header)
        response = OAuth2TokenView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(response.content)
        self.assertIn('access_token', response_content)
        result = {
            'access_token': response_content['access_token'],
            'token_type': 'bearer',
            'expires_in': 3600
        }
        self.assertDictEqual(response_content, result)
Ejemplo n.º 12
0
def build_router_urls():
    """
    Creates a router instance to generate API urls for Customer and Internal API
    """
    routes = []
    path = '/'.join([os.path.dirname(__file__), 'backend', 'views'])
    for filename in os.listdir(path):
        if os.path.isfile('/'.join([path, filename])) and filename.endswith('.py'):
            name = filename.replace('.py', '')
            module = imp.load_source(name, '/'.join([path, filename]))
            for member in inspect.getmembers(module):
                if inspect.isclass(member[1]) \
                        and member[1].__module__ == name \
                        and 'ViewSet' in [base.__name__ for base in member[1].__bases__]:
                    routes.append({'prefix': member[1].prefix,
                                   'viewset': member[1],
                                   'base_name': member[1].base_name})
    router = SimpleRouter()
    for route in routes:
        router.register(**route)
    return router.urls

urlpatterns = patterns('',
                       url(r'^oauth2/token/', OAuth2TokenView.as_view()),
                       url(r'^oauth2/redirect/', OAuth2RedirectView.as_view()),
                       url(r'^relay/', relay),
                       url(r'^swagger.json', OpenAPIView.as_view()),
                       url(r'^$', MetadataView.as_view()),
                       url(r'', include(build_router_urls())))
Ejemplo n.º 13
0
    """
    routes = []
    path = '/'.join([os.path.dirname(__file__), 'backend', 'views'])
    for filename in os.listdir(path):
        if os.path.isfile('/'.join([path, filename
                                    ])) and filename.endswith('.py'):
            name = filename.replace('.py', '')
            mod = imp.load_source(name, '/'.join([path, filename]))
            for member_name, member in inspect.getmembers(
                    mod, predicate=inspect.isclass):
                if member.__module__ == name and 'ViewSet' in [
                        base.__name__ for base in member.__bases__
                ]:
                    routes.append({
                        'prefix': member.prefix,
                        'viewset': member,
                        'base_name': member.base_name
                    })
    router = OVSRouter()
    for route in routes:
        router.register(**route)
    return router.urls


urlpatterns = patterns('', url(r'^oauth2/token/', OAuth2TokenView.as_view()),
                       url(r'^oauth2/redirect/', OAuth2RedirectView.as_view()),
                       url(r'^relay/', relay),
                       url(r'^swagger.json', OpenAPIView.as_view()),
                       url(r'^$', MetadataView.as_view()),
                       url(r'', include(build_router_urls())))
Ejemplo n.º 14
0
    def test_metadata(self):
        """
        Validates the authentication related information at the API root's metadata.
        - The 'roles' key is already checked in the Scope-related tests
        """
        from ovs.dal.lists.bearertokenlist import BearerTokenList
        from api.oauth2.tokenview import OAuth2TokenView
        from api.view import MetadataView

        def _raise_exception(argument):
            _ = argument
            raise RuntimeError('foobar')

        result_data = {'authenticated': False,
                       'authentication_state': None,
                       'username': None,
                       'userguid': None}

        time.sleep(180)
        data = {'grant_type': 'password',
                'username': '******',
                'password': '******'}
        request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1')
        response = OAuth2TokenView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertIn('expires_in', response_content)
        self.assertIn('access_token', response_content)

        time.sleep(180)
        expiry = int(response_content['expires_in'])
        access_token = response_content['access_token']
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1')
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'unauthenticated'}.items()), response_content)

        time.sleep(180)
        header = 'Basic foobar'
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'invalid_authorization_type'}.items()), response_content)

        time.sleep(180)
        header = 'Bearer foobar'
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'invalid_token'}.items()), response_content)

        time.sleep(180)
        user = UserList.get_user_by_username('admin')
        header = 'Bearer {0}'.format(access_token)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authenticated': True,
                                                                  'authentication_state': 'authenticated',
                                                                  'username': user.username,
                                                                  'userguid': user.guid}.items()), response_content)

        time.sleep(180)
        user.is_active = False
        user.save()
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'inactive_user'}.items()), response_content)
        user.is_active = True
        user.save()

        time.sleep(180)
        original_method = BearerTokenList.get_by_access_token
        BearerTokenList.get_by_access_token = staticmethod(_raise_exception)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'unexpected_exception'}.items()), response_content)

        time.sleep(180)
        BearerTokenList.get_by_access_token = staticmethod(original_method)
        time.sleep(expiry)
        request = self.factory.get('/', HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header)
        response = MetadataView.as_view()(request)
        response_content = json.loads(response.content)
        self.assertDictContainsSubset(dict(result_data.items() + {'authentication_state': 'token_expired'}.items()), response_content)