passport.py 713 B

123456789101112131415161718192021
  1. import jwt
  2. from flask import current_app
  3. from werkzeug.exceptions import Unauthorized
  4. class PassportService:
  5. def __init__(self):
  6. self.sk = current_app.config.get('SECRET_KEY')
  7. def issue(self, payload):
  8. return jwt.encode(payload, self.sk, algorithm='HS256')
  9. def verify(self, token):
  10. try:
  11. return jwt.decode(token, self.sk, algorithms=['HS256'])
  12. except jwt.exceptions.InvalidSignatureError:
  13. raise Unauthorized('Invalid token signature.')
  14. except jwt.exceptions.DecodeError:
  15. raise Unauthorized('Invalid token.')
  16. except jwt.exceptions.ExpiredSignatureError:
  17. raise Unauthorized('Token has expired.')