0

I'm trying the get all orders that belonging the user that already login to the system.

I want to get the id information of the current user with the get() method below and get the order information belonging to current user from the order table. My goal is to get the current user's id from the JWT token using flask-jwt-extended.

How can I do that?

@api.route('/orders')
@jwt_required()
def get(self):
   # current_user_info
   user_id = current_user_info["id"]
   return UserService.get_orders(user_id)

baris
  • 48
  • 7
  • 1
    There are two ways this can be done. 1. Your UI at each call will call get_current_user returning user information and then you develop API /orders/ to get the particular user order info. 2. I guess jwt_extended package has get_jwt_identity() using which Id can also be obtained. I prefer 1 personally. – coldy Feb 13 '22 at 20:55

2 Answers2

2

flask_jwt_extended provides the get_jwt_identity() function, which returns the identity used to create the token used in the current call: create_access_token(identity=username).

Link to the documentation

So in your case, it should become something like this

@api.route('/orders')
@jwt_required()
def get(self):
   # current_user_info
   user_id = get_jwt_identity()
   return UserService.get_orders(user_id)
Matteo Pasini
  • 1,787
  • 3
  • 13
  • 26
1

You can see the complete documentation for user loading and retrieval here: https://flask-jwt-extended.readthedocs.io/en/stable/automatic_user_loading/

vimalloc
  • 3,869
  • 4
  • 32
  • 45