Advertisement
Guest User

auth

a guest
Nov 14th, 2022
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | Source Code | 0 0
  1. from datetime import datetime, timedelta
  2. from flask import g
  3. import jwt
  4.  
  5. @api.route("/login")
  6. class UserLogin(Resource):
  7.     def post(self) -> Tuple[dict, int]:
  8.         if api.payload["email"] != "[email protected]":
  9.              return "error", 400
  10.         access_token = jwt.encode(
  11.             {
  12.                 "id": 1, #user id
  13.                 "exp": datetime.utcnow() + timedelta(seconds=3600),
  14.             },
  15.             _______JWT_PRIVATE_KEY_HERE_____,
  16.             algorithm="RS256",
  17.         )
  18.         return token, 200
  19.  
  20. # Protected endpoint
  21. @api.route("")
  22. class TestGet(Resource):
  23.     @auth
  24.     def get(self):
  25.         return f"Hi, your user id is {g.id}", 200
  26.  
  27. # Decorator to authenticate jwt tokens and set user id in g
  28. def auth(f):
  29.     @wraps(f)
  30.     def decoder_wrapper_function(*args, **kwargs):
  31.         token = authorization.split("Bearer ")
  32.         decoded = jwt.decode(token[1], _______JWT_PUBLIC_KEY_HERE________, algorithms=["RS256"])
  33.         if decoded and "id" in decoded.keys():
  34.             g.id = decoded["id"]
  35.             return f(*args, **kwargs)
  36.         raise Exception("Unauthorized user.")
  37.  
  38.     return decoder_wrapper_function
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement