workspace.py 6.9 KB

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