wraps.py 3.5 KB

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