workspace.py 8.1 KB

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