workspace.py 7.8 KB

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