You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

workspace.py 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import logging
  2. from flask import request
  3. from flask_login import current_user
  4. from flask_restx import Resource, fields, inputs, marshal, marshal_with, reqparse
  5. from sqlalchemy import select
  6. from werkzeug.exceptions import Unauthorized
  7. import services
  8. from controllers.common.errors import (
  9. FilenameNotExistsError,
  10. FileTooLargeError,
  11. NoFileUploadedError,
  12. TooManyFilesError,
  13. UnsupportedFileTypeError,
  14. )
  15. from controllers.console import api
  16. from controllers.console.admin import admin_required
  17. from controllers.console.error import AccountNotLinkTenantError
  18. from controllers.console.wraps import (
  19. account_initialization_required,
  20. cloud_edition_billing_resource_check,
  21. setup_required,
  22. )
  23. from extensions.ext_database import db
  24. from libs.helper import TimestampField
  25. from libs.login import login_required
  26. from models.account import Tenant, TenantStatus
  27. from services.account_service import TenantService
  28. from services.feature_service import FeatureService
  29. from services.file_service import FileService
  30. from services.workspace_service import WorkspaceService
  31. logger = logging.getLogger(__name__)
  32. provider_fields = {
  33. "provider_name": fields.String,
  34. "provider_type": fields.String,
  35. "is_valid": fields.Boolean,
  36. "token_is_set": fields.Boolean,
  37. }
  38. tenant_fields = {
  39. "id": fields.String,
  40. "name": fields.String,
  41. "plan": fields.String,
  42. "status": fields.String,
  43. "created_at": TimestampField,
  44. "role": fields.String,
  45. "in_trial": fields.Boolean,
  46. "trial_end_reason": fields.String,
  47. "custom_config": fields.Raw(attribute="custom_config"),
  48. }
  49. tenants_fields = {
  50. "id": fields.String,
  51. "name": fields.String,
  52. "plan": fields.String,
  53. "status": fields.String,
  54. "created_at": TimestampField,
  55. "current": fields.Boolean,
  56. }
  57. workspace_fields = {"id": fields.String, "name": fields.String, "status": fields.String, "created_at": TimestampField}
  58. class TenantListApi(Resource):
  59. @setup_required
  60. @login_required
  61. @account_initialization_required
  62. def get(self):
  63. tenants = TenantService.get_join_tenants(current_user)
  64. tenant_dicts = []
  65. for tenant in tenants:
  66. features = FeatureService.get_features(tenant.id)
  67. # Create a dictionary with tenant attributes
  68. tenant_dict = {
  69. "id": tenant.id,
  70. "name": tenant.name,
  71. "status": tenant.status,
  72. "created_at": tenant.created_at,
  73. "plan": features.billing.subscription.plan if features.billing.enabled else "sandbox",
  74. "current": tenant.id == current_user.current_tenant_id,
  75. }
  76. tenant_dicts.append(tenant_dict)
  77. return {"workspaces": marshal(tenant_dicts, tenants_fields)}, 200
  78. class WorkspaceListApi(Resource):
  79. @setup_required
  80. @admin_required
  81. def get(self):
  82. parser = reqparse.RequestParser()
  83. parser.add_argument("page", type=inputs.int_range(1, 99999), required=False, default=1, location="args")
  84. parser.add_argument("limit", type=inputs.int_range(1, 100), required=False, default=20, location="args")
  85. args = parser.parse_args()
  86. stmt = select(Tenant).order_by(Tenant.created_at.desc())
  87. tenants = db.paginate(select=stmt, page=args["page"], per_page=args["limit"], error_out=False)
  88. has_more = False
  89. if tenants.has_next:
  90. has_more = True
  91. return {
  92. "data": marshal(tenants.items, workspace_fields),
  93. "has_more": has_more,
  94. "limit": args["limit"],
  95. "page": args["page"],
  96. "total": tenants.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. logger.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. if new_tenant is None:
  132. raise ValueError("Tenant not found")
  133. return {"result": "success", "new_tenant": marshal(WorkspaceService.get_tenant_info(new_tenant), tenant_fields)}
  134. class CustomConfigWorkspaceApi(Resource):
  135. @setup_required
  136. @login_required
  137. @account_initialization_required
  138. @cloud_edition_billing_resource_check("workspace_custom")
  139. def post(self):
  140. parser = reqparse.RequestParser()
  141. parser.add_argument("remove_webapp_brand", type=bool, location="json")
  142. parser.add_argument("replace_webapp_logo", type=str, location="json")
  143. args = parser.parse_args()
  144. tenant = db.get_or_404(Tenant, current_user.current_tenant_id)
  145. custom_config_dict = {
  146. "remove_webapp_brand": args["remove_webapp_brand"],
  147. "replace_webapp_logo": args["replace_webapp_logo"]
  148. if args["replace_webapp_logo"] is not None
  149. else tenant.custom_config_dict.get("replace_webapp_logo"),
  150. }
  151. tenant.custom_config_dict = custom_config_dict
  152. db.session.commit()
  153. return {"result": "success", "tenant": marshal(WorkspaceService.get_tenant_info(tenant), tenant_fields)}
  154. class WebappLogoWorkspaceApi(Resource):
  155. @setup_required
  156. @login_required
  157. @account_initialization_required
  158. @cloud_edition_billing_resource_check("workspace_custom")
  159. def post(self):
  160. # check file
  161. if "file" not in request.files:
  162. raise NoFileUploadedError()
  163. if len(request.files) > 1:
  164. raise TooManyFilesError()
  165. # get file from request
  166. file = request.files["file"]
  167. if not file.filename:
  168. raise FilenameNotExistsError
  169. extension = file.filename.split(".")[-1]
  170. if extension.lower() not in {"svg", "png"}:
  171. raise UnsupportedFileTypeError()
  172. try:
  173. upload_file = FileService.upload_file(
  174. filename=file.filename,
  175. content=file.read(),
  176. mimetype=file.mimetype,
  177. user=current_user,
  178. )
  179. except services.errors.file.FileTooLargeError as file_too_large_error:
  180. raise FileTooLargeError(file_too_large_error.description)
  181. except services.errors.file.UnsupportedFileTypeError:
  182. raise UnsupportedFileTypeError()
  183. return {"id": upload_file.id}, 201
  184. class WorkspaceInfoApi(Resource):
  185. @setup_required
  186. @login_required
  187. @account_initialization_required
  188. # Change workspace name
  189. def post(self):
  190. parser = reqparse.RequestParser()
  191. parser.add_argument("name", type=str, required=True, location="json")
  192. args = parser.parse_args()
  193. tenant = db.get_or_404(Tenant, current_user.current_tenant_id)
  194. tenant.name = args["name"]
  195. db.session.commit()
  196. return {"result": "success", "tenant": marshal(WorkspaceService.get_tenant_info(tenant), tenant_fields)}
  197. api.add_resource(TenantListApi, "/workspaces") # GET for getting all tenants
  198. api.add_resource(WorkspaceListApi, "/all-workspaces") # GET for getting all tenants
  199. api.add_resource(TenantApi, "/workspaces/current", endpoint="workspaces_current") # GET for getting current tenant info
  200. api.add_resource(TenantApi, "/info", endpoint="info") # Deprecated
  201. api.add_resource(SwitchWorkspaceApi, "/workspaces/switch") # POST for switching tenant
  202. api.add_resource(CustomConfigWorkspaceApi, "/workspaces/custom-config")
  203. api.add_resource(WebappLogoWorkspaceApi, "/workspaces/custom-config/webapp-logo/upload")
  204. api.add_resource(WorkspaceInfoApi, "/workspaces/info") # POST for changing workspace info