def test_refresh_jwt(self): """ Test getting a refreshed token from original token works """ client = APIClient(enforce_csrf_checks=True) with freeze_time('2015-01-01 00:00:01'): orig_token = self.get_token() orig_token_decoded = utils.jwt_decode_handler(orig_token) expected_orig_iat = timegm(datetime.utcnow().utctimetuple()) # Make sure 'orig_iat' exists and is the current time (give some slack) orig_iat = orig_token_decoded['orig_iat'] self.assertLessEqual(orig_iat - expected_orig_iat, 1) with freeze_time('2015-01-01 00:00:03'): # Now try to get a refreshed token response = client.post('/auth-token-refresh/', {'token': orig_token}, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) new_token = response.data['token'] new_token_decoded = utils.jwt_decode_handler(new_token) # Make sure 'orig_iat' on the new token is same as original self.assertEquals(new_token_decoded['orig_iat'], orig_iat) self.assertGreater(new_token_decoded['exp'], orig_token_decoded['exp'])
def test_jwt_refresh(self): """ This test verifies that an existing user can refresh their JWT token :return: """ # NOTE: Only unexpired tokens can be refreshed. login_credentials = { 'username': self.username, 'password': self.password } response = self.api_client.post('/auth/api-token-auth/', login_credentials, format='json') jwt_token = response.data['token'] decoded_payload = utils.jwt_decode_handler(jwt_token) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsNotNone(jwt_token) decoded_payload = utils.jwt_decode_handler(jwt_token) refresh_payload = { 'token': jwt_token } response = self.api_client.post('/auth/api-token-refresh/', refresh_payload, format='json') new_jwt_token = response.data['token'] new_decoded_payload = utils.jwt_decode_handler(jwt_token) self.assertEqual(decoded_payload['orig_iat'], new_decoded_payload['orig_iat']) self.assertEqual(decoded_payload['exp'], new_decoded_payload['exp'])
def test_refresh_jwt(self): """ Test getting a refreshed token from original token works No date/time modifications are neccessary because it is assumed that this operation will take less than 300 seconds. """ client = APIClient(enforce_csrf_checks=True) orig_token = self.get_token() orig_token_decoded = utils.jwt_decode_handler(orig_token) expected_orig_iat = timegm(datetime.utcnow().utctimetuple()) # Make sure 'orig_iat' exists and is the current time (give some slack) orig_iat = orig_token_decoded['orig_iat'] self.assertLessEqual(orig_iat - expected_orig_iat, 1) time.sleep(1) # Now try to get a refreshed token response = client.post('/auth-token-refresh/', {'token': orig_token}, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) new_token = response.data['token'] new_token_decoded = utils.jwt_decode_handler(new_token) # Make sure 'orig_iat' on the new token is same as original self.assertEquals(new_token_decoded['orig_iat'], orig_iat) self.assertGreater(new_token_decoded['exp'], orig_token_decoded['exp'])
def test_jwt_decode_verify_exp(self): api_settings.JWT_VERIFY_EXPIRATION = False payload = utils.jwt_payload_handler(self.user) payload['exp'] = 1 token = utils.jwt_encode_handler(payload) utils.jwt_decode_handler(token) api_settings.JWT_VERIFY_EXPIRATION = True
def post(self, request): ''' a known issue now... a segment fault happens if you login and then logout and login again.. ''' serializer = testSignin.serializer_class(data=request.DATA) if serializer.is_valid(): payload = utils.jwt_decode_handler(serializer.object['token']) user = self.jwt.authenticate_credentials(payload) # below is a tric for authenticate.. # due to the authentication in django -- it need username and password, # however, decode of jwt doesn't contain password. user.backend = 'django.contrib.auth.backends.ModelBackend' # user = authenticate(username=user, nopass=True) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/home/') else: raise Exception('user not active') else: raise Exception('not valid user') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def token_payload(token, user=None, request=None): decoded = jwt_decode_handler(token) return { 'token': token, 'orig_iat': decoded.get('orig_iat'), 'user': ReferenceUserSerializer(user, context={'request': request}).data }
def test_login(self): """Test the login endpoint""" user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******', ) data = dict( username=user.username, email=user.email, password='******', ) response = self.client.post( '/api/v1/auth/login', data=data, format='json', ) self.assertEqual(response.status_code, status.HTTP_200_OK, 'Got error: {}'.format(response.content)) decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(decoded_payload['username'], user.username) self.assertEqual(decoded_payload['email'], user.email) self.assertEqual(decoded_payload['user_id'], user.pk)
def testuserJwtLogin(self): """Authenticate a test user, and prepare JWT token based authentification. POST user credentials to the JWT login url using the default :class:`django.test.TestCase.Client` client. Capture the JWT token from the request response, store it in :attr:`testuserdata['jwtToken']`, and setup the method :meth:`api_client()` of this instance to authenticate using this JWT token. Returns: The HTTP status code. """ # https://docs.djangoproject.com/en/1.8/releases/1.8/: # Passing a dotted path to reverse() and url # # Reversing URLs by Python path is an expensive operation as it # causes the path being reversed to be imported. # This behavior has also resulted in a security issue. # Use named URL patterns for reversing instead. # # See also: # https://docs.djangoproject.com/en/1.8/topics/auth/passwords/ # url = reverse('rest_framework_jwt.views.obtain_jwt_token') url = reverse('jwt_token_auth') response = self.client.post(url, self.data, format='json') jwtToken = response.data['token'] self.testuserdata['jwtToken'] = jwtToken self.testuserdata['decodedJwtToken'] = jwt_decode_handler(jwtToken) authHeader = 'JWT ' + self.testuserdata['jwtToken'] self.api_client.credentials(HTTP_AUTHORIZATION=authHeader) return response.status_code
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: raise exceptions.NotAuthenticated() try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: # pragma: no cover msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: # pragma: no cover msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: # pragma: no cover raise exceptions.AuthenticationFailed() except Exception as ex: raise exceptions.AuthenticationFailed(ex.message) user = User(**payload) return user, jwt_value
def post(self, request, model, app_label, object_id, field_name, score, **kwargs): user = utils.jwt_decode_handler(request.auth)['user_id'] user = CustomUser.objects.get(id=user) addRating = AddRatingFromModel() return addRating(request, model, app_label, object_id, field_name, score, user)
def grant(request): authKey = request.data.get('authKey') try: jwt_decode_handler(authKey) authenticated = True except: authenticated = False channels = request.data.get('channels') channels += [channel + '-pnpres' for channel in channels] channels = ','.join(channels) try: pubnub.grant(channel=channels, auth_key=authKey, read=True, write=authenticated, ttl=604800) return Response({'message': 'Granted!'}) except: return Response({'message': 'Failed!'}, status=status.HTTP_401_UNAUTHORIZED)
def test_create(self): serializer = JSONWebTokenSerializer(data=self.data) is_valid = serializer.is_valid() token = serializer.object['token'] decoded_payload = utils.jwt_decode_handler(token) self.assertTrue(is_valid) self.assertEqual(decoded_payload['username'], self.username)
def get(self, request): res = {} token = request.GET.get('token', None) cid = request.GET.get('cid', None) uid = jwt_decode_handler(token).get('user_id') hist = Learn.objects.filter(uid=uid, cid=int(cid)) ser = LearnSer(hist, many=True) res['code'] = 200 res['data'] = ser.data return Response(res)
def test_keep_jwt_session_after_refresh_user(self): """ Ensure JWT login view using JSON POST works. """ api_settings.JWT_ALLOW_REFRESH = True client = APIClient(enforce_csrf_checks=True) payload = utils.jwt_payload_handler(self.user, extra_data={'mock_id': 555}) token = utils.jwt_encode_handler(payload) assert utils.jwt_decode_handler(token)['mock_id'] == 555 response = client.post('/auth-token-refresh/', data={'token': token}, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK, str(response.content)) decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(decoded_payload['username'], self.username) self.assertEqual(decoded_payload['mock_id'], 555)
def get(self,request): token = request.META.get("HTTP_AUTHORIZATION").split(' ') a = jwt_decode_handler(token[2]) studrentid = a['user_id'] teachers = UserInfo.objects.filter(role=4) teacherserializer = TeacherInfoSerializer(teachers, many=True) teacherdata = teacherserializer.data result = True error = "" return JsonResponse({"result": result, "data": teacherdata, "error": error})
def post(self, request): decode_payload = jwt_decode_handler(request.data['token']) serializer = self.serializer_class(data=request.data, context={ 'user_id': decode_payload['user_id']}) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def authenticate(token, message): try: payload = jwt_decode_handler(token) except Exception: close_conn(message) msg = 'Token invalid/expired.' print(msg) raise ValueError(msg) user = payload['username'] return user
def parUpdate(self, request): body = request.data decoded = jwt_decode_handler( request.headers['Authorization'].split(' ')[1]) print(request.FILES) user = UserDetail.objects.get(username=decoded['username']) if (body.__contains__('username')): username = body['username'] user.username = username if (body.__contains__('first_name')): first_name = body['first_name'] user.first_name = first_name if (body.__contains__('last_name')): last_name = body['last_name'] user.last_name = last_name if (body.__contains__('email')): email = body['email'] user.email = email if (body.__contains__('phone')): phone = body['phone'] user.phone = phone if (body.__contains__('gender')): gender = body['gender'] user.gender = gender # if (body.__contains__('birthdate')): # birthdate = body['birthdate'] # user.birthdate = birthdate if (body.__contains__('is_tutor')): is_tutor = body['is_tutor'] if not bool(is_tutor): is_tutor = True if is_tutor == 'true' else False user.is_tutor = is_tutor if (body.__contains__('language')): languageId = body['language'] # Trae el id language = Language.objects.get(id=languageId) user.language = language if (body.__contains__('location')): locationId = body['location'] location = Location.objects.get(id=locationId) user.location = location if (body.__contains__('institution')): institutionId = body['institution'] institution = Institution.objects.get(id=institutionId) user.institution = institution if (body.__contains__('career')): careerId = body['career'] career = Career.objects.get(id=careerId) user.career = career if (body.__contains__('password')): newPw = body['password'] if newPw != '': user.set_password(newPw) user.save() return Response(UserDetailSerializer(user).data)
def test_keep_jwt_session_after_login(self): """ Ensure JWT login view using JSON POST works. """ client = APIClient(enforce_csrf_checks=True) payload = utils.jwt_payload_handler(extra_data={'mock_id': 555}) token = utils.jwt_encode_handler(payload) assert utils.jwt_decode_handler(token)['mock_id'] == 555 token = 'JWT {0}'.format(token) response = client.post('/auth-token/', data=self.data, HTTP_AUTHORIZATION=token, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username) self.assertEqual(decoded_payload['mock_id'], 555)
def test_user_login_provides_jwt_token(self): """It should be possible for logged in user to obtain JWT auth token. """ response = self.client.post(f'{self.BASE_AUTH_APP_URL}/register/', data=self.user_reg, format='json') # Ensure user is registered jwt_response = response.data # Should not raise if token is valid decode_jwt = jwt_decode_handler(jwt_response) self.assertEqual(response.status_code, status.HTTP_200_OK) response = self.client.post(f'{self.BASE_AUTH_APP_URL}/login/', data=self.user_log, format='json') jwt_response = response.data # Should not raise if token is valid decode_jwt = jwt_decode_handler(jwt_response) self.assertEqual(response.status_code, status.HTTP_200_OK)
def get(self, request): # 课程id cid = request.GET.get('cid', None) # 用户id jwt_token = request.GET.get('token', None) user = jwt_decode_handler(jwt_token) user_id = user.get('user_id') if not user_id: return Response({'code': 405, 'message': '请先登录'}) Buy(uid=int(user_id), cid=cid).save() return Response({'code': 200, 'message': '课程添加成功'})
def test_jwt_login_json(self): """ Ensure JWT login view using JSON POST works. """ client = APIClient(enforce_csrf_checks=True) response = client.post("/auth-token/", self.data, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK) decoded_payload = utils.jwt_decode_handler(response.data["token"]) self.assertEqual(decoded_payload["email"], self.email)
def get_submissions(request): token = request.environ['HTTP_AUTHORIZATION'] username = jwt_decode_handler(token)['username'] user = User.objects.get(username=username) if user.is_staff: submissions = Submission.objects.all().order_by('code') serializer = SubmissionSerializer(submissions, many=True) return JsonResponse(serializer.data, safe=False)
def post(self, request): # 我推荐重写,推荐企业加1自己也加1,还要有记录 # 1.获取传回来的指定功能参数 try: data = request.data #print(data) token = jwt_decode_handler(data['token']) except: return Response({"token_state": False}) # 2.如果拿获取到的数据对应修改 try: obj = EnterpriseCertificationInfo.objects.filter( user=token["user_id"], identity_status=2).first() except: return Response({"message": "查询出错"}) if obj: obj.recommended += 1 obj.save() try: # 查询对应的企业和用户的信息 state = Function.objects.filter(user_id=obj.company_id, company_id=data["company_id"]) if data["i_recommend"] == True and state.exists() == False: j = num_func(data["industryid"]) obj_data = globals()[j].objects.get( company_id=data["company_id"]) obj_data.recommended_count += 1 obj_data.save() # 保存状态操作 serializer = RecommendedSerializer(data=data, partial=True) if serializer.is_valid(): serializer.save() return Response({"state": 1}) else: return Response(serializer.errors) if state[0].i_recommend: return Response({'message': '你已经推荐过该企业'}) # 更新操作 serializer = RecommendedSerializer(state, data=data, partial=True) if serializer.is_valid(): serializer.save() return Response({"state": 1}) else: return Response(serializer.errors) except: return Response({"message": "程序出错"})
def post(self, request, *args, **kwargs): client_id = request.POST.get('client_id') client_secret = request.POST.get('client_secret') code = request.POST.get('code') try: jwt_decode_handler(code) except (ExpiredSignature, InvalidAudience, InvalidIssuer): return Response({ 'success': False, 'error': 'unauthorized', }, status=status.HTTP_401_UNAUTHORIZED) return Response( { 'access_token': code, 'refresh_token': '', 'expires_in': 3600 }, status=status.HTTP_200_OK)
def get(self, request): # 购买课程id cid = request.GET.get('cid', None) # 订单号 order = request.GET.get("order", None) # 获取token jwt_token = request.GET.get("token", None) user_json = jwt_decode_handler(jwt_token) # 获取token中的uid user_id = user_json.get("user_id") # 判断是否登录 if not user_id: return Response({"code": 405, "message": "用户信息已失效,请重新登录"}) # 查询订单是否存在,或订单是否已经支付过 order_id = Order.objects.filter(order=order, uid=int(user_id)).first() if not order_id or order_id.is_succeed == 1: return Response({"code": 405, "message": "订单不存在或已付款,请刷新后查看"}) alipay = AliPay( appid="2016102400753303", app_notify_url=None, # 默认回调url app_private_key_string=app_private_key_string, alipay_public_key_string=alipay_public_key_string, # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥, sign_type="RSA2", # RSA 或者 RSA2 debug=True # 默认False ) # 此为支付宝交易查询接口 response = alipay.api_alipay_trade_query(order) if response.get("code") != "10000" or response.get( "trade_status") != "TRADE_SUCCESS": return Response({"code": 405, "message": "开通失败"}) order_id = Order.objects.filter(order=order, uid=int(user_id)).first() # 将支付状态修改为已支付 order_id.is_succeed = 1 order_id.save() if not cid: # 查询开通的会员级别 vip = VIP.objects.filter(grade=order_id.behoof).first() # 修改对应用户的vip级别 user = User.objects.get(id=int(user_id)) user.vid = vip.id user.vip_start_time = datetime.datetime.now() # 提交所有修改 user.save() return Response({"code": 200, "message": "恭喜您,会员开通成功"}) else: Buy.objects.create(uid=int(user_id), cid=int(cid)) return Response({"code": 200, "message": "恭喜您,购买成功"})
async def __call__(self, receive, send): try: token = parse_qs( self.scope['query_string'].decode('utf8'))["token"][0] payload = jwt_decode_handler(token) username = jwt_get_username_from_payload_handler(payload) self.scope['user'] = await get_user(username) except: self.scope['user'] = AnonymousUser() inner = self.inner(self.scope) return await inner(receive, send)
def test_jwt_login_json(self): """ Ensure JWT login view using JSON POST works. """ client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(decoded_payload['user_id'], str(self.user.id))
def has_permission(self, request, view): token = request.META.get("HTTP_AUTHORIZATION").split(' ') trole = jwt_decode_handler(token[2]) if request.method == 'POST' or request.method == 'PUT' or request.method == 'DELETE': if trole['role'] == 2: return True else: return False else: return True return False
def login(self): """ Ensure we can login with a default admin user and get the token. """ url = reverse('login') response = self.client.post(url, self.data, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username) return response.data['token']
def get(self, request): try: payload = jwt_decode_handler(request.GET.get('token')) user = User.objects.get(id=payload['user_id']) if user.is_active is False: user.is_active = True user.save() except: pass return Response({"activation": True})
def get(self,request): token = request.META.get("HTTP_AUTHORIZATION").split(' ') a = jwt_decode_handler(token[2]) managerid = a['user_id'] complaits = Complaint.objects.filter(solve=True) complaitserializer = ComplaintSerializer(complaits, many=True) complaitdata = complaitserializer.data result = True data = {"data": complaitdata} error = "" return JsonResponse({"result": result, "data": data, "error": error})
def test_jwt_login_custom_response_json(self): """ Ensure JWT login view using JSON POST works. """ client = APIClient(enforce_csrf_checks=False) response = client.post('/api-auth/', self.data, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['email'], self.email)
def get_courses(request): token = request.environ['HTTP_AUTHORIZATION'] username = jwt_decode_handler(token)['username'] user = User.objects.get(username=username) if user.is_staff: courses = Course.objects.all().order_by('code') else: catie_profile = CATieProfile.objects.get(user=user) courses = catie_profile.courses.all().order_by('code') serializer = CourseSerializer(courses, many=True) return JsonResponse(serializer.data, safe=False)
def get(self, request): token = request.META.get("HTTP_AUTHORIZATION").split(' ') a = jwt_decode_handler(token[2]) classes = Classes.objects.filter(center_id=a["center_id"], delete=False, active=True) if len(classes)>0: serializer = ClassesSerializer(classes, many=True) data = serializer.data else: data={} result = True error = "" return JsonResponse({"result": result, "data": data, "error": error})
def test_jwt_login_form(self): """ Ensure JWT login view using form POST works. """ client = APIClient(enforce_csrf_checks=True) response = client.post("/auth-token/", self.data) decoded_payload = utils.jwt_decode_handler(response.data["token"]) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload["username"], self.username)
def authenticate(self, request): token = request.META.get('HTTP_SUPER_TOKEN'.upper()) try: payload = jwt_decode_handler(token) except jwt.ExpiredSignature: raise AuthenticationFailed("登陆已过期,请重新登陆!") except jwt.DecodeError: raise AuthenticationFailed('暂未登陆,请重新登陆!') except jwt.InvalidTokenError: raise AuthenticationFailed("token不合法,请重新登陆!") user = self.authenticate_credentials(payload) return (user, token)
def test_login(self): """ send access token if valid """ url = reverse('login') response = self.client.post(url, self.data, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username) self.assertFalse('password' in decoded_payload)
def test_get_demands(self): client = APIClient(enforce_csrf_checks=True) response = client.post('/login/', self.data, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + response.data['token']) response = client.get('/demands/', format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_user_registration_provides_jwt_token(self): """It should be possible for user to register and obtain JWT auth token. """ users = User.objects.all() response = self.client.post(f'{self.BASE_AUTH_APP_URL}/register/', data=self.user_reg, format='json') jwt_response = response.data # Should not raise if token is valid decode_jwt = jwt_decode_handler(jwt_response) self.assertEqual(response.status_code, status.HTTP_200_OK)
def delete(self, request): decode_payload = jwt_decode_handler(request.data['token']) serializer = self.serializer_class(data=request.data, context={ 'user_id': decode_payload['user_id']}) userhistory = UserHistory.objects.get( user_iduser=decode_payload['user_id'], movie_idmovie=request.data['movie_idmovie']) if serializer.is_valid(raise_exception=True): userhistory.delete() return Response(serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def has_permission(self, request, view): # Read permissions are allowed to any request if request.method == 'GET': token = request.META.get("HTTP_AUTHORIZATION").split(' ') a = jwt_decode_handler(token[2]) if a['role'] == 1: return True else: print("xsxs") return False return True
def get(self, request, format=None, pk=None): if request.user.is_authenticated(): user_id = request.user.pk else: try: token = request.META['HTTP_AUTHORIZATION'][3:] decode = jwt_decode_handler(token) user_id = decode['user_id'] except KeyError: return Response({"detail": "Authorization Token not provided or user Not Authenticated"}, status=401) playlists = PlayLists.objects.filter(user__pk=user_id) serializer = PlaylistSerializer(playlists, many=True) return Response(serializer.data)
def test_can_login_and_get_token(self): (http_status, response_json) = self._post( '/api-token-auth/', {'username': '******', 'password': '******'}) assert_equal(200, http_status) assert_in('token', response_json) decoded_token = jwt_decode_handler(response_json['token']) assert_equal({ 'email': '', 'exp': 1420156800, 'user_id': 1, 'username': '******'}, decoded_token)
def test_jwt_auth(self): """ This test verifies that an existing user can get an auth token using a JSON post :return: """ login_credentials = { 'username': self.username, 'password': self.password } response = self.api_client.post('/auth/api-token-auth/', login_credentials, format='json') jwt_token = response.data['token'] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsNotNone(jwt_token) decoded_payload = utils.jwt_decode_handler(jwt_token) self.assertEqual(decoded_payload['username'], self.username) self.assertEqual(decoded_payload['email'], self.email)
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 = 'JWT {0}'.format(token) client = APIClient(enforce_csrf_checks=True) response = client.post( '/auth-token/', self.data, HTTP_AUTHORIZATION=auth, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username)
def update(self, request, pk=None): if request.auth is not None: permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) user_id = utils.jwt_decode_handler(request.auth) user_id = user_id["user_id"] if user_id == int(pk): customuser = CustomUser.objects.get(pk=pk) serializer = CustomUserSerializer(customuser, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_401_UNAUTHORIZED) else: return Response(status=status.HTTP_401_UNAUTHORIZED)
def put(self, request, format=None, pk=None): if request.user.is_authenticated(): user_id = request.user.pk else: try: token = request.META['HTTP_AUTHORIZATION'][3:] decode = jwt_decode_handler(token) user_id = decode['user_id'] except KeyError: return Response({"detail": "Authorization Token not provided or user Not Authenticated"}, status=401) user = User.objects.get(pk=user_id); name = request.POST['name'] description = request.POST['description'] songs = request.POST.getlist('songs[]') songs = Song.objects.filter(pk__in=songs) playlist = PlayLists(user=user, name=name, description=description) playlist.save() playlist.songs.add(*songs) playlist.save() return Response({"inserted": playlist.pk}, status=200)
def register(request, *args, **kwargs): # If they've sent a bad token, we'll fail here auth_data = jwt_decode_handler(request.META['HTTP_AUTHORIZATION'][7:]) # Otherwise, it's a valid user. user = User.objects.get(pk=auth_data['user_id']) # Actually parse what they sent form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # lots of things we try and fail asap installable_id = form.data['installable_id'] installable = Installable.objects.get(pk=installable_id) if not installable.can_edit(user): raise Exception("User not allow to edit this installable") has_sig = len(form.data['sig']) > 0 tmp_path, sha256 = persist_to_tempfile(request.FILES['file']) rev_kwargs = { 'commit_message': form.data['commit'], 'uploaded': datetime.datetime.utcnow(), 'tar_gz_sha256': sha256, 'tar_gz_sig_available': has_sig, 'installable': installable, 'replacement_revision': None, 'downloads': 0, } try: # Try to get the version from their file rev_kwargs['version'] = get_version(tmp_path) except Exception, e: # Otherwise cancel everything and quit ASAP try: os.unlink(tmp_path) except Exception, e: log.error(e) return JsonResponse({'error': True, 'message': 'Server Error'})
def finalize_response(self, request, response, *args, **kwargs): """ Add a response header to suggest a token refresh when we get close to the expiration time. """ response = super(JWTViewSet, self).finalize_response( request, response, *args, **kwargs ) auth = request.auth delta = settings.JWT_SUGGEST_REFRESH_DELTA if auth: try: payload = jwt_decode_handler(auth) expiry = payload.get('exp') utc_timestamp = timegm(datetime.utcnow().utctimetuple()) if utc_timestamp > (expiry - delta.seconds): response['Suggest-Token-Refresh'] = 'True' except: # the token has expired, so no need to try and refresh it pass return response
def test_jwt_decode(self): payload = utils.jwt_payload_handler(self.user) token = utils.jwt_encode_handler(payload) decoded_payload = utils.jwt_decode_handler(token) self.assertEqual(decoded_payload, payload)
def test_correct_audience(self): payload = utils.jwt_payload_handler(self.user) payload['aud'] = "my_aud" token = utils.jwt_encode_handler(payload) decoded_payload = utils.jwt_decode_handler(token) self.assertEqual(decoded_payload, payload)
def test_fail_audience_wrong(self): payload = utils.jwt_payload_handler(self.user) payload['aud'] = "my_aud2" token = utils.jwt_encode_handler(payload) with self.assertRaises(jwt.exceptions.InvalidAudienceError): utils.jwt_decode_handler(token)
def test_correct_issuer(self): payload = utils.jwt_payload_handler(self.user) payload['iss'] = "example.com" token = utils.jwt_encode_handler(payload) decoded_payload = utils.jwt_decode_handler(token) self.assertEqual(decoded_payload, payload)
def test_fail_issuer_wrong(self): payload = utils.jwt_payload_handler(self.user) token = utils.jwt_encode_handler(payload) payload['iss'] = "example2.com" with self.assertRaises(jwt.exceptions.InvalidIssuerError): utils.jwt_decode_handler(token)
def test_fail_issuer_missing(self): payload = utils.jwt_payload_handler(self.user) token = utils.jwt_encode_handler(payload) with self.assertRaises(jwt.exceptions.InvalidIssuerError): utils.jwt_decode_handler(token)
def get(self, request, model, app_label, object_id, field_name, score): serializer = VoteSerializer(data=request.data) user = utils.jwt_decode_handler(request.auth)['user_id'] return Response('{"response":"hey."}', status=status.HTTP_200_OK)
def post(self, request, format=None): try: user_id = utils.jwt_decode_handler(request.auth) return Response(user_id, status=status.HTTP_200_OK) except Exception as e: return Response({"error": e.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)