+ self.assertEqual(self.load_json('/api/blog'), [])
+
+
+class OAuth1Tests(ApiTest):
+ @classmethod
+ def setUpClass(cls):
+ cls.user = User.objects.create(username='test')
+ cls.user.set_password('test')
+ cls.user.save()
+ cls.consumer_secret = 'len(quote(consumer secret))>=32'
+ Consumer.objects.create(
+ key='client',
+ secret=cls.consumer_secret
+ )
+
+ @classmethod
+ def tearDownClass(cls):
+ User.objects.all().delete()
+
+ def test_create_token(self):
+ # Fetch request token.
+ base_query = ("oauth_consumer_key=client&oauth_nonce=12345678&"
+ "oauth_signature_method=HMAC-SHA1&oauth_timestamp={}&"
+ "oauth_version=1.0".format(int(time())))
+ raw = '&'.join([
+ 'GET',
+ quote('http://testserver/api/oauth/request_token/', safe=''),
+ quote(base_query, safe='')
+ ])
+ h = hmac.new(
+ (quote(self.consumer_secret) + '&').encode('latin1'),
+ raw.encode('latin1'),
+ hashlib.sha1
+ ).digest()
+ h = b64encode(h).rstrip(b'\n')
+ sign = quote(h)
+ query = "{}&oauth_signature={}".format(base_query, sign)
+ response = self.client.get('/api/oauth/request_token/?' + query)
+ request_token_data = parse_qs(response.content.decode('latin1'))
+ request_token = request_token_data['oauth_token'][0]
+ request_token_secret = request_token_data['oauth_token_secret'][0]
+
+ # Request token authorization.
+ self.client.login(username='test', password='test')
+ response = self.client.get('/api/oauth/authorize/?oauth_token=%s&oauth_callback=test://oauth.callback/' % request_token)
+ post_data = response.context['form'].initial
+
+ response = self.client.post('/api/oauth/authorize/?' + urlencode(post_data))
+ self.assertEqual(
+ response['Location'],
+ 'test://oauth.callback/?oauth_token=' + request_token
+ )
+
+ # Fetch access token.
+ base_query = ("oauth_consumer_key=client&oauth_nonce=12345678&"
+ "oauth_signature_method=HMAC-SHA1&oauth_timestamp={}&"
+ "oauth_token={}&oauth_version=1.0".format(
+ int(time()), request_token))
+ raw = '&'.join([
+ 'GET',
+ quote('http://testserver/api/oauth/access_token/', safe=''),
+ quote(base_query, safe='')
+ ])
+ h = hmac.new(
+ (quote(self.consumer_secret) + '&' +
+ quote(request_token_secret, safe='')).encode('latin1'),
+ raw.encode('latin1'),
+ hashlib.sha1
+ ).digest()
+ h = b64encode(h).rstrip(b'\n')
+ sign = quote(h)
+ query = "{}&oauth_signature={}".format(base_query, sign)
+ response = self.client.get('/api/oauth/access_token/?' + query)
+ access_token_data = parse_qs(response.content.decode('latin1'))
+ access_token = access_token_data['oauth_token'][0]
+
+ self.assertTrue(
+ Token.objects.filter(
+ key=access_token,
+ token_type=Token.ACCESS,
+ user=self.user
+ ).exists())
+
+
+class AuthorizedTests(ApiTest):
+ fixtures = ['test-books.yaml']