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.

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