def test_get_user_from_request_without_header(self): """ get_user_from_request must raise Exception on no Authorization header """ user = self.create_user() encoded_jwt, timestamp = self.make_jwt(user) request = HttpRequest() User.redis_connection.database[encoded_jwt] = timestamp with self.assertRaises(Exception): User.get_user_from_request(request)
def check_post_reachable(self, post, request): if post.status == Post.DELETED: raise Exception('Post not found') if post.status != Post.ACTIVE: user = None try: user = User.get_user_from_request(request) except: pass if not user or not user.pk == post.author.pk: raise Exception('Post not found')
def test_get_user_from_request(self): """ get_user_from_request must return authenticated user from request """ user = self.create_user() encoded_jwt, timestamp = self.make_jwt(user) decoded_jwt = encoded_jwt.decode('utf-8') request = HttpRequest() request.META = {'HTTP_AUTHORIZATION': decoded_jwt} User.redis_connection.database[encoded_jwt] = timestamp authenticated_user = User.get_user_from_request(request) self.assertEqual(user.email, authenticated_user.email, 'Wrong user returned')
def wrapper(request: HttpRequest, *args, **kwargs): try: user = User.get_user_from_request(request) if not user: raise Exception('User not found') return func(request, user, *args, **kwargs) except Exception as error: return JsonResponse({ 'status': 'error', 'message': str(error) }, status=403)