0

I'm not sure if this is even possible, but I'm trying to discover patterns that would make my code more maintainable/extendable. Right now I don't like that I have to call a token decode function in every request method view function, I find the @before_request decorator being attached to a blueprint super handy but I haven't figured out how to mutate the request body so that the function can just "magically" expect the decrypted payload in the request body. If this is not intended to be permitted I can totally understand that as well from a software perspective...

I'm looking for something like this :-

Edit incoming request body payloads in flask api

Currently my setup is :

class MyMethodView(MethodView):
    def post(self):
        token = request.headers.get('token')
        identifier, is_valid = decrypt_token(token)
        # Use identifier for endpoint 

What I'd like to do is

class MyMethodView(MethodView):
    def post(self):
        identifier= request.get_json().get('identifier')
        # Use identifier for endpoint 

using the following

blueprint.@before_request():
def authenticate():
  token = request.headers.get('token')
  identifier, is_valid = decrypt(token)
  # Some how modify the request body with the identifier

  if is_valid: 
    return None
  else:
    #Unauthorized

I guess some of my curiosity revolves around whether there is a better way to do this as opposed to adding the auth check logic to every function, from my perspective I could build a few public endpoints to test locally and then just slap on some code without modifying those functions to add authentication.

fibonachoceres
  • 727
  • 4
  • 14

1 Answers1

1

You can store the decoded token in the flask.g object in your before_action to make it available for the lifetime of that request. https://flask.palletsprojects.com/en/1.1.x/appcontext/

vimalloc
  • 3,869
  • 4
  • 32
  • 45
  • Thanks I suppose this is the next best thing possible apart from trying to make your code agnostic to the interception. Since this means that I'd have to refactor all the existing endpoints, I'm thinking I could go with a function that wraps request.get_json() instead of replacing the assignment with the g context. But this is useful to know for other cases I might have in the future, thanks! I think if I access the request module from another function it'll still get me the right request context so this should be possible – fibonachoceres Sep 19 '20 at 11:27