wraps.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # -*- coding:utf-8 -*-
  2. from datetime import datetime
  3. from functools import wraps
  4. from flask import request, current_app
  5. from flask_login import user_logged_in
  6. from flask_restful import Resource
  7. from werkzeug.exceptions import NotFound, Unauthorized
  8. from libs.login import _get_user
  9. from extensions.ext_database import db
  10. from models.account import Tenant, TenantAccountJoin, Account
  11. from models.model import ApiToken, App
  12. def validate_app_token(view=None):
  13. def decorator(view):
  14. @wraps(view)
  15. def decorated(*args, **kwargs):
  16. api_token = validate_and_get_api_token('app')
  17. app_model = db.session.query(App).filter(App.id == api_token.app_id).first()
  18. if not app_model:
  19. raise NotFound()
  20. if app_model.status != 'normal':
  21. raise NotFound()
  22. if not app_model.enable_api:
  23. raise NotFound()
  24. return view(app_model, None, *args, **kwargs)
  25. return decorated
  26. if view:
  27. return decorator(view)
  28. # if view is None, it means that the decorator is used without parentheses
  29. # use the decorator as a function for method_decorators
  30. return decorator
  31. def validate_dataset_token(view=None):
  32. def decorator(view):
  33. @wraps(view)
  34. def decorated(*args, **kwargs):
  35. api_token = validate_and_get_api_token('dataset')
  36. tenant_account_join = db.session.query(Tenant, TenantAccountJoin) \
  37. .filter(Tenant.id == api_token.tenant_id) \
  38. .filter(TenantAccountJoin.tenant_id == Tenant.id) \
  39. .filter(TenantAccountJoin.role == 'owner') \
  40. .one_or_none()
  41. if tenant_account_join:
  42. tenant, ta = tenant_account_join
  43. account = Account.query.filter_by(id=ta.account_id).first()
  44. # Login admin
  45. if account:
  46. account.current_tenant = tenant
  47. current_app.login_manager._update_request_context_with_user(account)
  48. user_logged_in.send(current_app._get_current_object(), user=_get_user())
  49. else:
  50. raise Unauthorized("Tenant owner account is not exist.")
  51. else:
  52. raise Unauthorized("Tenant is not exist.")
  53. return view(api_token.tenant_id, *args, **kwargs)
  54. return decorated
  55. if view:
  56. return decorator(view)
  57. # if view is None, it means that the decorator is used without parentheses
  58. # use the decorator as a function for method_decorators
  59. return decorator
  60. def validate_and_get_api_token(scope=None):
  61. """
  62. Validate and get API token.
  63. """
  64. auth_header = request.headers.get('Authorization')
  65. if auth_header is None or ' ' not in auth_header:
  66. raise Unauthorized("Authorization header must be provided and start with 'Bearer'")
  67. auth_scheme, auth_token = auth_header.split(None, 1)
  68. auth_scheme = auth_scheme.lower()
  69. if auth_scheme != 'bearer':
  70. raise Unauthorized("Authorization scheme must be 'Bearer'")
  71. api_token = db.session.query(ApiToken).filter(
  72. ApiToken.token == auth_token,
  73. ApiToken.type == scope,
  74. ).first()
  75. if not api_token:
  76. raise Unauthorized("Access token is invalid")
  77. api_token.last_used_at = datetime.utcnow()
  78. db.session.commit()
  79. return api_token
  80. class AppApiResource(Resource):
  81. method_decorators = [validate_app_token]
  82. class DatasetApiResource(Resource):
  83. method_decorators = [validate_dataset_token]