def test_specify_scopes(self): """ Validates whether requested scopes are assigned """ from oauth2.tokenview import OAuth2TokenView from view import MetadataView data = {'grant_type': 'password', 'username': '******', 'password': '******'} request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) access_token = json.loads(response.content)['access_token'] header = 'Bearer {0}'.format(access_token) request = Authentication.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(response_content['roles'], ['read', 'write', 'manage']) data['scope'] = 'read write' request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) access_token = json.loads(response.content)['access_token'] header = 'Bearer {0}'.format(access_token) request = Authentication.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']), ['read', 'write']) data = {'grant_type': 'password', 'username': '******', 'password': '******', 'scope': 'read write manage'} request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_scope'}))
def test_resource_owner_password_credentials(self): """ Validates the Resource Owner Password Credentials """ from oauth2.tokenview import OAuth2TokenView data = {'grant_type': 'password'} request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because there's no username & password self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_request'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because the password is wrong self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_client'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because the user is inactive self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'inactive_user'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because there's no password grant self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'unauthorized_client'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Succeeds 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)
def test_client_credentials(self): """ Validates the Client Credentials """ from oauth2.tokenview import OAuth2TokenView data = {'grant_type': 'client_credentials'} request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because the HTTP_AUTHORIZATION header is missing self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'missing_header'})) header = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format('foo', 'bar'))) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header) response = OAuth2TokenView.as_view()(request) # Fails because there is no such client self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_client'})) 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 = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header) response = OAuth2TokenView.as_view()(request) # Fails because the grant is of type Resource Owner Password Credentials self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_grant'})) admin_na_client.grant_type = 'CLIENT_CREDENTIALS' admin_na_client.save() request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header) response = OAuth2TokenView.as_view()(request) # Fails because the grant is of type Resource Owner Password Credentials self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'inactive_user'})) 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}:{1}'.format(admin_client.guid, admin_client.client_secret))) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1', HTTP_AUTHORIZATION=header) response = OAuth2TokenView.as_view()(request) # Succeeds 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)
def test_specify_scopes(self): """ Validates whether requested scopes are assigned """ from oauth2.tokenview import OAuth2TokenView from view import MetadataView data = { 'grant_type': 'password', 'username': '******', 'password': '******' } request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) access_token = json.loads(response.content)['access_token'] header = 'Bearer {0}'.format(access_token) request = Authentication.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(response_content['roles'], ['read', 'write', 'manage']) data['scope'] = 'read write' request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) access_token = json.loads(response.content)['access_token'] header = 'Bearer {0}'.format(access_token) request = Authentication.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']), ['read', 'write']) data = { 'grant_type': 'password', 'username': '******', 'password': '******', 'scope': 'read write manage' } request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_scope'}))
def test_grandtype_headers(self): """ Validates whether not sending a grant_type will fail the call and the grant_type is checked """ from oauth2.tokenview import OAuth2TokenView request = Authentication.factory.post('/', HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_request'})) data = {'grant_type': 'foobar'} request = Authentication.factory.post('/', HTTP_X_REAL_IP='127.0.0.1', data=data) response = OAuth2TokenView.as_view()(request) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'unsupported_grant_type'}))
def test_grandtype_headers(self): """ Validates whether not sending a grant_type will fail the call and the grant_type is checked """ from oauth2.tokenview import OAuth2TokenView request = self.factory.post('/', HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_request'})) data = {'grant_type': 'foobar'} request = self.factory.post('/', HTTP_X_REAL_IP='127.0.0.1', data=data) response = OAuth2TokenView.as_view()(request) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'unsupported_grant_type'}))
def test_resource_owner_password_credentials(self): """ Validates the Resource Owner Password Credentials """ from oauth2.tokenview import OAuth2TokenView data = {'grant_type': 'password'} request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because there's no username & password self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_request'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because the password is wrong self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_client'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because the user is inactive self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'inactive_user'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because there's no password grant self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'unauthorized_client'})) data.update({'username': '******', 'password': '******'}) request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Succeeds 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)
def test_authentication_backend(self): """ Validates the Authentication backend """ from django.contrib.auth.models import User as DUser from oauth2.tokenview import OAuth2TokenView from oauth2.backend import OAuth2Backend backend = OAuth2Backend() data = { 'grant_type': 'password', 'username': '******', 'password': '******' } request = Authentication.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 = Authentication.factory.get('/') response = backend.authenticate(request) self.assertIsNone(response) header = 'Bearer foobar' request = Authentication.factory.get('/', HTTP_AUTHORIZATION=header) with self.assertRaises(AuthenticationFailed) as context: backend.authenticate(request) self.assertEqual(context.exception.status_code, 401) self.assertEqual(str(context.exception.detail), 'invalid_token') header = 'Bearer {0}'.format(access_token) request = Authentication.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') user = UserList.get_user_by_username('admin') user.is_active = False user.save() request = Authentication.factory.get('/', HTTP_AUTHORIZATION=header) with self.assertRaises(AuthenticationFailed) as context: backend.authenticate(request) self.assertEqual(context.exception.status_code, 401) self.assertEqual(str(context.exception.detail), 'inactive_user') time.sleep(int(response_content['expires_in'])) request = Authentication.factory.get('/', HTTP_AUTHORIZATION=header) with self.assertRaises(AuthenticationFailed) as context: backend.authenticate(request) self.assertEqual(context.exception.status_code, 401) self.assertEqual(str(context.exception.detail), 'token_expired')
def test_authentication_backend(self): """ Validates the Authentication backend """ from django.contrib.auth.models import User as DUser from oauth2.tokenview import OAuth2TokenView from oauth2.backend import OAuth2Backend backend = OAuth2Backend() data = {'grant_type': 'password', 'username': '******', 'password': '******'} request = Authentication.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 = Authentication.factory.get('/') response = backend.authenticate(request) self.assertIsNone(response) header = 'Bearer foobar' request = Authentication.factory.get('/', HTTP_AUTHORIZATION=header) with self.assertRaises(AuthenticationFailed) as context: backend.authenticate(request) self.assertEqual(context.exception.status_code, 401) self.assertEqual(str(context.exception.detail), 'invalid_token') header = 'Bearer {0}'.format(access_token) request = Authentication.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') user = UserList.get_user_by_username('admin') user.is_active = False user.save() request = Authentication.factory.get('/', HTTP_AUTHORIZATION=header) with self.assertRaises(AuthenticationFailed) as context: backend.authenticate(request) self.assertEqual(context.exception.status_code, 401) self.assertEqual(str(context.exception.detail), 'inactive_user') time.sleep(int(response_content['expires_in'])) request = Authentication.factory.get('/', HTTP_AUTHORIZATION=header) with self.assertRaises(AuthenticationFailed) as context: backend.authenticate(request) self.assertEqual(context.exception.status_code, 401) self.assertEqual(str(context.exception.detail), 'token_expired')
def build_router_urls(): """ Creates a router instance to generate API urls for Customer and Internal API """ routes = [] path = os.path.join(os.path.dirname(__file__), 'backend', 'views') for filename in os.listdir(path): if os.path.isfile(os.path.join(path, filename)) and filename.endswith('.py'): name = filename.replace('.py', '') module = imp.load_source(name, os.path.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'^$', MetadataView.as_view()), url(r'', include(build_router_urls())) )
def build_router_urls(): """ Creates a router instance to generate API urls for Customer and Internal API """ routes = [] path = os.path.join(os.path.dirname(__file__), 'backend', 'views') for filename in os.listdir(path): if os.path.isfile(os.path.join(path, filename)) and filename.endswith('.py'): name = filename.replace('.py', '') module = imp.load_source(name, os.path.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'^$', MetadataView.as_view()), url(r'', include(build_router_urls())))
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 oauth2.tokenview import OAuth2TokenView from view import MetadataView def raise_exception(argument): _ = argument raise RuntimeError('foobar') result_data = {'authenticated': False, 'authentication_state': None, 'username': None, 'userguid': None} data = {'grant_type': 'password', 'username': '******', 'password': '******'} request = Authentication.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) response_content = json.loads(response.content) expiry = int(response_content['expires_in']) access_token = response_content['access_token'] request = Authentication.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) header = 'Basic foobar' request = Authentication.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) header = 'Bearer foobar' request = Authentication.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) user = UserList.get_user_by_username('admin') header = 'Bearer {0}'.format(access_token) request = Authentication.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, 'username': user.username, 'userguid': user.guid}.items()), response_content) time.sleep(180) # Make sure to not hit the rate limit user.is_active = False user.save() request = Authentication.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) original_method = BearerTokenList.get_by_access_token BearerTokenList.get_by_access_token = staticmethod(raise_exception) request = Authentication.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) BearerTokenList.get_by_access_token = staticmethod(original_method) time.sleep(expiry) request = Authentication.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)
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 oauth2.tokenview import OAuth2TokenView from view import MetadataView def _raise_exception(argument): _ = argument raise RuntimeError('foobar') result_data = { 'authenticated': False, 'authentication_state': None, 'username': None, 'userguid': None } 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) 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) 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) 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) 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) # Make sure to not hit the rate limit 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) 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) 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)
def test_client_credentials(self): """ Validates the Client Credentials """ from oauth2.tokenview import OAuth2TokenView data = {'grant_type': 'client_credentials'} request = self.factory.post('/', data=data, HTTP_X_REAL_IP='127.0.0.1') response = OAuth2TokenView.as_view()(request) # Fails because the HTTP_AUTHORIZATION header is missing self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'missing_header'})) 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) response = OAuth2TokenView.as_view()(request) # Fails because there is no such client self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_client'})) 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) response = OAuth2TokenView.as_view()(request) # Fails because the grant is of type Resource Owner Password Credentials self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_grant'})) 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) response = OAuth2TokenView.as_view()(request) # Fails because the grant is of type Resource Owner Password Credentials self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'inactive_user'})) 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) response = OAuth2TokenView.as_view()(request) # Fails because it's an invalid secret self.assertEqual(response.status_code, 400) self.assertEqual(response.content, json.dumps({'error': 'invalid_client'})) 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) # Succeeds 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)