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.

installed_app.py 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import logging
  2. from typing import Any
  3. from flask import request
  4. from flask_restx import Resource, inputs, marshal_with, reqparse
  5. from sqlalchemy import and_
  6. from werkzeug.exceptions import BadRequest, Forbidden, NotFound
  7. from controllers.console import api
  8. from controllers.console.explore.wraps import InstalledAppResource
  9. from controllers.console.wraps import account_initialization_required, cloud_edition_billing_resource_check
  10. from extensions.ext_database import db
  11. from fields.installed_app_fields import installed_app_list_fields
  12. from libs.datetime_utils import naive_utc_now
  13. from libs.login import current_user, login_required
  14. from models import Account, App, InstalledApp, RecommendedApp
  15. from services.account_service import TenantService
  16. from services.app_service import AppService
  17. from services.enterprise.enterprise_service import EnterpriseService
  18. from services.feature_service import FeatureService
  19. logger = logging.getLogger(__name__)
  20. class InstalledAppsListApi(Resource):
  21. @login_required
  22. @account_initialization_required
  23. @marshal_with(installed_app_list_fields)
  24. def get(self):
  25. app_id = request.args.get("app_id", default=None, type=str)
  26. if not isinstance(current_user, Account):
  27. raise ValueError("current_user must be an Account instance")
  28. current_tenant_id = current_user.current_tenant_id
  29. if app_id:
  30. installed_apps = (
  31. db.session.query(InstalledApp)
  32. .where(and_(InstalledApp.tenant_id == current_tenant_id, InstalledApp.app_id == app_id))
  33. .all()
  34. )
  35. else:
  36. installed_apps = db.session.query(InstalledApp).where(InstalledApp.tenant_id == current_tenant_id).all()
  37. if current_user.current_tenant is None:
  38. raise ValueError("current_user.current_tenant must not be None")
  39. current_user.role = TenantService.get_user_role(current_user, current_user.current_tenant)
  40. installed_app_list: list[dict[str, Any]] = [
  41. {
  42. "id": installed_app.id,
  43. "app": installed_app.app,
  44. "app_owner_tenant_id": installed_app.app_owner_tenant_id,
  45. "is_pinned": installed_app.is_pinned,
  46. "last_used_at": installed_app.last_used_at,
  47. "editable": current_user.role in {"owner", "admin"},
  48. "uninstallable": current_tenant_id == installed_app.app_owner_tenant_id,
  49. }
  50. for installed_app in installed_apps
  51. if installed_app.app is not None
  52. ]
  53. # filter out apps that user doesn't have access to
  54. if FeatureService.get_system_features().webapp_auth.enabled:
  55. user_id = current_user.id
  56. app_ids = [installed_app["app"].id for installed_app in installed_app_list]
  57. webapp_settings = EnterpriseService.WebAppAuth.batch_get_app_access_mode_by_id(app_ids)
  58. # Pre-filter out apps without setting or with sso_verified
  59. filtered_installed_apps = []
  60. app_id_to_app_code = {}
  61. for installed_app in installed_app_list:
  62. app_id = installed_app["app"].id
  63. webapp_setting = webapp_settings.get(app_id)
  64. if not webapp_setting or webapp_setting.access_mode == "sso_verified":
  65. continue
  66. app_code = AppService.get_app_code_by_id(str(app_id))
  67. app_id_to_app_code[app_id] = app_code
  68. filtered_installed_apps.append(installed_app)
  69. app_codes = list(app_id_to_app_code.values())
  70. # Batch permission check
  71. permissions = EnterpriseService.WebAppAuth.batch_is_user_allowed_to_access_webapps(
  72. user_id=user_id,
  73. app_codes=app_codes,
  74. )
  75. # Keep only allowed apps
  76. res = []
  77. for installed_app in filtered_installed_apps:
  78. app_id = installed_app["app"].id
  79. app_code = app_id_to_app_code[app_id]
  80. if permissions.get(app_code):
  81. res.append(installed_app)
  82. installed_app_list = res
  83. logger.debug("installed_app_list: %s, user_id: %s", installed_app_list, user_id)
  84. installed_app_list.sort(
  85. key=lambda app: (
  86. -app["is_pinned"],
  87. app["last_used_at"] is None,
  88. -app["last_used_at"].timestamp() if app["last_used_at"] is not None else 0,
  89. )
  90. )
  91. return {"installed_apps": installed_app_list}
  92. @login_required
  93. @account_initialization_required
  94. @cloud_edition_billing_resource_check("apps")
  95. def post(self):
  96. parser = reqparse.RequestParser()
  97. parser.add_argument("app_id", type=str, required=True, help="Invalid app_id")
  98. args = parser.parse_args()
  99. recommended_app = db.session.query(RecommendedApp).where(RecommendedApp.app_id == args["app_id"]).first()
  100. if recommended_app is None:
  101. raise NotFound("App not found")
  102. if not isinstance(current_user, Account):
  103. raise ValueError("current_user must be an Account instance")
  104. current_tenant_id = current_user.current_tenant_id
  105. app = db.session.query(App).where(App.id == args["app_id"]).first()
  106. if app is None:
  107. raise NotFound("App not found")
  108. if not app.is_public:
  109. raise Forbidden("You can't install a non-public app")
  110. installed_app = (
  111. db.session.query(InstalledApp)
  112. .where(and_(InstalledApp.app_id == args["app_id"], InstalledApp.tenant_id == current_tenant_id))
  113. .first()
  114. )
  115. if installed_app is None:
  116. # todo: position
  117. recommended_app.install_count += 1
  118. new_installed_app = InstalledApp(
  119. app_id=args["app_id"],
  120. tenant_id=current_tenant_id,
  121. app_owner_tenant_id=app.tenant_id,
  122. is_pinned=False,
  123. last_used_at=naive_utc_now(),
  124. )
  125. db.session.add(new_installed_app)
  126. db.session.commit()
  127. return {"message": "App installed successfully"}
  128. class InstalledAppApi(InstalledAppResource):
  129. """
  130. update and delete an installed app
  131. use InstalledAppResource to apply default decorators and get installed_app
  132. """
  133. def delete(self, installed_app):
  134. if not isinstance(current_user, Account):
  135. raise ValueError("current_user must be an Account instance")
  136. if installed_app.app_owner_tenant_id == current_user.current_tenant_id:
  137. raise BadRequest("You can't uninstall an app owned by the current tenant")
  138. db.session.delete(installed_app)
  139. db.session.commit()
  140. return {"result": "success", "message": "App uninstalled successfully"}, 204
  141. def patch(self, installed_app):
  142. parser = reqparse.RequestParser()
  143. parser.add_argument("is_pinned", type=inputs.boolean)
  144. args = parser.parse_args()
  145. commit_args = False
  146. if "is_pinned" in args:
  147. installed_app.is_pinned = args["is_pinned"]
  148. commit_args = True
  149. if commit_args:
  150. db.session.commit()
  151. return {"result": "success", "message": "App info updated successfully"}
  152. api.add_resource(InstalledAppsListApi, "/installed-apps")
  153. api.add_resource(InstalledAppApi, "/installed-apps/<uuid:installed_app_id>")