Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime, timedelta
- from flask import g
- import jwt
- @api.route("/login")
- class UserLogin(Resource):
- def post(self) -> Tuple[dict, int]:
- return "error", 400
- access_token = jwt.encode(
- {
- "id": 1, #user id
- "exp": datetime.utcnow() + timedelta(seconds=3600),
- },
- _______JWT_PRIVATE_KEY_HERE_____,
- algorithm="RS256",
- )
- return token, 200
- # Protected endpoint
- @api.route("")
- class TestGet(Resource):
- @auth
- def get(self):
- return f"Hi, your user id is {g.id}", 200
- # Decorator to authenticate jwt tokens and set user id in g
- def auth(f):
- @wraps(f)
- def decoder_wrapper_function(*args, **kwargs):
- token = authorization.split("Bearer ")
- decoded = jwt.decode(token[1], _______JWT_PUBLIC_KEY_HERE________, algorithms=["RS256"])
- if decoded and "id" in decoded.keys():
- g.id = decoded["id"]
- return f(*args, **kwargs)
- raise Exception("Unauthorized user.")
- return decoder_wrapper_function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement