def test_get_cultural_heritage_item(self): title = 'Very emotional thresh hook' item_data = { "title": title, } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) item_data = { "title": "Draven montage", } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.cultural_heritage_item_url + "?limit=1", format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['results']), 1) response = self.client.get( self.cultural_heritage_item_url + "?limit=1&offset=1", format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['results']), 1)
def guardadatosmovil(request): if request.method == 'POST': id=request.user.id modelo_celular = json.loads(request.body)['model'] version_celular = json.loads(request.body)['tipo'] uuid = json.loads(request.body)['uuid'] print 'Guardando...',modelo_celular,version_celular if Usuarios.objects.filter(uuid=uuid): so = Usuarios.objects.get(uuid=uuid) so.modelo_celular = modelo_celular so.version_celular = version_celular so.ip= get_real_ip(request) so.fecha=datetime.datetime.today() so.save() c= simplejson.dumps({'u':'ok'}) return HttpResponse(c, content_type="application/json")
def test_cultural_heritage_item_favorited_amount(self): item_data = { "title": "Ahri mid montage", } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) response_content = json.loads(smart_text(response.content)) id = response_content['id'] self.assertEqual(response.status_code, 201) response = self.client.post( '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/', format='json', ) self.assertEqual(response.status_code, 201) response = self.client2.post( '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/', format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.cultural_heritage_item_url + str(id), format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['favorited_amount'], 2)
def test_list_user_items_with_another_user(self): title = 'Very emotional thresh hook' item_data = { "title": title, } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.my_items_url, format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['results'][0]['title'], title) self.client.logout() self.client.login(username=self.username2, password=self.password2) response = self.client.get( self.my_items_url, format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['results']), 0)
def test_create_cultural_heritage_item_with_time(self): item_data = { "title": "Very emotional thresh hook", 'start_year': 1512, 'end_year': 1571 } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] response = self.client.get( self.cultural_heritage_item_url + str(id) + '/', format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertAlmostEqual(float(response_content['start_year']), 1512) self.assertAlmostEqual(float(response_content['end_year']), 1571)
def test_signup_default_profile_picture(self): """ Ensure JWT signup works using JSON POST . """ data = { 'email': "*****@*****.**", 'username': "******", 'password': self.password, 'confirm_password': self.password, } response = self.client.post(self.sigun_url, json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, 201) self.login_data_with_username['username_or_email'] = "Suleiman" response = self.client.post( self.login_url, json.dumps(self.login_data_with_username), content_type='application/json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) token = response_content['token'] response = APIClient().get('/api/auth/me/', HTTP_AUTHORIZATION='JWT ' + token) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 200) self.assertEqual(response_content['username'], "Suleiman") self.assertEqual(response_content['email'], "*****@*****.**") self.assertTrue( response_content['profile_picture'] in settings.PROFILE_PICTURES)
def test_recommendation_with_time(self): item_data = { "title": "Draven support", 'tags': [{ 'name': 'lol' }, { 'name': 'support' }], 'longitude': '23.523', 'latitude': '43.232', 'start_year': 1500, 'end_year': 1700, } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] item_data = { "title": "zoe support", 'tags': [{ 'name': 'lol' }, { 'name': 'support' }], 'longitude': '40.523', 'latitude': '52.232', } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) item_data = { "title": "istanbul galata tower", 'longitude': '25.523', 'latitude': '48.232', 'start_year': 1500, 'end_year': 1700, } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) item_data = { "item_id": id, } response = self.client.get('/cultural_heritage_item/recommendation', item_data, format='json') response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['results'][0]['title'], 'istanbul galata tower')
def test_account_update_with_firstname_and_picture(self): response = self.client.post( self.login_url, json.dumps(self.login_data_with_username), content_type='application/json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) token = response_content['token'] data = { 'profile_picture': 'http://i.imgur.com/3OLTFVq.jpg', 'firstname': 'hayri', } response = APIClient().patch(self.update_profile + self.username + '/', json.dumps(data), content_type='application/json', HTTP_AUTHORIZATION='JWT ' + token) self.assertEqual(response.status_code, 200) response = APIClient().get('/api/auth/me', HTTP_AUTHORIZATION='JWT ' + token) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['profile_picture'], 'http://i.imgur.com/3OLTFVq.jpg') self.assertEqual(response_content['firstname'], 'hayri')
def updatealias(request): if request.method == 'POST': print json.loads(request.body) alias =json.loads(request.body)['info'] uuid = json.loads(request.body)['uuid'] print 'nombre',alias try: _u =Usuarios.objects.get(uuid=uuid) _u.publicidadcompartir = alias _u.save() except: pass c= simplejson.dumps('ok') return HttpResponse(c, content_type="application/json")
def test_create_cultural_heritage_item_with_comment(self): item_data = { "title": "Very emotional thresh hook", } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) response_content = json.loads(smart_text(response.content)) id = response_content['id'] self.assertEqual(response.status_code, 201) text = 'That is a nice heritage item' item_data = { 'comment': { 'text': text, } } response = self.client.post( self.cultural_heritage_item_url + str(id) + '/comment', item_data, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.cultural_heritage_item_url + str(id) + '/', format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['comments']), 1) self.assertEqual(response_content['comments'][0]['text'], text) self.assertEqual(response_content['id'], id)
def test_get_tags(self): item_data = { "title": "Space needle", 'tags': [{ 'name': 'place1', }, { 'name': 'Seattle1' }, { 'name': 'space1' }, { 'name': 'Needle1' }, { 'name': 'downtown1' }] } item_data2 = { "title": "Discovery park", 'tags': [{ 'name': 'place', }, { 'name': 'Seattle' }, { 'name': 'space' }, { 'name': 'Needle' }, { 'name': 'downtown' }] } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.post( self.cultural_heritage_item_url, item_data2, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.tags_url, format='json', ) # test endpoint flexibility response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content), 10) response = self.client.get( '/tags', format='json', ) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content), 10)
def test_cultural_heritage_search_with_guest_user(self): item_data = { "title": "Draven support", 'tags': [{ 'name': 'adc', }, { 'name': 'meta' }], 'place_name': 'meta', 'latitude': '22.12', 'longitude': '23.14' } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) item_data = { "title": "Zoe support", 'latitude': '26.12', 'longitude': '27.14' } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) item_data = { "title": "Tresh hook meta", 'tags': [{ 'name': 'Meta' }, { 'name': 'support' }] } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) self.client.logout() response = self.client.get(self.cultural_heritage_item_url + 'search/' + 'adc') response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['results']), 1) response = self.client.get(self.cultural_heritage_item_url + 'search/' + 'meta') response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['results']), 3)
def test_item_visit_time(self): title = 'Very emotional thresh hook' item_data = { "title": title, "tags": [ { "name": "talha", "name": "thresh", } ] } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] item_data = { 'cultural_heritage_item': id, 'duration': 5 } response = self.client.put( '/user/visit_time', item_data, format='json', ) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 200) self.assertEqual(response_content['duration'], 5) response = self.client.put( '/user/visit_time', item_data, format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['duration'], 10) response = self.client2.put( '/user/visit_time', item_data, format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['duration'], 5)
def vendidogrupo(request): print 'POST..', json.loads(request.body) x = json.loads(request.body) ''' f = open('/var/www/html/error.html', 'a') f.write(x) f.close() ''' data = json.dumps('x') return HttpResponse(data, content_type="application/json")
def test_me_endpoint_with_loggedin_user(self): response = self.client.post( self.login_url, json.dumps(self.login_data_with_username), content_type='application/json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) token = response_content['token'] response = APIClient().get('/api/auth/me/', HTTP_AUTHORIZATION='JWT ' + token) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 200) self.assertEqual(response_content['username'], self.username) self.assertEqual(response_content['email'], self.email)
def test_get_cultural_heritage_item_by_id_with_image_media_items(self): item_data = { "title": "Very emotional thresh hook", } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] # First image item image_item_data1 = { 'images': [ { 'url': 'http://i.imgur.com/3OLTFVq.jpg', 'main': True }, ] } response = self.client.post( self.cultural_heritage_item_url + str(id) + '/image', image_item_data1, format='json', ) self.assertEqual(response.status_code, 201) # Second image item image_item_data2 = { 'images': [{ 'url': 'http://i.imgur.com/3OL28374TFVq.jpg', }] } response = self.client.post( self.cultural_heritage_item_url + str(id) + '/image', image_item_data2, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.cultural_heritage_item_url + str(id), format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['images']), 2)
def post(self, request): print 'aceptaser', json.loads(request.body)[0]['id'] id_socia = Socia.objects.get(user_id=request.user.id).id ser = Servicio.objects.get(id=json.loads(request.body)[0]['id']) numero_notificacion = Cliente.objects.get( user_id=ser.cliente.user.id).numero_notificacion noticliente = ser.cliente.numero_notificacion ser.socia_id = id_socia ser.estado_id = 2 ser.save() header = { "Content-Type": "application/json; charset=utf-8", "Authorization": "Basic OGQyNTllMmUtMmY2Ny00ZGQxLWEzNWMtMjM5NTdlNjM0ZTc3" } payload = { "app_id": "6d06ccb5-60c3-4a76-83d5-9363fbf6b40a", "include_player_ids": [numero_notificacion], "contents": { "en": "Tienes una nueva chica que te atendera" }, "data": { 'aceptaservicio': json.loads(request.body)[0]['id'] } } req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload)) print(req.status_code, req.reason) x = { 'servicio': json.loads(request.body)[0]['id'], 'detalle': 'socia-cliente' } c = simplejson.dumps(x) return HttpResponse(c, content_type="application/json")
def put(self, request): id = request.user.id data = json.loads(request.body) print data telefono = None cliente = data['id'] c = Cliente.objects.get(id=cliente) au = AuthUser.objects.get(id=c.user_id) for i in data: if i == 'estado_civil': c.estado_civil_id = data['estado_civil'] if i == 'numero_hijos': c.numero_hijos = data['numero_hijos'] if i == 'first_name': au.first_name = data['user__first_name'] if i == 'last_name': au.last_name = data['user__last_name'] if i == 'email': au.email = data['user__email'] if i == 'pais': au.pais = data['user__pais'] if i == 'nacimiento': au.nacimiento = data['user__nacimiento'] if i == 'telefono': telefono = data['telefono']['numero'] if i == 'dni': au.dni = data['user__dni'] if i == 'user__direccion': au.direccion = data['user__direccion'] c.save() au.save() if telefono: TelefonoUser(user_id=c.user.id, numero=telefono).save() return HttpResponse(simplejson.dumps('OK'), content_type="application/json")
def test_item_popularity_num_comments(self): response = self.client.post(self.cultural_heritage_item_url, {'title': 'Lee Sin'}, format='json') self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] item = Cultural_Heritage.objects.all()[0] self.assertEqual(popularity_score(item), 0) num_comments = 6 for i in range(num_comments): response = self.client.post( self.cultural_heritage_item_url + str(id) + '/comment', {'comment': { 'text': 'Comment {}'.format(i) }}, format='json') self.assertEqual(response.status_code, 201) item = Cultural_Heritage.objects.all()[0] expected_popularity = log(1 + num_comments * COEFF_NUM_COMMENTS) self.assertAlmostEqual(popularity_score(item), expected_popularity)
def test_delete_cultural_heritage_item(self): title = 'Very emotional thresh hook' item_data = { "title": title, } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] response = self.client.delete( self.cultural_heritage_item_url + str(id) + '/', format='json', ) self.assertEqual(response.status_code, 204) response = self.client.get( self.cultural_heritage_item_url + str(id) + '/', format='json', ) self.assertEqual(response.status_code, 404)
def contacto(request): print 'entrando..' if request.method == 'POST': data = json.loads(request.body)['data'] descripcion = data['descripcion'] name = data['name'] email = data['email'] subject, from_email, to = 'Nuevo Contacto', '*****@*****.**', '*****@*****.**' text_content = 'Un nuevo contacto ' html_content = 'Email: ' + email + '<br>' + 'Name:' + name + '<br>' + descripcion msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() c = simplejson.dumps('ok') return HttpResponse(c, content_type="application/json")
def test_favorite_cultural_heritage_item_twice(self): item_data = { "title": "Ahri mid montage", } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) response_content = json.loads(smart_text(response.content)) id = response_content['id'] self.assertEqual(response.status_code, 201) self.client.post( '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/', format='json', ) # Here we ensure that the same user cannot favorite the same item more than once. response = self.client.post( '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/', format='json', ) self.assertEqual(response.status_code, 400)
def test_item_popularity_num_favorites(self): response = self.client.post(self.cultural_heritage_item_url, {'title': 'Lee Sin'}, format='json') self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) response = self.client.post( '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/', format='json', ) self.assertEqual(response.status_code, 201) item = Cultural_Heritage.objects.all()[0] expected_popularity = log(1 + COEFF_NUM_FAVORITES) self.assertAlmostEqual(popularity_score(item), expected_popularity) response = self.client.delete( '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/', format='json', ) self.assertEqual(response.status_code, 204) item = Cultural_Heritage.objects.all()[0] self.assertEqual(popularity_score(item), 0)
def test_create_cultural_heritage_item_with_tags(self): item_data = { "title": "Space needle", 'tags': [{ 'name': 'place', }, { 'name': 'Seattle' }, { 'name': 'space' }, { 'name': 'Needle' }, { 'name': 'downtown' }] } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 201) id = response_content['id'] response = self.client.get( self.cultural_heritage_item_url + str(id), format='json', ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response_content['tags']), 5)
def actualiza(request,uuid): if request.method == 'POST': data = json.loads(request.body) print 'actualiza..',data if Usuarios.objects.filter(uuid=uuid).count() >0 : _u=Usuarios.objects.get(uuid=uuid) _u.lat=data['position']['lat'] _u.lng=data['position']['lng'] _u.modelo_celular=data['model'] _u.version_celular=data['tipo'] _u.ip= get_real_ip(request) _u.save() c= simplejson.dumps('ok') return HttpResponse(c, content_type="application/json")
def test_account_update_with_new_password(self): response = self.client.post( self.login_url, json.dumps(self.login_data_with_username), content_type='application/json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) token = response_content['token'] data = { 'old_password': '******', 'password': '******', 'confirm_password': '******' } response = APIClient().patch(self.update_profile + self.username + '/', json.dumps(data), content_type='application/json', HTTP_AUTHORIZATION='JWT ' + token) self.assertEqual(response.status_code, 200) self.login_data_with_username['password'] = '******' response = self.client.post( self.login_url, json.dumps(self.login_data_with_username), content_type='application/json', ) self.assertEqual(response.status_code, 200)
def post(self, request): data = json.loads(request.body) dato = data['dato'] print '......',dato colegio =data['colegio'] nivel = ['inicial','primaria','secundaria'] if dato['inicial'] == True: Colegionivel(nivel_id=1,colegio_id=colegio).save() if dato['primaria'] == True: Colegionivel(nivel_id=2,colegio_id=colegio).save() if dato['secundaria'] == True: Colegionivel(nivel_id=3,colegio_id=colegio).save() data_dict = ValuesQuerySetToDict(colegio) data_json = simplejson.dumps(data_dict) return HttpResponse(data_json, content_type="application/json")
def test_create_cultural_heritage_item_with_many_images_at_once(self): item_data = { "title": "Space needle", } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] image_item_data = { 'images': [ { 'url': 'http://i.imgur.com/1113OLTFsdfVq.jpg', }, { 'url': 'http://i.imgur.com/111r3OLTF21Vq.jpg', }, { 'url': 'http://i.imgur.com/111e3OLT3213FVq.jpg', }, { 'url': 'http://i.imgur.com/1113wO12LTFVq.jpg', }, { 'url': 'http://i.imgur.com/1113weOLTFVq.jpg', }, ] } response = self.client.post( self.cultural_heritage_item_url + str(id) + '/image', image_item_data, format='json', ) self.assertEqual(response.status_code, 201) response = self.client.get( self.cultural_heritage_item_url + str(id), format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(len(response_content['images']), 5)
def test_update_cultural_heritage_item(self): title = 'Very emotional thresh hook' item_data = { "title": title, "tags": [{ "name": "talha", "name": "thresh", }] } response = self.client.post( self.cultural_heritage_item_url, item_data, format='json', ) self.assertEqual(response.status_code, 201) response_content = json.loads(smart_text(response.content)) id = response_content['id'] item_data = { "comments": [], "description": "new description", "id": id, "images": [], "public_accessibility": True, "tags": [{ "name": "tag" }], "title": "Title 7jaaa", # "user": 2 Since we wont change the user } response = self.client.patch( self.cultural_heritage_item_url + str(id) + '/', item_data, format='json', ) self.assertEqual(response.status_code, 200) response = self.client.get( self.cultural_heritage_item_url + str(id) + '/', format='json', ) self.assertEqual(response.status_code, 200) response_content = json.loads(smart_text(response.content)) self.assertEqual(response_content['title'], 'Title 7jaaa') self.assertEqual(response_content['tags'][0]['name'], 'tag')
def guardaintercambio(request,uuid): if request.method == 'POST': deseo = json.loads(request.body)['deseo'] ofrezco = json.loads(request.body)['ofrezco'] user_id = Usuarios.objects.get(uuid=uuid).id Intercambio(user_id=user_id,deseo_id=deseo,ofrezco_id=ofrezco).save() _id = Intercambio.objects.all().values('id').order_by('-id')[0]['id'] c= simplejson.dumps(_id) return HttpResponse(c, content_type="application/json")
def test_post_json_failing_jwt_auth(self): """ Ensure POSTing json over JWT auth without correct credentials fails """ response = self.client.post('/jwt/', content_type='application/json') response_content = json.loads(smart_text(response.content)) self.assertEqual(response.status_code, 401) self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"') expected_error = ['Incorrect authentication credentials.'] self.assertEqual(response_content['errors'], expected_error)
def test_jwt_login_json(self): """ Ensure JWT login view using JSON POST works. """ response = self.client.post( '/auth-token/', json.dumps(self.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 post(self, request, *args, **kwargs): try: request_json = json.loads(smart_text(request.body)) except ValueError: return self.render_bad_request_response() form = JSONWebTokenForm(request_json) if not form.is_valid(): return self.render_bad_request_response({'errors': form.errors}) context_dict = { 'token': form.object['token'] } return self.render_response(context_dict)
def test_post_invalid_jwt_header_failing_jwt_auth(self): """ Ensure POSTing over JWT auth without correct credentials fails """ auth = 'Bearer abc abc' 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 = ['Invalid Authorization header. Credentials string should not contain spaces.'] self.assertEqual(response_content['errors'], expected_error)
def test_post_invalid_token_failing_jwt_auth(self): """ Ensure POSTing over JWT auth with invalid token fails """ auth = 'Bearer abc123' 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 = ['Error decoding signature.'] self.assertEqual(response_content['errors'], expected_error)
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_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_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)
def post(self, request): request_json = json.loads(smart_text(request.body)) print request_json token = request_json['token'] new_payload = self.refresh(token) return Response(json.dumps(new_payload), mimetype='application/json')