workspace.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import logging
  2. from flask import request
  3. from flask_login import current_user
  4. from flask_restful import Resource, fields, inputs, marshal, marshal_with, reqparse
  5. import services
  6. from controllers.console import api
  7. from controllers.console.admin import admin_required
  8. from controllers.console.datasets.error import (
  9. FileTooLargeError,
  10. NoFileUploadedError,
  11. TooManyFilesError,
  12. UnsupportedFileTypeError,
  13. )
  14. from controllers.console.error import AccountNotLinkTenantError
  15. from controllers.console.setup import setup_required
  16. from controllers.console.wraps import account_initialization_required, cloud_edition_billing_resource_check
  17. from extensions.ext_database import db
  18. from libs.helper import TimestampField
  19. from libs.login import login_required
  20. from models.account import Tenant
  21. from services.account_service import TenantService
  22. from services.file_service import FileService
  23. from services.workspace_service import WorkspaceService
  24. provider_fields = {
  25. 'provider_name': fields.String,
  26. 'provider_type': fields.String,
  27. 'is_valid': fields.Boolean,
  28. 'token_is_set': fields.Boolean,
  29. }
  30. tenant_fields = {
  31. 'id': fields.String,
  32. 'name': fields.String,
  33. 'plan': fields.String,
  34. 'status': fields.String,
  35. 'created_at': TimestampField,
  36. 'role': fields.String,
  37. 'in_trial': fields.Boolean,
  38. 'trial_end_reason': fields.String,
  39. 'custom_config': fields.Raw(attribute='custom_config'),
  40. }
  41. tenants_fields = {
  42. 'id': fields.String,
  43. 'name': fields.String,
  44. 'plan': fields.String,
  45. 'status': fields.String,
  46. 'created_at': TimestampField,
  47. 'current': fields.Boolean
  48. }
  49. workspace_fields = {
  50. 'id': fields.String,
  51. 'name': fields.String,
  52. 'status': fields.String,
  53. 'created_at': TimestampField
  54. }
  55. class TenantListApi(Resource):
  56. @setup_required
  57. @login_required
  58. @account_initialization_required
  59. def get(self):
  60. tenants = TenantService.get_join_tenants(current_user)
  61. for tenant in tenants:
  62. if tenant.id == current_user.current_tenant_id:
  63. tenant.current = True # Set current=True for current tenant
  64. return {'workspaces': marshal(tenants, tenants_fields)}, 200
  65. class WorkspaceListApi(Resource):
  66. @setup_required
  67. @admin_required
  68. def get(self):
  69. parser = reqparse.RequestParser()
  70. parser.add_argument('page', type=inputs.int_range(1, 99999), required=False, default=1, location='args')
  71. parser.add_argument('limit', type=inputs.int_range(1, 100), required=False, default=20, location='args')
  72. args = parser.parse_args()
  73. tenants = db.session.query(Tenant).order_by(Tenant.created_at.desc())\
  74. .paginate(page=args['page'], per_page=args['limit'])
  75. has_more = False
  76. if len(tenants.items) == args['limit']:
  77. current_page_first_tenant = tenants[-1]
  78. rest_count = db.session.query(Tenant).filter(
  79. Tenant.created_at < current_page_first_tenant.created_at,
  80. Tenant.id != current_page_first_tenant.id
  81. ).count()
  82. if rest_count > 0:
  83. has_more = True
  84. total = db.session.query(Tenant).count()
  85. return {
  86. 'data': marshal(tenants.items, workspace_fields),
  87. 'has_more': has_more,
  88. 'limit': args['limit'],
  89. 'page': args['page'],
  90. 'total': total
  91. }, 200
  92. class TenantApi(Resource):
  93. @setup_required
  94. @login_required
  95. @account_initialization_required
  96. @marshal_with(tenant_fields)
  97. def get(self):
  98. if request.path == '/info':
  99. logging.warning('Deprecated URL /info was used.')
  100. tenant = current_user.current_tenant
  101. return WorkspaceService.get_tenant_info(tenant), 200
  102. class SwitchWorkspaceApi(Resource):
  103. @setup_required
  104. @login_required
  105. @account_initialization_required
  106. def post(self):
  107. parser = reqparse.RequestParser()
  108. parser.add_argument('tenant_id', type=str, required=True, location='json')
  109. args = parser.parse_args()
  110. # check if tenant_id is valid, 403 if not
  111. try:
  112. TenantService.switch_tenant(current_user, args['tenant_id'])
  113. except Exception:
  114. raise AccountNotLinkTenantError("Account not link tenant")
  115. new_tenant = db.session.query(Tenant).get(args['tenant_id']) # Get new tenant
  116. return {'result': 'success', 'new_tenant': marshal(WorkspaceService.get_tenant_info(new_tenant), tenant_fields)}
  117. class CustomConfigWorkspaceApi(Resource):
  118. @setup_required
  119. @login_required
  120. @account_initialization_required
  121. @cloud_edition_billing_resource_check('workspace_custom')
  122. def post(self):
  123. parser = reqparse.RequestParser()
  124. parser.add_argument('remove_webapp_brand', type=bool, location='json')
  125. parser.add_argument('replace_webapp_logo', type=str, location='json')
  126. args = parser.parse_args()
  127. custom_config_dict = {
  128. 'remove_webapp_brand': args['remove_webapp_brand'],
  129. 'replace_webapp_logo': args['replace_webapp_logo'],
  130. }
  131. tenant = db.session.query(Tenant).filter(Tenant.id == current_user.current_tenant_id).one_or_404()
  132. tenant.custom_config_dict = custom_config_dict
  133. db.session.commit()
  134. return {'result': 'success', 'tenant': marshal(WorkspaceService.get_tenant_info(tenant), tenant_fields)}
  135. class WebappLogoWorkspaceApi(Resource):
  136. @setup_required
  137. @login_required
  138. @account_initialization_required
  139. @cloud_edition_billing_resource_check('workspace_custom')
  140. def post(self):
  141. # get file from request
  142. file = request.files['file']
  143. # check file
  144. if 'file' not in request.files:
  145. raise NoFileUploadedError()
  146. if len(request.files) > 1:
  147. raise TooManyFilesError()
  148. extension = file.filename.split('.')[-1]
  149. if extension.lower() not in ['svg', 'png']:
  150. raise UnsupportedFileTypeError()
  151. try:
  152. upload_file = FileService.upload_file(file, current_user, True)
  153. except services.errors.file.FileTooLargeError as file_too_large_error:
  154. raise FileTooLargeError(file_too_large_error.description)
  155. except services.errors.file.UnsupportedFileTypeError:
  156. raise UnsupportedFileTypeError()
  157. return { 'id': upload_file.id }, 201
  158. api.add_resource(TenantListApi, '/workspaces') # GET for getting all tenants
  159. api.add_resource(WorkspaceListApi, '/all-workspaces') # GET for getting all tenants
  160. api.add_resource(TenantApi, '/workspaces/current', endpoint='workspaces_current') # GET for getting current tenant info
  161. api.add_resource(TenantApi, '/info', endpoint='info') # Deprecated
  162. api.add_resource(SwitchWorkspaceApi, '/workspaces/switch') # POST for switching tenant
  163. api.add_resource(CustomConfigWorkspaceApi, '/workspaces/custom-config')
  164. api.add_resource(WebappLogoWorkspaceApi, '/workspaces/custom-config/webapp-logo/upload')