From d3a283232f9404bdea3b1fd68d09d7f8a4c2cbcc Mon Sep 17 00:00:00 2001
From: fit2bot <68588906+fit2bot@users.noreply.github.com>
Date: Wed, 18 Oct 2023 14:10:24 +0800
Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=20xpack=20license=20?=
 =?UTF-8?q?=E6=A3=80=E6=9F=A5=20(#11885)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: ibuler <ibuler@qq.com>
---
 .../models/automations/push_account.py        |  4 ++--
 apps/acls/serializers/base.py                 |  4 ++--
 apps/assets/const/base.py                     |  5 ++--
 apps/assets/const/protocol.py                 |  2 +-
 apps/jumpserver/settings/_xpack.py            | 12 +++++++++-
 apps/jumpserver/utils.py                      | 23 -------------------
 apps/settings/api/public.py                   |  5 ++--
 apps/terminal/api/applet/applet.py            |  2 +-
 apps/terminal/connect_methods.py              |  4 ++--
 apps/users/views/profile/reset.py             |  2 +-
 10 files changed, 24 insertions(+), 39 deletions(-)

diff --git a/apps/accounts/models/automations/push_account.py b/apps/accounts/models/automations/push_account.py
index 84aa1bb6e..99bbda01d 100644
--- a/apps/accounts/models/automations/push_account.py
+++ b/apps/accounts/models/automations/push_account.py
@@ -1,9 +1,9 @@
+from django.conf import settings
 from django.db import models
 from django.utils.translation import gettext_lazy as _
 
 from accounts.const import AutomationTypes
 from accounts.models import Account
-from jumpserver.utils import has_valid_xpack_license
 from .base import AccountBaseAutomation
 from .change_secret import ChangeSecretMixin
 
@@ -41,7 +41,7 @@ class PushAccountAutomation(ChangeSecretMixin, AccountBaseAutomation):
 
     def save(self, *args, **kwargs):
         self.type = AutomationTypes.push_account
-        if not has_valid_xpack_license():
+        if not settings.XPACK_LICENSE_IS_VALID:
             self.is_periodic = False
         super().save(*args, **kwargs)
 
diff --git a/apps/acls/serializers/base.py b/apps/acls/serializers/base.py
index 4c2d80bfc..09f75bf42 100644
--- a/apps/acls/serializers/base.py
+++ b/apps/acls/serializers/base.py
@@ -1,9 +1,9 @@
+from django.conf import settings
 from django.utils.translation import gettext_lazy as _
 from rest_framework import serializers
 
 from acls.models.base import BaseACL
 from common.serializers.fields import JSONManyToManyField, LabeledChoiceField
-from jumpserver.utils import has_valid_xpack_license
 from orgs.models import Organization
 from ..const import ActionChoices
 
@@ -68,7 +68,7 @@ class ActionAclSerializer(serializers.Serializer):
         field_action = self.fields.get("action")
         if not field_action:
             return
-        if not has_valid_xpack_license():
+        if not settings.XPACK_LICENSE_IS_VALID:
             field_action._choices.pop(ActionChoices.review, None)
         for choice in self.Meta.action_choices_exclude:
             field_action._choices.pop(choice, None)
diff --git a/apps/assets/const/base.py b/apps/assets/const/base.py
index 66c991caa..a77691c1b 100644
--- a/apps/assets/const/base.py
+++ b/apps/assets/const/base.py
@@ -1,9 +1,8 @@
+from django.conf import settings
 from django.db import models
 from django.db.models import TextChoices
 from django.utils.translation import gettext_lazy as _
 
-from jumpserver.utils import has_valid_xpack_license
-
 
 class Type:
     def __init__(self, label, value):
@@ -113,7 +112,7 @@ class BaseType(TextChoices):
 
     @classmethod
     def get_choices(cls):
-        if not has_valid_xpack_license():
+        if not settings.XPACK_LICENSE_IS_VALID:
             return [
                 (tp.value, tp.label)
                 for tp in cls.get_community_types()
diff --git a/apps/assets/const/protocol.py b/apps/assets/const/protocol.py
index 9976596b2..5aea2daec 100644
--- a/apps/assets/const/protocol.py
+++ b/apps/assets/const/protocol.py
@@ -276,7 +276,7 @@ class Protocol(ChoicesMixin, models.TextChoices):
                 }
             }
         }
-        if settings.XPACK_ENABLED:
+        if settings.XPACK_LICENSE_IS_VALID:
             choices = protocols[cls.chatgpt]['setting']['api_mode']['choices']
             choices.extend([
                 ('gpt-4', 'GPT-4'),
diff --git a/apps/jumpserver/settings/_xpack.py b/apps/jumpserver/settings/_xpack.py
index 9f4319a35..6e43c7501 100644
--- a/apps/jumpserver/settings/_xpack.py
+++ b/apps/jumpserver/settings/_xpack.py
@@ -1,17 +1,27 @@
 # -*- coding: utf-8 -*-
 #
 
+import datetime
 import os
-from .. import const
+
 from .base import INSTALLED_APPS, TEMPLATES
+from .. import const
+
+current_year = datetime.datetime.now().year
+corporation = f'FIT2CLOUD 飞致云 © 2014-{current_year}'
 
 XPACK_DIR = os.path.join(const.BASE_DIR, 'xpack')
 XPACK_ENABLED = os.path.isdir(XPACK_DIR)
 XPACK_TEMPLATES_DIR = []
 XPACK_CONTEXT_PROCESSOR = []
+XPACK_LICENSE_IS_VALID = False
+XPACK_LICENSE_INFO = {
+    'corporation': corporation,
+}
 
 if XPACK_ENABLED:
     from xpack.utils import get_xpack_templates_dir, get_xpack_context_processor
+
     INSTALLED_APPS.insert(0, 'xpack.apps.XpackConfig')
     XPACK_TEMPLATES_DIR = get_xpack_templates_dir(const.BASE_DIR)
     XPACK_CONTEXT_PROCESSOR = get_xpack_context_processor()
diff --git a/apps/jumpserver/utils.py b/apps/jumpserver/utils.py
index 24f2b10d7..350c9b346 100644
--- a/apps/jumpserver/utils.py
+++ b/apps/jumpserver/utils.py
@@ -1,9 +1,7 @@
 # -*- coding: utf-8 -*-
 #
-from datetime import datetime
 from functools import partial
 
-from django.conf import settings
 from werkzeug.local import LocalProxy
 
 from common.local import thread_local
@@ -21,25 +19,4 @@ def get_current_request():
     return _find('current_request')
 
 
-def has_valid_xpack_license():
-    if not settings.XPACK_ENABLED:
-        return False
-    from xpack.plugins.license.models import License
-    return License.has_valid_license()
-
-
-def get_xpack_license_info() -> dict:
-    if has_valid_xpack_license():
-        from xpack.plugins.license.models import License
-        info = License.get_license_detail()
-        corporation = info.get('corporation', '')
-    else:
-        current_year = datetime.now().year
-        corporation = f'FIT2CLOUD 飞致云 © 2014-{current_year}'
-    info = {
-        'corporation': corporation
-    }
-    return info
-
-
 current_request = LocalProxy(partial(_find, 'current_request'))
diff --git a/apps/settings/api/public.py b/apps/settings/api/public.py
index 85c56bdbf..81abfeb99 100644
--- a/apps/settings/api/public.py
+++ b/apps/settings/api/public.py
@@ -5,7 +5,6 @@ from rest_framework.permissions import AllowAny
 from authentication.permissions import IsValidUserOrConnectionToken
 from common.utils import get_logger, lazyproperty
 from common.utils.timezone import local_now
-from jumpserver.utils import has_valid_xpack_license, get_xpack_license_info
 from .. import serializers
 from ..utils import get_interface_setting_or_default
 
@@ -36,8 +35,8 @@ class PublicSettingApi(OpenPublicSettingApi):
     def get_object(self):
         values = super().get_object()
         values.update({
-            "XPACK_LICENSE_IS_VALID": has_valid_xpack_license(),
-            "XPACK_LICENSE_INFO": get_xpack_license_info(),
+            "XPACK_LICENSE_IS_VALID": settings.XPACK_LICENSE_IS_VALID,
+            "XPACK_LICENSE_INFO": settings.XPACK_LICENSE_INFO,
             "PASSWORD_RULE": {
                 'SECURITY_PASSWORD_MIN_LENGTH': settings.SECURITY_PASSWORD_MIN_LENGTH,
                 'SECURITY_ADMIN_USER_PASSWORD_MIN_LENGTH': settings.SECURITY_ADMIN_USER_PASSWORD_MIN_LENGTH,
diff --git a/apps/terminal/api/applet/applet.py b/apps/terminal/api/applet/applet.py
index 90b4f162c..9e656487b 100644
--- a/apps/terminal/api/applet/applet.py
+++ b/apps/terminal/api/applet/applet.py
@@ -61,7 +61,7 @@ class DownloadUploadMixin:
         update = request.query_params.get('update')
 
         is_enterprise = manifest.get('edition') == Applet.Edition.enterprise
-        if is_enterprise and not settings.XPACK_ENABLED:
+        if is_enterprise and not settings.XPACK_LICENSE_IS_VALID:
             raise ValidationError({'error': _('This is enterprise edition applet')})
 
         instance = Applet.objects.filter(name=name).first()
diff --git a/apps/terminal/connect_methods.py b/apps/terminal/connect_methods.py
index 8672001c0..9c7ee989a 100644
--- a/apps/terminal/connect_methods.py
+++ b/apps/terminal/connect_methods.py
@@ -75,7 +75,7 @@ class NativeClient(TextChoices):
         xpack_protocols = Protocol.xpack_protocols()
 
         for protocol, _clients in clients_map.items():
-            if not settings.XPACK_ENABLED and protocol in xpack_protocols:
+            if not settings.XPACK_LICENSE_IS_VALID and protocol in xpack_protocols:
                 continue
             if isinstance(_clients, dict):
                 if os == 'all':
@@ -83,7 +83,7 @@ class NativeClient(TextChoices):
                 else:
                     _clients = _clients.get(os, _clients['default'])
             for client in _clients:
-                if not settings.XPACK_ENABLED and client in cls.xpack_methods():
+                if not settings.XPACK_LICENSE_IS_VALID and client in cls.xpack_methods():
                     continue
                 methods[protocol].append({
                     'value': client.value,
diff --git a/apps/users/views/profile/reset.py b/apps/users/views/profile/reset.py
index d33681b1b..96d407302 100644
--- a/apps/users/views/profile/reset.py
+++ b/apps/users/views/profile/reset.py
@@ -90,7 +90,7 @@ class UserForgotPasswordView(FormView):
     @staticmethod
     def get_validate_backends_context(has_phone):
         validate_backends = [{'name': _('Email'), 'is_active': True, 'value': 'email'}]
-        if settings.XPACK_ENABLED:
+        if settings.XPACK_LICENSE_IS_VALID:
             if settings.SMS_ENABLED and has_phone:
                 is_active = True
             else: