data_source_bearer_auth.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from flask_login import current_user
  2. from flask_restful import Resource, reqparse
  3. from werkzeug.exceptions import Forbidden
  4. from controllers.console import api
  5. from controllers.console.auth.error import ApiKeyAuthFailedError
  6. from libs.login import login_required
  7. from services.auth.api_key_auth_service import ApiKeyAuthService
  8. from ..setup import setup_required
  9. from ..wraps import account_initialization_required
  10. class ApiKeyAuthDataSource(Resource):
  11. @setup_required
  12. @login_required
  13. @account_initialization_required
  14. def get(self):
  15. # The role of the current user in the table must be admin or owner
  16. if not current_user.is_admin_or_owner:
  17. raise Forbidden()
  18. data_source_api_key_bindings = ApiKeyAuthService.get_provider_auth_list(current_user.current_tenant_id)
  19. if data_source_api_key_bindings:
  20. return {
  21. 'settings': [data_source_api_key_binding.to_dict() for data_source_api_key_binding in
  22. data_source_api_key_bindings]}
  23. return {'settings': []}
  24. class ApiKeyAuthDataSourceBinding(Resource):
  25. @setup_required
  26. @login_required
  27. @account_initialization_required
  28. def post(self):
  29. # The role of the current user in the table must be admin or owner
  30. if not current_user.is_admin_or_owner:
  31. raise Forbidden()
  32. parser = reqparse.RequestParser()
  33. parser.add_argument('category', type=str, required=True, nullable=False, location='json')
  34. parser.add_argument('provider', type=str, required=True, nullable=False, location='json')
  35. parser.add_argument('credentials', type=dict, required=True, nullable=False, location='json')
  36. args = parser.parse_args()
  37. ApiKeyAuthService.validate_api_key_auth_args(args)
  38. try:
  39. ApiKeyAuthService.create_provider_auth(current_user.current_tenant_id, args)
  40. except Exception as e:
  41. raise ApiKeyAuthFailedError(str(e))
  42. return {'result': 'success'}, 200
  43. class ApiKeyAuthDataSourceBindingDelete(Resource):
  44. @setup_required
  45. @login_required
  46. @account_initialization_required
  47. def delete(self, binding_id):
  48. # The role of the current user in the table must be admin or owner
  49. if not current_user.is_admin_or_owner:
  50. raise Forbidden()
  51. ApiKeyAuthService.delete_provider_auth(current_user.current_tenant_id, binding_id)
  52. return {'result': 'success'}, 200
  53. api.add_resource(ApiKeyAuthDataSource, '/api-key-auth/data-source')
  54. api.add_resource(ApiKeyAuthDataSourceBinding, '/api-key-auth/data-source/binding')
  55. api.add_resource(ApiKeyAuthDataSourceBindingDelete, '/api-key-auth/data-source/<uuid:binding_id>')