token_auth.py 979 B

12345678910111213141516171819202122232425262728293031323334
  1. from collections import namedtuple
  2. from flask import current_app, g, request
  3. from flask_httpauth import HTTPBasicAuth
  4. from itsdangerous import Serializer, BadSignature, SignatureExpired
  5. from app.libs.error_code import AuthFailed, Forbidden
  6. from app.libs.scope import is_in_scope
  7. auth = HTTPBasicAuth(scheme='JWT')
  8. User = namedtuple('User', ['uid'])
  9. @auth.verify_password
  10. def verify_password(token, password):
  11. user_info = verify_auth_token(token)
  12. if not user_info:
  13. return False
  14. else:
  15. g.user = user_info
  16. return True
  17. def verify_auth_token(token):
  18. s = Serializer(current_app.config['SECRET_KEY'])
  19. try:
  20. data = s.loads(token)
  21. except SignatureExpired:
  22. raise AuthFailed(message='token无效', code=1003)
  23. except BadSignature:
  24. raise AuthFailed(message='token过期', code=1002)
  25. uid = data['uid']
  26. allow = is_in_scope(request.endpoint)
  27. if not allow:
  28. raise Forbidden()
  29. return User(uid)