0

I have a custom middleware where I check whether incoming requests have a cookie present or not. If the cookie is not present, then it shows KeyError:.

[15/May/2021 18:00:05] "GET /api/auth/profile/ HTTP/1.1" 500 62653
Internal Server Error: /
Traceback (most recent call last):
  File "F:\<dir>\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "F:\<dirs\to\middleware>\middleware.py", line 49, in __call__
    myCookie = request.COOKIES['my_cookie']
KeyError: 'my_cookie'

I want it to return only a 500 Internal Server Error if the cookie is not present. How do I do this?

This is my middleware:

class AuthMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        if request.path == '/api/auth/profile/':

            try:
                myCookie = request.COOKIES['my_cookie']
                // do something with the cookie
                return self.get_response(request)

            except jwt.ExpiredSignatureError:
                // do something
                return self.get_response(request)

Here, I only check whether the token has expired but I couldn't add mechanism to handle a KeyError. How do I do this?

forest
  • 1,312
  • 3
  • 20
  • 47

2 Answers2

0

Add another exception like this:

try:
    myCookie = request.COOKIES['my_cookie']
    // do something with the cookie
    return self.get_response(request)

except jwt.ExpiredSignatureError:
    // do something
    return self.get_response(request)

except KeyError:
    // do something
    return self.get_response(request)

Or you can use

my_cookie = request.COOKIES.get('my_cookie', None)
if not my_cookie:  # cookie not found
   # do something
return self.get_response(request)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Here, if I return `self.get_response(request)` from `except KeyError`, it'll be an unauthorized access. So I want to return a 500 error from this response. Now, can I return errors or statuses from custom middlewares? – forest May 16 '21 at 16:35
  • It is possible. Please see this answer: https://stackoverflow.com/a/52827952/2696165 – ruddra May 16 '21 at 16:50
0

Found a workaround with HttpResponseServerError:

from django.http import HttpResponse, HttpResponseServerError

class AuthMiddleware:
    ...
    def __call__(self, request):
        ...
        except KeyError:
            response = HttpResponseServerError()
            response.write("<h2>Error: Cookie [ access ] is missing!</h2>")
            return response

I think it's better to use DRF custom exceptions for this issue.

forest
  • 1,312
  • 3
  • 20
  • 47