0

I have custom token creating and decoding methods. Now everytime I get request I need to decode token to get request user or I get anonymous user. How can I decode it without repeating every time these lines?

    auth = get_authorization_header(request).split()

    if auth and len(auth) == 2:
        token = auth[1].decode('utf-8')
        id = decode_access_token(token)

1 Answer 1

1

You can create a middleware, where you decode the token and pass the info about the user to the class/function view

class SimpleMiddleware:
  def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

  def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    auth = get_authorization_header(request).split()
    user = None
    if auth and len(auth) == 2:
      token = auth[1].decode('utf-8')
      id = decode_access_token(token)
      user = ... # get user
    response = self.get_response(request, user)

    # Code to be executed for each request/response after
    # the view is called.

    return response

And in your view

@method_decorator(SimpleMiddleware, name='dispatch')
class SimpleView(View):

  def post(self, request, user):
    pass
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answer. In which file you suggest to store this middleware code?
I usually create a middleware folder, inside the application root folder, in which I store every middleware separately - e.g. /app/middleware/SimpleMiddleware.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.