def obj_create(self, bundle, request=None, **kwargs): bundle.obj = Obj() bundle.obj.id = 1 code = bundle.data.get('code') redirect_uri = bundle.data.get('redirectUri', '') if not code: self.create_response( bundle.request, bundle, response_class=BadRequest('code is required')) logger.error('code is required') # TODO: Add catch errors token_response = FacebookAuthorization.convert_code( code, redirect_uri=redirect_uri) # TODO: Add access_token to cache access_token = token_response['access_token'] action, user = connect_user(bundle.request, access_token=access_token) from events.tasks import store_fb_events, refresh_fb_events store_fb_events.delay(user) refresh_fb_events.delay(user) payload = jwt_payload_handler(user) payload['access_token'] = user.access_token bundle.obj.token = jwt_encode_handler(payload) # TODO: clean up response return bundle
def get_credentials(self, user=None): if user is None: user = self.user else: user = user jwt = jwt_encode_handler({ 'user_id': user.id, 'username': user.username }) return '%s %s' % (settings.JWT_AUTH_HEADER_PREFIX, jwt)
def test_refresh(self): """ Ensure JWT refresh view using JSON POST works. """ data = {"token": utils.jwt_encode_handler(self.payload)} response = self.client.post(self.refresh_auth_token_url, data, content_type="application/json") decoded_payload = utils.jwt_decode_handler(response.json()["token"]) self.assertEqual(response.status_code, 200) self.assertEqual(decoded_payload["username"], self.username)
def test_no_orig_iat(self): """ Ensure JWT refresh view using JSON POST fails if no orig_iat is present on the payload. """ self.payload.pop("orig_iat") data = {"token": utils.jwt_encode_handler(self.payload)} response = self.client.post(self.refresh_auth_token_url, data, content_type="application/json") self.assertEqual(response.status_code, 400)
def test_jwt_refresh_json_no_orig_iat(self): """ Ensure JWT refresh view using JSON POST fails if no orig_iat is present on the payload. """ self.payload.pop('orig_iat') data = {'token': utils.jwt_encode_handler(self.payload)} response = self.client.post('/refresh-token/', json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, 400)
def test_passing_jwt_auth(self): """ Ensure getting form over JWT auth with correct credentials passes and does not require CSRF """ payload = utils.jwt_payload_handler(self.user) token = utils.jwt_encode_handler(payload) auth = "Bearer {0}".format(token) response = self.client.get(self.protected_url, content_type="application/json", HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()["username"], self.username)
def test_inactive_user(self): """ Ensure JWT refresh view using JSON POST fails if the user is inactive """ self.user.is_active = False self.user.save() data = {"token": utils.jwt_encode_handler(self.payload)} response = self.client.post(self.refresh_auth_token_url, data, content_type="application/json") self.assertEqual(response.status_code, 400)
def test_jwt_refresh_json(self): """ Ensure JWT refresh view using JSON POST works. """ data = {'token': utils.jwt_encode_handler(self.payload)} response = self.client.post('/refresh-token/', json.dumps(data), content_type='application/json') response_content = json.loads(smart_text(response.content)) decoded_payload = utils.jwt_decode_handler(response_content['token']) self.assertEqual(response.status_code, 200) self.assertEqual(decoded_payload['username'], self.username)
def test_expired_token_failing_jwt_auth(self): """ Ensure getting over JWT auth with expired token fails """ payload = utils.jwt_payload_handler(self.user) payload["exp"] = 1 token = utils.jwt_encode_handler(payload) auth = "Bearer {0}".format(token) response = self.client.get(self.protected_url, content_type="application/json", HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 401) self.assertEqual(response["WWW-Authenticate"], 'JWT realm="api"') expected_error = ["Signature has expired."] self.assertEqual(response.json()["errors"], expected_error)
def test_jwt_refresh_json_inactive_user(self): """ Ensure JWT refresh view using JSON POST fails if the user is inactive """ self.user.is_active = False self.user.save() data = {'token': utils.jwt_encode_handler(self.payload)} response = self.client.post('/refresh-token/', json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, 400)
def test_post_json_passing_jwt_auth(self): """ Ensure POSTing form over JWT auth with correct credentials passes and does not require CSRF """ payload = utils.jwt_payload_handler(self.user) token = utils.jwt_encode_handler(payload) auth = 'Bearer {0}'.format(token) response = self.client.post('/jwt/', content_type='application/json', HTTP_AUTHORIZATION=auth) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 200) self.assertEqual(response_content['username'], self.username)
def test_refresh_with_expired_token(self): """ Ensure JWT refresh view using JSON POST fails if the refresh has expired """ # We make sure that the refresh token is not in the window # allowed by the expiration delta. This is much easier using # freezegun. orig_iat = (datetime.utcfromtimestamp(self.payload["orig_iat"]) - settings.JWT_REFRESH_EXPIRATION_DELTA - timedelta(days=1)) self.payload["orig_iat"] = timegm(orig_iat.utctimetuple()) data = {"token": utils.jwt_encode_handler(self.payload)} response = self.client.post(self.refresh_auth_token_url, data, content_type="application/json") self.assertEqual(response.status_code, 400)
def test_post_json_passing_jwt_auth(self): """ Ensure POSTing form over JWT auth with correct credentials passes and does not require CSRF """ payload = utils.jwt_payload_handler(self.user) token = utils.jwt_encode_handler(payload) auth = 'Bearer {0}'.format(token) response = self.client.post( '/jwt/', content_type='application/json', HTTP_AUTHORIZATION=auth ) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 200) self.assertEqual(response_content['username'], self.username)
def test_jwt_login_with_expired_token(self): """ Ensure JWT login view works even if expired token is provided """ payload = utils.jwt_payload_handler(self.user) payload['exp'] = 1 token = utils.jwt_encode_handler(payload) auth = 'Bearer {0}'.format(token) response = self.client.post(self.login_url, json.dumps(self.login_data_with_username), content_type='application/json', HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) decoded_payload = utils.jwt_decode_handler(response_content['token']) self.assertEqual(decoded_payload['username'], self.username)
def test_post_expired_token_failing_jwt_auth(self): """ Ensure POSTing over JWT auth with expired token fails """ payload = utils.jwt_payload_handler(self.user) payload['exp'] = 1 token = utils.jwt_encode_handler(payload) auth = 'Bearer {0}'.format(token) response = self.client.post('/jwt/', content_type='application/json', HTTP_AUTHORIZATION=auth) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 401) self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"') expected_error = ['Signature has expired.'] self.assertEqual(response_content['errors'], expected_error)
def test_login_with_expired_token(self): """ Ensure JWT login view works even if expired token is provided """ payload = utils.jwt_payload_handler(self.user) payload["exp"] = 1 token = utils.jwt_encode_handler(payload) auth = "Bearer {0}".format(token) response = self.client.post( self.auth_token_url, self.data, content_type="application/json", HTTP_AUTHORIZATION=auth, ) response_content = response.json() decoded_payload = utils.jwt_decode_handler(response_content["token"]) self.assertEqual(response.status_code, 200) self.assertEqual(decoded_payload["username"], self.username)
def test_post_expired_token_failing_jwt_auth(self): """ Ensure POSTing over JWT auth with expired token fails """ payload = utils.jwt_payload_handler(self.user) payload['exp'] = 1 token = utils.jwt_encode_handler(payload) auth = 'Bearer {0}'.format(token) response = self.client.post( '/jwt/', content_type='application/json', HTTP_AUTHORIZATION=auth ) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 401) self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"') expected_error = ['Signature has expired.'] self.assertEqual(response_content['errors'], expected_error)
def test_jwt_refresh_with_expired_token(self): """ Ensure JWT refresh view using JSON POST fails if the refresh has expired """ # We make sure that the refresh token is not in the window # allowed by the expiration delta. This is much easier using # freezegun. orig_iat = datetime.utcfromtimestamp(self.payload['orig_iat']) -\ settings.JWT_REFRESH_EXPIRATION_DELTA -\ timedelta(days=1) self.payload['orig_iat'] = timegm(orig_iat.utctimetuple()) data = {'token': utils.jwt_encode_handler(self.payload)} response = self.client.post('/refresh-token/', json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, 400)
def process_response(request, response): if 'HTTP_AUTHORIZATION' in request.META: try: auth_indicator = JSONWebTokenAuthMixin().authenticate(request) except AuthenticationFailed as e: logging.exception(e) return response if auth_indicator is None: return response token = auth_indicator[1] token = jwt_decode_handler(token) exp = token['exp'] exp = datetime.fromtimestamp(exp) if exp - timedelta(0, 3600) < datetime.now(): # expiring in one hour # renew the token from jwt_auth import settings token['exp'] = datetime.utcnow() + settings.JWT_EXPIRATION_DELTA token = jwt_encode_handler(token) newtoken = settings.JWT_AUTH_HEADER_PREFIX + " " + token response['HTTP_AUTHORIZATION'] = newtoken return response
def test_jwt_login_with_expired_token(self): """ Ensure JWT login view works even if expired token is provided """ payload = utils.jwt_payload_handler(self.user) payload['exp'] = 1 token = utils.jwt_encode_handler(payload) auth = 'Bearer {0}'.format(token) response = self.client.post( '/auth-token/', json.dumps(self.data), content_type='application/json', HTTP_AUTHORIZATION=auth ) response_content = json.loads(smart_text(response.content)) decoded_payload = utils.jwt_decode_handler(response_content['token']) self.assertEqual(response.status_code, 200) self.assertEqual(decoded_payload['username'], self.username)