workspace.py 6.9 KB

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