mirror of
https://github.com/jumpserver/jumpserver.git
synced 2025-12-25 13:32:36 +00:00
Compare commits
1 Commits
pr@dev@per
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8131cf1b22 |
@@ -1,4 +1,3 @@
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
@@ -167,7 +166,7 @@ class AccountViewSet(OrgBulkModelViewSet):
|
||||
|
||||
class AccountSecretsViewSet(AccountRecordViewLogMixin, AccountViewSet):
|
||||
"""
|
||||
因为可能要导出所有账号,所以单独建立了一个 viewset
|
||||
因为可能要导出所有账号,所以单独建立了一个 viewset
|
||||
"""
|
||||
serializer_classes = {
|
||||
'default': serializers.AccountSecretSerializer,
|
||||
|
||||
@@ -81,7 +81,4 @@ class IntegrationApplicationViewSet(OrgBulkModelViewSet):
|
||||
remote_addr=get_request_ip(request), service=service.name, service_id=service.id,
|
||||
account=f'{account.name}({account.username})', asset=f'{asset.name}({asset.address})',
|
||||
)
|
||||
|
||||
# 根据配置决定是否返回密码
|
||||
secret = account.secret if settings.SECURITY_ACCOUNT_SECRET_READ else None
|
||||
return Response(data={'id': request.user.id, 'secret': secret})
|
||||
return Response(data={'id': request.user.id, 'secret': account.secret})
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
from django.conf import settings
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_filters import rest_framework as drf_filters
|
||||
from rest_framework import status
|
||||
from rest_framework.decorators import action
|
||||
|
||||
@@ -104,7 +104,7 @@ class AutomationExecutionViewSet(
|
||||
mixins.CreateModelMixin, mixins.ListModelMixin,
|
||||
mixins.RetrieveModelMixin, viewsets.GenericViewSet
|
||||
):
|
||||
search_fields = ('id', 'trigger', 'automation__name')
|
||||
search_fields = ('trigger', 'automation__name')
|
||||
filterset_fields = ('trigger', 'automation_id', 'automation__name')
|
||||
filterset_class = AutomationExecutionFilterSet
|
||||
serializer_class = serializers.AutomationExecutionSerializer
|
||||
|
||||
@@ -234,7 +234,7 @@ class AutomationExecutionFilterSet(DaysExecutionFilterMixin, BaseFilterSet):
|
||||
|
||||
class Meta:
|
||||
model = AutomationExecution
|
||||
fields = ["id", "days", 'trigger', 'automation__name']
|
||||
fields = ["days", 'trigger', 'automation__name']
|
||||
|
||||
|
||||
class PushAccountRecordFilterSet(SecretRecordMixin, UUIDFilterMixin, BaseFilterSet):
|
||||
|
||||
@@ -81,9 +81,7 @@ class VaultModelMixin(models.Model):
|
||||
def mark_secret_save_to_vault(self):
|
||||
self._secret = self._secret_save_to_vault_mark
|
||||
self.skip_history_when_saving = True
|
||||
# Avoid calling overridden `save()` on concrete models (e.g. AccountTemplate)
|
||||
# which may mutate `secret/_secret` again and cause post_save recursion.
|
||||
super(VaultModelMixin, self).save(update_fields=['_secret'])
|
||||
self.save()
|
||||
|
||||
@property
|
||||
def secret_has_save_to_vault(self):
|
||||
|
||||
@@ -14,7 +14,7 @@ from accounts.models import Account, AccountTemplate, GatheredAccount
|
||||
from accounts.tasks import push_accounts_to_assets_task
|
||||
from assets.const import Category, AllTypes
|
||||
from assets.models import Asset
|
||||
from common.serializers import SecretReadableMixin, SecretReadableCheckMixin, CommonBulkModelSerializer
|
||||
from common.serializers import SecretReadableMixin, CommonBulkModelSerializer
|
||||
from common.serializers.fields import ObjectRelatedField, LabeledChoiceField
|
||||
from common.utils import get_logger
|
||||
from .base import BaseAccountSerializer, AuthValidateMixin
|
||||
@@ -341,6 +341,10 @@ class AssetAccountBulkSerializer(
|
||||
|
||||
@staticmethod
|
||||
def _handle_update_create(vd, lookup):
|
||||
ori = Account.objects.filter(**lookup).first()
|
||||
if ori and ori.secret == vd.get('secret'):
|
||||
return ori, False, 'skipped'
|
||||
|
||||
instance, value = Account.objects.update_or_create(defaults=vd, **lookup)
|
||||
state = 'created' if value else 'updated'
|
||||
return instance, True, state
|
||||
@@ -474,7 +478,7 @@ class AssetAccountBulkSerializer(
|
||||
return results
|
||||
|
||||
|
||||
class AccountSecretSerializer(SecretReadableCheckMixin, SecretReadableMixin, AccountSerializer):
|
||||
class AccountSecretSerializer(SecretReadableMixin, AccountSerializer):
|
||||
spec_info = serializers.DictField(label=_('Spec info'), read_only=True)
|
||||
|
||||
class Meta(AccountSerializer.Meta):
|
||||
@@ -487,10 +491,9 @@ class AccountSecretSerializer(SecretReadableCheckMixin, SecretReadableMixin, Acc
|
||||
exclude_backup_fields = [
|
||||
'passphrase', 'push_now', 'params', 'spec_info'
|
||||
]
|
||||
secret_fields = ['secret']
|
||||
|
||||
|
||||
class AccountHistorySerializer(SecretReadableCheckMixin, serializers.ModelSerializer):
|
||||
class AccountHistorySerializer(serializers.ModelSerializer):
|
||||
secret_type = LabeledChoiceField(choices=SecretType.choices, label=_('Secret type'))
|
||||
secret = serializers.CharField(label=_('Secret'), read_only=True)
|
||||
id = serializers.IntegerField(label=_('ID'), source='history_id', read_only=True)
|
||||
@@ -506,7 +509,6 @@ class AccountHistorySerializer(SecretReadableCheckMixin, serializers.ModelSerial
|
||||
'history_user': {'label': _('User')},
|
||||
'history_date': {'label': _('Date')},
|
||||
}
|
||||
secret_fields = ['secret']
|
||||
|
||||
|
||||
class AccountTaskSerializer(serializers.Serializer):
|
||||
|
||||
@@ -2,7 +2,7 @@ from django.utils.translation import gettext_lazy as _
|
||||
from rest_framework import serializers
|
||||
|
||||
from accounts.models import AccountTemplate
|
||||
from common.serializers import SecretReadableMixin, SecretReadableCheckMixin
|
||||
from common.serializers import SecretReadableMixin
|
||||
from common.serializers.fields import ObjectRelatedField
|
||||
from .base import BaseAccountSerializer
|
||||
|
||||
@@ -62,11 +62,10 @@ class AccountDetailTemplateSerializer(AccountTemplateSerializer):
|
||||
fields = AccountTemplateSerializer.Meta.fields + ['spec_info']
|
||||
|
||||
|
||||
class AccountTemplateSecretSerializer(SecretReadableCheckMixin, SecretReadableMixin, AccountDetailTemplateSerializer):
|
||||
class AccountTemplateSecretSerializer(SecretReadableMixin, AccountDetailTemplateSerializer):
|
||||
class Meta(AccountDetailTemplateSerializer.Meta):
|
||||
fields = AccountDetailTemplateSerializer.Meta.fields
|
||||
extra_kwargs = {
|
||||
**AccountDetailTemplateSerializer.Meta.extra_kwargs,
|
||||
'secret': {'write_only': False},
|
||||
}
|
||||
secret_fields = ['secret']
|
||||
|
||||
@@ -79,7 +79,7 @@ class VaultSignalHandler(object):
|
||||
else:
|
||||
vault_client.update(instance)
|
||||
except Exception as e:
|
||||
logger.exception('Vault save failed: %s', e)
|
||||
logger.error('Vault save failed: {}'.format(e))
|
||||
raise VaultException()
|
||||
|
||||
@staticmethod
|
||||
@@ -87,7 +87,7 @@ class VaultSignalHandler(object):
|
||||
try:
|
||||
vault_client.delete(instance)
|
||||
except Exception as e:
|
||||
logger.exception('Vault delete failed: %s', e)
|
||||
logger.error('Vault delete failed: {}'.format(e))
|
||||
raise VaultException()
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from accounts.backends import vault_client
|
||||
from accounts.const import VaultTypeChoices
|
||||
from accounts.models import AccountTemplate, Account
|
||||
from accounts.models import Account, AccountTemplate
|
||||
from common.utils import get_logger
|
||||
from orgs.utils import tmp_to_root_org
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ class BaseManager:
|
||||
self.execution.save()
|
||||
|
||||
def print_summary(self):
|
||||
content = "\nSummary: \n"
|
||||
content = "\nSummery: \n"
|
||||
for k, v in self.summary.items():
|
||||
content += f"\t - {k}: {v}\n"
|
||||
content += "\t - Using: {}s\n".format(self.duration)
|
||||
|
||||
@@ -219,18 +219,8 @@ class RDPFileClientProtocolURLMixin:
|
||||
}
|
||||
})
|
||||
else:
|
||||
if connect_method_dict['type'] == 'virtual_app':
|
||||
endpoint_protocol = 'vnc'
|
||||
token_protocol = 'vnc'
|
||||
data.update({
|
||||
'protocol': 'vnc',
|
||||
})
|
||||
else:
|
||||
endpoint_protocol = connect_method_dict['endpoint_protocol']
|
||||
token_protocol = token.protocol
|
||||
|
||||
endpoint = self.get_smart_endpoint(
|
||||
protocol=endpoint_protocol,
|
||||
protocol=connect_method_dict['endpoint_protocol'],
|
||||
asset=asset
|
||||
)
|
||||
data.update({
|
||||
@@ -246,7 +236,7 @@ class RDPFileClientProtocolURLMixin:
|
||||
},
|
||||
'endpoint': {
|
||||
'host': endpoint.host,
|
||||
'port': endpoint.get_port(token.asset, token_protocol),
|
||||
'port': endpoint.get_port(token.asset, token.protocol),
|
||||
}
|
||||
})
|
||||
return data
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.backends import ModelBackend
|
||||
from django.views import View
|
||||
|
||||
from common.utils import get_logger
|
||||
from users.models import User
|
||||
@@ -65,3 +66,11 @@ class JMSBaseAuthBackend:
|
||||
class JMSModelBackend(JMSBaseAuthBackend, ModelBackend):
|
||||
def user_can_authenticate(self, user):
|
||||
return True
|
||||
|
||||
|
||||
class BaseAuthCallbackClientView(View):
|
||||
http_method_names = ['get']
|
||||
|
||||
def get(self, request):
|
||||
from authentication.views.utils import redirect_to_guard_view
|
||||
return redirect_to_guard_view(query_string='next=client')
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
import django_cas_ng.views
|
||||
from django.urls import path
|
||||
|
||||
from .views import CASLoginView
|
||||
from .views import CASLoginView, CASCallbackClientView
|
||||
|
||||
urlpatterns = [
|
||||
path('login/', CASLoginView.as_view(), name='cas-login'),
|
||||
path('logout/', django_cas_ng.views.LogoutView.as_view(), name='cas-logout'),
|
||||
path('callback/', django_cas_ng.views.CallbackView.as_view(), name='cas-proxy-callback')
|
||||
path('callback/', django_cas_ng.views.CallbackView.as_view(), name='cas-proxy-callback'),
|
||||
path('login/client', CASCallbackClientView.as_view(), name='cas-proxy-callback-client'),
|
||||
]
|
||||
|
||||
@@ -3,6 +3,7 @@ from django.http import HttpResponseRedirect
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_cas_ng.views import LoginView
|
||||
|
||||
from authentication.backends.base import BaseAuthCallbackClientView
|
||||
from authentication.views.mixins import FlashMessageMixin
|
||||
|
||||
__all__ = ['LoginView']
|
||||
@@ -20,3 +21,7 @@ class CASLoginView(LoginView, FlashMessageMixin):
|
||||
return response
|
||||
else:
|
||||
return resp
|
||||
|
||||
|
||||
class CASCallbackClientView(BaseAuthCallbackClientView):
|
||||
pass
|
||||
|
||||
@@ -69,8 +69,6 @@ class AccessTokenAuthentication(authentication.BaseAuthentication):
|
||||
msg = _('Invalid token header. Sign string should not contain invalid characters.')
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
user, header = self.authenticate_credentials(token)
|
||||
if not user:
|
||||
return None
|
||||
after_authenticate_update_date(user)
|
||||
return user, header
|
||||
|
||||
@@ -79,6 +77,10 @@ class AccessTokenAuthentication(authentication.BaseAuthentication):
|
||||
model = get_user_model()
|
||||
user_id = cache.get(token)
|
||||
user = get_object_or_none(model, id=user_id)
|
||||
|
||||
if not user:
|
||||
msg = _('Invalid token or cache refreshed.')
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
return user, None
|
||||
|
||||
def authenticate_header(self, request):
|
||||
@@ -108,7 +110,7 @@ class SessionAuthentication(authentication.SessionAuthentication):
|
||||
user = getattr(request._request, 'user', None)
|
||||
|
||||
# Unauthenticated, CSRF validation not required
|
||||
if not user or not user.is_active or not user.is_valid:
|
||||
if not user or not user.is_active:
|
||||
return None
|
||||
|
||||
try:
|
||||
|
||||
@@ -7,5 +7,6 @@ from . import views
|
||||
urlpatterns = [
|
||||
path('login/', views.OAuth2AuthRequestView.as_view(), name='login'),
|
||||
path('callback/', views.OAuth2AuthCallbackView.as_view(), name='login-callback'),
|
||||
path('callback/client/', views.OAuth2AuthCallbackClientView.as_view(), name='login-callback-client'),
|
||||
path('logout/', views.OAuth2EndSessionView.as_view(), name='logout')
|
||||
]
|
||||
|
||||
@@ -6,7 +6,7 @@ from django.utils.http import urlencode
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views import View
|
||||
|
||||
from authentication.decorators import pre_save_next_to_session, redirect_to_pre_save_next_after_auth
|
||||
from authentication.backends.base import BaseAuthCallbackClientView
|
||||
from authentication.mixins import authenticate
|
||||
from authentication.utils import build_absolute_uri
|
||||
from authentication.views.mixins import FlashMessageMixin
|
||||
@@ -17,14 +17,12 @@ logger = get_logger(__file__)
|
||||
|
||||
class OAuth2AuthRequestView(View):
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request):
|
||||
log_prompt = "Process OAuth2 GET requests: {}"
|
||||
logger.debug(log_prompt.format('Start'))
|
||||
|
||||
request_params = request.GET.dict()
|
||||
request_params.pop('next', None)
|
||||
query = urlencode(request_params)
|
||||
authentication_request_params = request.GET.dict()
|
||||
query = urlencode(authentication_request_params)
|
||||
redirect_uri = build_absolute_uri(
|
||||
request, path=reverse(settings.AUTH_OAUTH2_AUTH_LOGIN_CALLBACK_URL_NAME)
|
||||
)
|
||||
@@ -52,7 +50,6 @@ class OAuth2AuthRequestView(View):
|
||||
class OAuth2AuthCallbackView(View, FlashMessageMixin):
|
||||
http_method_names = ['get', ]
|
||||
|
||||
@redirect_to_pre_save_next_after_auth
|
||||
def get(self, request):
|
||||
""" Processes GET requests. """
|
||||
log_prompt = "Process GET requests [OAuth2AuthCallbackView]: {}"
|
||||
@@ -67,7 +64,9 @@ class OAuth2AuthCallbackView(View, FlashMessageMixin):
|
||||
logger.debug(log_prompt.format('Login: {}'.format(user)))
|
||||
auth.login(self.request, user)
|
||||
logger.debug(log_prompt.format('Redirect'))
|
||||
return HttpResponseRedirect(settings.AUTH_OAUTH2_AUTHENTICATION_REDIRECT_URI)
|
||||
next_url = request.GET.get('next') or settings.AUTH_OAUTH2_AUTHENTICATION_REDIRECT_URI
|
||||
next_url = safe_next_url(next_url, request=request)
|
||||
return HttpResponseRedirect(next_url)
|
||||
else:
|
||||
if getattr(request, 'error_message', ''):
|
||||
response = self.get_failed_response('/', title=_('OAuth2 Error'), msg=request.error_message)
|
||||
@@ -78,6 +77,10 @@ class OAuth2AuthCallbackView(View, FlashMessageMixin):
|
||||
return HttpResponseRedirect(redirect_url)
|
||||
|
||||
|
||||
class OAuth2AuthCallbackClientView(BaseAuthCallbackClientView):
|
||||
pass
|
||||
|
||||
|
||||
class OAuth2EndSessionView(View):
|
||||
http_method_names = ['get', 'post', ]
|
||||
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
from django.core.cache import cache
|
||||
from django.conf import settings
|
||||
|
||||
from oauth2_provider.models import get_application_model
|
||||
|
||||
from .utils import clear_oauth2_authorization_server_view_cache
|
||||
|
||||
__all__ = ['on_oauth2_provider_application_deleted']
|
||||
|
||||
|
||||
Application = get_application_model()
|
||||
|
||||
|
||||
@receiver(post_delete, sender=Application)
|
||||
def on_oauth2_provider_application_deleted(sender, instance, **kwargs):
|
||||
if instance.name == settings.OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME:
|
||||
clear_oauth2_authorization_server_view_cache()
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
from oauth2_provider.models import get_application_model
|
||||
|
||||
from common.utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
def get_or_create_jumpserver_client_application():
|
||||
"""Auto get or create OAuth2 JumpServer Client application."""
|
||||
Application = get_application_model()
|
||||
@@ -19,13 +14,4 @@ def get_or_create_jumpserver_client_application():
|
||||
'skip_authorization': True,
|
||||
}
|
||||
)
|
||||
return application
|
||||
|
||||
|
||||
CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX = 'oauth2_provider_metadata'
|
||||
|
||||
|
||||
def clear_oauth2_authorization_server_view_cache():
|
||||
logger.info("Clearing OAuth2 Authorization Server Metadata view cache")
|
||||
cache_key = f'views.decorators.cache.cache_page.{CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX}.GET*'
|
||||
cache.delete_pattern(cache_key)
|
||||
return application
|
||||
@@ -7,11 +7,11 @@ from django.conf import settings
|
||||
from django.urls import reverse
|
||||
from oauth2_provider.settings import oauth2_settings
|
||||
from typing import List, Dict, Any
|
||||
from .utils import get_or_create_jumpserver_client_application, CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX
|
||||
from .utils import get_or_create_jumpserver_client_application
|
||||
|
||||
|
||||
@method_decorator(csrf_exempt, name='dispatch')
|
||||
@method_decorator(cache_page(timeout=60 * 60 * 24, key_prefix=CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX), name='dispatch')
|
||||
@method_decorator(cache_page(60 * 60), name='dispatch')
|
||||
class OAuthAuthorizationServerView(View):
|
||||
"""
|
||||
OAuth 2.0 Authorization Server Metadata Endpoint
|
||||
|
||||
@@ -15,5 +15,6 @@ from . import views
|
||||
urlpatterns = [
|
||||
path('login/', views.OIDCAuthRequestView.as_view(), name='login'),
|
||||
path('callback/', views.OIDCAuthCallbackView.as_view(), name='login-callback'),
|
||||
path('callback/client/', views.OIDCAuthCallbackClientView.as_view(), name='login-callback-client'),
|
||||
path('logout/', views.OIDCEndSessionView.as_view(), name='logout'),
|
||||
]
|
||||
|
||||
@@ -25,11 +25,11 @@ from django.utils.http import urlencode
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import View
|
||||
|
||||
from authentication.decorators import pre_save_next_to_session, redirect_to_pre_save_next_after_auth
|
||||
from authentication.utils import build_absolute_uri_for_oidc
|
||||
from authentication.views.mixins import FlashMessageMixin
|
||||
from common.utils import safe_next_url
|
||||
from .utils import get_logger
|
||||
from ..base import BaseAuthCallbackClientView
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
@@ -58,7 +58,6 @@ class OIDCAuthRequestView(View):
|
||||
b = base64.urlsafe_b64encode(h)
|
||||
return b.decode('ascii')[:-1]
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request):
|
||||
""" Processes GET requests. """
|
||||
|
||||
@@ -67,9 +66,8 @@ class OIDCAuthRequestView(View):
|
||||
|
||||
# Defines common parameters used to bootstrap the authentication request.
|
||||
logger.debug(log_prompt.format('Construct request params'))
|
||||
request_params = request.GET.dict()
|
||||
request_params.pop('next', None)
|
||||
request_params.update({
|
||||
authentication_request_params = request.GET.dict()
|
||||
authentication_request_params.update({
|
||||
'scope': settings.AUTH_OPENID_SCOPES,
|
||||
'response_type': 'code',
|
||||
'client_id': settings.AUTH_OPENID_CLIENT_ID,
|
||||
@@ -82,7 +80,7 @@ class OIDCAuthRequestView(View):
|
||||
code_verifier = self.gen_code_verifier()
|
||||
code_challenge_method = settings.AUTH_OPENID_CODE_CHALLENGE_METHOD or 'S256'
|
||||
code_challenge = self.gen_code_challenge(code_verifier, code_challenge_method)
|
||||
request_params.update({
|
||||
authentication_request_params.update({
|
||||
'code_challenge_method': code_challenge_method,
|
||||
'code_challenge': code_challenge
|
||||
})
|
||||
@@ -93,7 +91,7 @@ class OIDCAuthRequestView(View):
|
||||
if settings.AUTH_OPENID_USE_STATE:
|
||||
logger.debug(log_prompt.format('Use state'))
|
||||
state = get_random_string(settings.AUTH_OPENID_STATE_LENGTH)
|
||||
request_params.update({'state': state})
|
||||
authentication_request_params.update({'state': state})
|
||||
request.session['oidc_auth_state'] = state
|
||||
|
||||
# Nonces should be used too! In that case the generated nonce is stored both in the
|
||||
@@ -101,12 +99,17 @@ class OIDCAuthRequestView(View):
|
||||
if settings.AUTH_OPENID_USE_NONCE:
|
||||
logger.debug(log_prompt.format('Use nonce'))
|
||||
nonce = get_random_string(settings.AUTH_OPENID_NONCE_LENGTH)
|
||||
request_params.update({'nonce': nonce, })
|
||||
authentication_request_params.update({'nonce': nonce, })
|
||||
request.session['oidc_auth_nonce'] = nonce
|
||||
|
||||
# Stores the "next" URL in the session if applicable.
|
||||
logger.debug(log_prompt.format('Stores next url in the session'))
|
||||
next_url = request.GET.get('next')
|
||||
request.session['oidc_auth_next_url'] = safe_next_url(next_url, request=request)
|
||||
|
||||
# Redirects the user to authorization endpoint.
|
||||
logger.debug(log_prompt.format('Construct redirect url'))
|
||||
query = urlencode(request_params)
|
||||
query = urlencode(authentication_request_params)
|
||||
redirect_url = '{url}?{query}'.format(
|
||||
url=settings.AUTH_OPENID_PROVIDER_AUTHORIZATION_ENDPOINT, query=query)
|
||||
|
||||
@@ -126,8 +129,6 @@ class OIDCAuthCallbackView(View, FlashMessageMixin):
|
||||
|
||||
http_method_names = ['get', ]
|
||||
|
||||
|
||||
@redirect_to_pre_save_next_after_auth
|
||||
def get(self, request):
|
||||
""" Processes GET requests. """
|
||||
log_prompt = "Process GET requests [OIDCAuthCallbackView]: {}"
|
||||
@@ -166,6 +167,7 @@ class OIDCAuthCallbackView(View, FlashMessageMixin):
|
||||
raise SuspiciousOperation('Invalid OpenID Connect callback state value')
|
||||
|
||||
# Authenticates the end-user.
|
||||
next_url = request.session.get('oidc_auth_next_url', None)
|
||||
code_verifier = request.session.get('oidc_auth_code_verifier', None)
|
||||
logger.debug(log_prompt.format('Process authenticate'))
|
||||
try:
|
||||
@@ -189,7 +191,9 @@ class OIDCAuthCallbackView(View, FlashMessageMixin):
|
||||
callback_params.get('session_state', None)
|
||||
|
||||
logger.debug(log_prompt.format('Redirect'))
|
||||
return HttpResponseRedirect(settings.AUTH_OPENID_AUTHENTICATION_REDIRECT_URI)
|
||||
return HttpResponseRedirect(
|
||||
next_url or settings.AUTH_OPENID_AUTHENTICATION_REDIRECT_URI
|
||||
)
|
||||
if 'error' in callback_params:
|
||||
logger.debug(
|
||||
log_prompt.format('Error in callback params: {}'.format(callback_params['error']))
|
||||
@@ -208,6 +212,10 @@ class OIDCAuthCallbackView(View, FlashMessageMixin):
|
||||
return HttpResponseRedirect(redirect_url)
|
||||
|
||||
|
||||
class OIDCAuthCallbackClientView(BaseAuthCallbackClientView):
|
||||
pass
|
||||
|
||||
|
||||
class OIDCEndSessionView(View):
|
||||
""" Allows to end the session of any user authenticated using OpenID Connect.
|
||||
|
||||
|
||||
@@ -8,5 +8,6 @@ urlpatterns = [
|
||||
path('login/', views.Saml2AuthRequestView.as_view(), name='saml2-login'),
|
||||
path('logout/', views.Saml2EndSessionView.as_view(), name='saml2-logout'),
|
||||
path('callback/', views.Saml2AuthCallbackView.as_view(), name='saml2-callback'),
|
||||
path('callback/client/', views.Saml2AuthCallbackClientView.as_view(), name='saml2-callback-client'),
|
||||
path('metadata/', views.Saml2AuthMetadataView.as_view(), name='saml2-metadata'),
|
||||
]
|
||||
|
||||
@@ -19,6 +19,7 @@ from onelogin.saml2.idp_metadata_parser import (
|
||||
from authentication.views.mixins import FlashMessageMixin
|
||||
from common.utils import get_logger, safe_next_url
|
||||
from .settings import JmsSaml2Settings
|
||||
from ..base import BaseAuthCallbackClientView
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
@@ -207,7 +208,7 @@ class Saml2AuthRequestView(View, PrepareRequestMixin):
|
||||
log_prompt = "Process SAML GET requests: {}"
|
||||
logger.debug(log_prompt.format('Start'))
|
||||
|
||||
request_params = request.GET.dict()
|
||||
authentication_request_params = request.GET.dict()
|
||||
|
||||
try:
|
||||
saml_instance = self.init_saml_auth(request)
|
||||
@@ -215,7 +216,7 @@ class Saml2AuthRequestView(View, PrepareRequestMixin):
|
||||
logger.error(log_prompt.format('Init saml auth error: %s' % error))
|
||||
return HttpResponse(error, status=412)
|
||||
|
||||
next_url = request_params.get('next') or settings.AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT
|
||||
next_url = authentication_request_params.get('next', settings.AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT)
|
||||
next_url = safe_next_url(next_url, request=request)
|
||||
url = saml_instance.login(return_to=next_url)
|
||||
logger.debug(log_prompt.format('Redirect login url'))
|
||||
@@ -295,11 +296,10 @@ class Saml2AuthCallbackView(View, PrepareRequestMixin, FlashMessageMixin):
|
||||
return response
|
||||
|
||||
logger.debug(log_prompt.format('Redirect'))
|
||||
relay_state = post_data.get('RelayState')
|
||||
if not relay_state or len(relay_state) == 0:
|
||||
relay_state = "/"
|
||||
next_url = saml_instance.redirect_to(relay_state)
|
||||
next_url = safe_next_url(next_url, request=request)
|
||||
redir = post_data.get('RelayState')
|
||||
if not redir or len(redir) == 0:
|
||||
redir = "/"
|
||||
next_url = saml_instance.redirect_to(redir)
|
||||
return HttpResponseRedirect(next_url)
|
||||
|
||||
@csrf_exempt
|
||||
@@ -307,6 +307,10 @@ class Saml2AuthCallbackView(View, PrepareRequestMixin, FlashMessageMixin):
|
||||
return super().dispatch(*args, **kwargs)
|
||||
|
||||
|
||||
class Saml2AuthCallbackClientView(BaseAuthCallbackClientView):
|
||||
pass
|
||||
|
||||
|
||||
class Saml2AuthMetadataView(View, PrepareRequestMixin):
|
||||
|
||||
def get(self, request):
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
from django.db.models import TextChoices
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD = 'next'
|
||||
|
||||
RSA_PRIVATE_KEY = 'rsa_private_key'
|
||||
RSA_PUBLIC_KEY = 'rsa_public_key'
|
||||
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
"""
|
||||
This module provides decorators to handle redirect URLs during the authentication flow:
|
||||
1. pre_save_next_to_session: Captures and stores the intended next URL before redirecting to auth provider
|
||||
2. redirect_to_pre_save_next_after_auth: Redirects to the stored next URL after successful authentication
|
||||
3. post_save_next_to_session: Copies the stored next URL to session['next'] after view execution
|
||||
"""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.urls import reverse
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from functools import wraps
|
||||
|
||||
from common.utils import get_logger, safe_next_url
|
||||
from .const import USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
|
||||
__all__ = [
|
||||
'pre_save_next_to_session', 'redirect_to_pre_save_next_after_auth',
|
||||
'post_save_next_to_session_if_guard_redirect'
|
||||
]
|
||||
|
||||
# Session key for storing the redirect URL after authentication
|
||||
AUTH_SESSION_NEXT_URL_KEY = 'auth_next_url'
|
||||
|
||||
|
||||
def pre_save_next_to_session(get_next_url=None):
|
||||
"""
|
||||
Decorator to capture and store the 'next' parameter into session BEFORE view execution.
|
||||
|
||||
This decorator is applied to the authentication request view to preserve the user's
|
||||
intended destination URL before redirecting to the authentication provider.
|
||||
|
||||
Args:
|
||||
get_next_url: Optional callable that extracts the next URL from request.
|
||||
Default: lambda req: req.GET.get('next')
|
||||
|
||||
Usage:
|
||||
# Use default (request.GET.get('next'))
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request):
|
||||
pass
|
||||
|
||||
# Custom extraction from POST data
|
||||
@pre_save_next_to_session(get_next_url=lambda req: req.POST.get('next'))
|
||||
def post(self, request):
|
||||
pass
|
||||
|
||||
# Custom extraction from both GET and POST
|
||||
@pre_save_next_to_session(
|
||||
get_next_url=lambda req: req.GET.get('next') or req.POST.get('next')
|
||||
)
|
||||
def get(self, request):
|
||||
pass
|
||||
|
||||
Example flow:
|
||||
User accesses: /auth/oauth2/?next=/dashboard/
|
||||
↓ (decorator saves '/dashboard/' to session)
|
||||
Redirected to OAuth2 provider for authentication
|
||||
"""
|
||||
# Default function to extract next URL from request.GET
|
||||
if get_next_url is None:
|
||||
get_next_url = lambda req: req.GET.get('next')
|
||||
|
||||
def decorator(view_func):
|
||||
@wraps(view_func)
|
||||
def wrapper(self, request, *args, **kwargs):
|
||||
next_url = get_next_url(request)
|
||||
if next_url:
|
||||
request.session[AUTH_SESSION_NEXT_URL_KEY] = next_url
|
||||
logger.debug(f"[Auth] Saved next_url to session: {next_url}")
|
||||
return view_func(self, request, *args, **kwargs)
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
def redirect_to_pre_save_next_after_auth(view_func):
|
||||
"""
|
||||
Decorator to redirect to the previously saved 'next' URL after successful authentication.
|
||||
|
||||
This decorator is applied to the authentication callback view. After the user successfully
|
||||
authenticates, if a 'next' URL was previously saved in the session (by pre_save_next_to_session),
|
||||
the user will be redirected to that URL instead of the default redirect location.
|
||||
|
||||
Conditions for redirect:
|
||||
- User must be authenticated (request.user.is_authenticated)
|
||||
- Session must contain the saved next URL (AUTH_SESSION_NEXT_URL_KEY)
|
||||
- The next URL must not be '/' (avoid unnecessary redirects)
|
||||
- The next URL must pass security validation (safe_next_url)
|
||||
|
||||
If any condition fails, returns the original view response.
|
||||
|
||||
Usage:
|
||||
@redirect_to_pre_save_next_after_auth
|
||||
def get(self, request):
|
||||
# Process authentication callback
|
||||
if user_authenticated:
|
||||
auth.login(request, user)
|
||||
return HttpResponseRedirect(default_url)
|
||||
|
||||
Example flow:
|
||||
User redirected back from OAuth2 provider: /auth/oauth2/callback/?code=xxx
|
||||
↓ (view processes authentication, user becomes authenticated)
|
||||
Decorator checks session for saved next URL
|
||||
↓ (finds '/dashboard/' in session)
|
||||
Redirects to: /dashboard/
|
||||
↓ (clears saved URL from session)
|
||||
"""
|
||||
@wraps(view_func)
|
||||
def wrapper(self, request, *args, **kwargs):
|
||||
# Execute the original view method first
|
||||
response = view_func(self, request, *args, **kwargs)
|
||||
|
||||
# Check if user has been authenticated
|
||||
if request.user and request.user.is_authenticated:
|
||||
# Check if session contains a saved next URL
|
||||
saved_next_url = request.session.get(AUTH_SESSION_NEXT_URL_KEY)
|
||||
|
||||
if saved_next_url and saved_next_url != '/':
|
||||
# Validate the URL for security
|
||||
safe_url = safe_next_url(saved_next_url, request=request)
|
||||
if safe_url:
|
||||
# Clear the saved URL from session (one-time use)
|
||||
request.session.pop(AUTH_SESSION_NEXT_URL_KEY, None)
|
||||
logger.debug(f"[Auth] Redirecting authenticated user to saved next_url: {safe_url}")
|
||||
return HttpResponseRedirect(safe_url)
|
||||
|
||||
# Return the original response if no redirect conditions are met
|
||||
return response
|
||||
return wrapper
|
||||
|
||||
|
||||
def post_save_next_to_session_if_guard_redirect(view_func):
|
||||
"""
|
||||
Decorator to copy AUTH_SESSION_NEXT_URL_KEY to session['next'] after view execution,
|
||||
but only if redirecting to login-guard view.
|
||||
|
||||
This decorator is applied AFTER view execution. It copies the value from
|
||||
AUTH_SESSION_NEXT_URL_KEY (internal storage) to 'next' (standard session key)
|
||||
for use by downstream code.
|
||||
|
||||
Only sets the 'next' session key when the response is a redirect to guard-view
|
||||
(i.e., response with redirect status code and location path matching login-guard view URL).
|
||||
|
||||
Usage:
|
||||
@post_save_next_to_session_if_guard_redirect
|
||||
def get(self, request):
|
||||
# Process the request and return response
|
||||
if some_condition:
|
||||
return self.redirect_to_guard_view() # Decorator will copy next to session
|
||||
return HttpResponseRedirect(url) # Decorator won't copy if not to guard-view
|
||||
|
||||
Example flow:
|
||||
View executes and returns redirect to guard view
|
||||
↓ (response is redirect with 'login-guard' in Location)
|
||||
Decorator checks if response is redirect to guard-view and session has saved next URL
|
||||
↓ (copies AUTH_SESSION_NEXT_URL_KEY to session['next'])
|
||||
User is redirected to guard-view with 'next' available in session
|
||||
"""
|
||||
@wraps(view_func)
|
||||
def wrapper(self, request, *args, **kwargs):
|
||||
# Execute the original view method
|
||||
response = view_func(self, request, *args, **kwargs)
|
||||
|
||||
# Check if response is a redirect to guard view
|
||||
# Redirect responses typically have status codes 301, 302, 303, 307, 308
|
||||
is_guard_redirect = False
|
||||
if hasattr(response, 'status_code') and response.status_code in (301, 302, 303, 307, 308):
|
||||
# Check if the redirect location is to guard view
|
||||
location = response.get('Location', '')
|
||||
if location:
|
||||
# Extract path from location URL (handle both absolute and relative URLs)
|
||||
parsed_url = urlparse(location)
|
||||
path = parsed_url.path
|
||||
|
||||
# Check if path matches guard view URL pattern
|
||||
guard_view_url = reverse('authentication:login-guard')
|
||||
if path == guard_view_url:
|
||||
is_guard_redirect = True
|
||||
|
||||
# Only set 'next' if response is a redirect to guard view
|
||||
if is_guard_redirect:
|
||||
# Copy AUTH_SESSION_NEXT_URL_KEY to 'next' if it exists
|
||||
saved_next_url = request.session.get(AUTH_SESSION_NEXT_URL_KEY)
|
||||
if saved_next_url:
|
||||
# 这里 'next' 是 UserLoginGuardView.redirect_field_name
|
||||
request.session[USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD] = saved_next_url
|
||||
logger.debug(f"[Auth] Copied {AUTH_SESSION_NEXT_URL_KEY} to 'next' in session: {saved_next_url}")
|
||||
|
||||
return response
|
||||
return wrapper
|
||||
@@ -36,7 +36,7 @@ class MFAMiddleware:
|
||||
# 这个是 mfa 登录页需要的请求, 也得放出来, 用户其实已经在 CAS/OIDC 中完成登录了
|
||||
white_urls = [
|
||||
'login/mfa', 'mfa/select', 'face/context', 'jsi18n/', '/static/',
|
||||
'/profile/otp', '/logout/', '/media/'
|
||||
'/profile/otp', '/logout/',
|
||||
]
|
||||
for url in white_urls:
|
||||
if request.path.find(url) > -1:
|
||||
|
||||
@@ -139,6 +139,7 @@ def authenticate(request=None, **credentials):
|
||||
"""
|
||||
If the given credentials are valid, return a User object.
|
||||
"""
|
||||
|
||||
temp_user = None
|
||||
username = credentials.get('username')
|
||||
for backend, backend_path in _get_backends(return_tuples=True):
|
||||
|
||||
@@ -9,8 +9,6 @@ from audits.models import UserSession
|
||||
from common.sessions.cache import user_session_manager
|
||||
from .signals import post_auth_success, post_auth_failed, user_auth_failed, user_auth_success
|
||||
|
||||
from .backends.oauth2_provider.signal_handlers import *
|
||||
|
||||
|
||||
@receiver(user_logged_in)
|
||||
def on_user_auth_login_success(sender, user, request, **kwargs):
|
||||
@@ -59,4 +57,3 @@ def on_user_login_success(sender, request, user, backend, create=False, **kwargs
|
||||
def on_user_login_failed(sender, username, request, reason, backend, **kwargs):
|
||||
request.session['auth_backend'] = backend
|
||||
post_auth_failed.send(sender, username=username, request=request, reason=reason)
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from rest_framework.request import Request
|
||||
from authentication import errors
|
||||
from authentication.mixins import AuthMixin
|
||||
from authentication.notifications import OAuthBindMessage
|
||||
from authentication.decorators import post_save_next_to_session_if_guard_redirect
|
||||
from common.utils import get_logger
|
||||
from common.utils.common import get_request_ip
|
||||
from common.utils.django import reverse, get_object_or_none
|
||||
@@ -47,6 +46,15 @@ class BaseLoginCallbackView(AuthMixin, FlashMessageMixin, IMClientMixin, View):
|
||||
def verify_state(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def get_next_url(self, request):
|
||||
"""
|
||||
Get next url for redirect after authentication.
|
||||
|
||||
Note: This method can be overridden in subclasses, but DO NOT DELETE.
|
||||
Subclasses may rely on this interface for customizing redirect behavior.
|
||||
"""
|
||||
pass
|
||||
|
||||
def create_user_if_not_exist(self, user_id, **kwargs):
|
||||
user = None
|
||||
user_attr = self.client.get_user_detail(user_id, **kwargs)
|
||||
@@ -73,7 +81,6 @@ class BaseLoginCallbackView(AuthMixin, FlashMessageMixin, IMClientMixin, View):
|
||||
|
||||
return user, None
|
||||
|
||||
@post_save_next_to_session_if_guard_redirect
|
||||
def get(self, request: Request):
|
||||
code = request.GET.get('code')
|
||||
redirect_url = request.GET.get('redirect_url')
|
||||
@@ -112,6 +119,13 @@ class BaseLoginCallbackView(AuthMixin, FlashMessageMixin, IMClientMixin, View):
|
||||
response = self.get_failed_response(login_url, title=msg, msg=msg)
|
||||
return response
|
||||
|
||||
if redirect_url and 'next=client' in redirect_url:
|
||||
self.request.META['QUERY_STRING'] += '&next=client'
|
||||
|
||||
next_url = self.get_next_url(request)
|
||||
if next_url:
|
||||
# guard view 需要用到 session 中的 next 参数
|
||||
request.session['next'] = next_url
|
||||
return self.redirect_to_guard_view()
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ from django.views import View
|
||||
from rest_framework.exceptions import APIException
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
|
||||
from authentication.decorators import post_save_next_to_session_if_guard_redirect, pre_save_next_to_session
|
||||
from authentication import errors
|
||||
from authentication.const import ConfirmType
|
||||
from authentication.mixins import AuthMixin
|
||||
@@ -25,7 +24,7 @@ from common.views.mixins import PermissionsMixin, UserConfirmRequiredExceptionMi
|
||||
from users.models import User
|
||||
from users.views import UserVerifyPasswordView
|
||||
from .base import BaseLoginCallbackView
|
||||
from .mixins import FlashMessageMixin
|
||||
from .mixins import METAMixin, FlashMessageMixin
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
@@ -172,18 +171,20 @@ class DingTalkEnableStartView(UserVerifyPasswordView):
|
||||
return success_url
|
||||
|
||||
|
||||
class DingTalkQRLoginView(DingTalkQRMixin, View):
|
||||
class DingTalkQRLoginView(DingTalkQRMixin, METAMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request: HttpRequest):
|
||||
redirect_url = request.GET.get('redirect_url') or reverse('index')
|
||||
query_string = request.GET.urlencode()
|
||||
redirect_url = f'{redirect_url}?{query_string}'
|
||||
next_url = self.get_next_url_from_meta() or reverse('index')
|
||||
next_url = safe_next_url(next_url, request=request)
|
||||
|
||||
redirect_uri = reverse('authentication:dingtalk-qr-login-callback', external=True)
|
||||
redirect_uri += '?' + urlencode({
|
||||
'redirect_url': redirect_url,
|
||||
'next': next_url,
|
||||
})
|
||||
|
||||
url = self.get_qr_url(redirect_uri)
|
||||
@@ -209,7 +210,6 @@ class DingTalkQRLoginCallbackView(DingTalkQRMixin, BaseLoginCallbackView):
|
||||
class DingTalkOAuthLoginView(DingTalkOAuthMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request: HttpRequest):
|
||||
redirect_url = request.GET.get('redirect_url')
|
||||
|
||||
@@ -223,7 +223,6 @@ class DingTalkOAuthLoginView(DingTalkOAuthMixin, View):
|
||||
class DingTalkOAuthLoginCallbackView(AuthMixin, DingTalkOAuthMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@post_save_next_to_session_if_guard_redirect
|
||||
def get(self, request: HttpRequest):
|
||||
code = request.GET.get('code')
|
||||
redirect_url = request.GET.get('redirect_url')
|
||||
|
||||
@@ -8,7 +8,6 @@ from django.views import View
|
||||
from rest_framework.exceptions import APIException
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
|
||||
from authentication.decorators import pre_save_next_to_session
|
||||
from authentication.const import ConfirmType
|
||||
from authentication.permissions import UserConfirmation
|
||||
from common.sdk.im.feishu import URL
|
||||
@@ -109,12 +108,9 @@ class FeiShuQRBindCallbackView(FeiShuQRMixin, BaseBindCallbackView):
|
||||
class FeiShuQRLoginView(FeiShuQRMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request: HttpRequest):
|
||||
redirect_url = request.GET.get('redirect_url') or reverse('index')
|
||||
query_string = request.GET.copy()
|
||||
query_string.pop('next', None)
|
||||
query_string = query_string.urlencode()
|
||||
query_string = request.GET.urlencode()
|
||||
redirect_url = f'{redirect_url}?{query_string}'
|
||||
redirect_uri = reverse(f'authentication:{self.category}-qr-login-callback', external=True)
|
||||
redirect_uri += '?' + urlencode({
|
||||
|
||||
@@ -29,7 +29,7 @@ from users.utils import (
|
||||
redirect_user_first_login_or_index
|
||||
)
|
||||
from .. import mixins, errors
|
||||
from ..const import RSA_PRIVATE_KEY, RSA_PUBLIC_KEY, USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD
|
||||
from ..const import RSA_PRIVATE_KEY, RSA_PUBLIC_KEY
|
||||
from ..forms import get_user_login_form_cls
|
||||
from ..utils import get_auth_methods
|
||||
|
||||
@@ -260,7 +260,7 @@ class UserLoginView(mixins.AuthMixin, UserLoginContextMixin, FormView):
|
||||
|
||||
|
||||
class UserLoginGuardView(mixins.AuthMixin, RedirectView):
|
||||
redirect_field_name = USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD
|
||||
redirect_field_name = 'next'
|
||||
login_url = reverse_lazy('authentication:login')
|
||||
login_mfa_url = reverse_lazy('authentication:login-mfa')
|
||||
login_confirm_url = reverse_lazy('authentication:login-wait-confirm')
|
||||
|
||||
@@ -4,6 +4,17 @@ from django.utils.translation import gettext_lazy as _
|
||||
from common.utils import FlashMessageUtil
|
||||
|
||||
|
||||
class METAMixin:
|
||||
def get_next_url_from_meta(self):
|
||||
request_meta = self.request.META or {}
|
||||
next_url = None
|
||||
referer = request_meta.get('HTTP_REFERER', '')
|
||||
next_url_item = referer.rsplit('next=', 1)
|
||||
if len(next_url_item) > 1:
|
||||
next_url = next_url_item[-1]
|
||||
return next_url
|
||||
|
||||
|
||||
class FlashMessageMixin:
|
||||
@staticmethod
|
||||
def get_response(redirect_url='', title='', msg='', m_type='message', interval=5):
|
||||
|
||||
@@ -8,7 +8,6 @@ from rest_framework.exceptions import APIException
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
from rest_framework.request import Request
|
||||
|
||||
from authentication.decorators import pre_save_next_to_session
|
||||
from authentication.const import ConfirmType
|
||||
from authentication.permissions import UserConfirmation
|
||||
from common.sdk.im.slack import URL, SLACK_REDIRECT_URI_SESSION_KEY
|
||||
@@ -97,12 +96,9 @@ class SlackEnableStartView(UserVerifyPasswordView):
|
||||
class SlackQRLoginView(SlackMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request: Request):
|
||||
redirect_url = request.GET.get('redirect_url') or reverse('index')
|
||||
query_string = request.GET.copy()
|
||||
query_string.pop('next', None)
|
||||
query_string = query_string.urlencode()
|
||||
query_string = request.GET.urlencode()
|
||||
redirect_url = f'{redirect_url}?{query_string}'
|
||||
redirect_uri = reverse('authentication:slack-qr-login-callback', external=True)
|
||||
redirect_uri += '?' + urlencode({
|
||||
|
||||
@@ -12,7 +12,6 @@ from authentication import errors
|
||||
from authentication.const import ConfirmType
|
||||
from authentication.mixins import AuthMixin
|
||||
from authentication.permissions import UserConfirmation
|
||||
from authentication.decorators import post_save_next_to_session_if_guard_redirect, pre_save_next_to_session
|
||||
from common.sdk.im.wecom import URL
|
||||
from common.sdk.im.wecom import WeCom, wecom_tool
|
||||
from common.utils import get_logger
|
||||
@@ -21,7 +20,7 @@ from common.views.mixins import UserConfirmRequiredExceptionMixin, PermissionsMi
|
||||
from users.models import User
|
||||
from users.views import UserVerifyPasswordView
|
||||
from .base import BaseLoginCallbackView, BaseBindCallbackView
|
||||
from .mixins import FlashMessageMixin
|
||||
from .mixins import METAMixin, FlashMessageMixin
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
@@ -116,14 +115,20 @@ class WeComEnableStartView(UserVerifyPasswordView):
|
||||
return success_url
|
||||
|
||||
|
||||
class WeComQRLoginView(WeComQRMixin, View):
|
||||
class WeComQRLoginView(WeComQRMixin, METAMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request: HttpRequest):
|
||||
|
||||
next_url = self.get_next_url_from_meta() or reverse('index')
|
||||
next_url = safe_next_url(next_url, request=request)
|
||||
# 当 next_url 包含 redirect_uri 到非本站点时(如 jms://)会触发企业微信的 waf 501 错误,因此需要存储在 session 中,然后在callback 中获取
|
||||
wecom_tool.set_next_url_in_session(request, next_url)
|
||||
|
||||
redirect_url = request.GET.get('redirect_url') or reverse('index')
|
||||
redirect_uri = reverse('authentication:wecom-qr-login-callback', external=True)
|
||||
redirect_uri += '?' + urlencode({'redirect_url': redirect_url})
|
||||
|
||||
url = self.get_qr_url(redirect_uri)
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
@@ -140,15 +145,20 @@ class WeComQRLoginCallbackView(WeComQRMixin, BaseLoginCallbackView):
|
||||
msg_user_not_bound_err = _('WeCom is not bound')
|
||||
msg_not_found_user_from_client_err = _('Failed to get user from WeCom')
|
||||
|
||||
def get_next_url(self, request):
|
||||
next_url = wecom_tool.get_next_url_from_session(request)
|
||||
return next_url
|
||||
|
||||
|
||||
class WeComOAuthLoginView(WeComOAuthMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@pre_save_next_to_session()
|
||||
def get(self, request: HttpRequest):
|
||||
redirect_url = request.GET.get('redirect_url')
|
||||
|
||||
redirect_uri = reverse('authentication:wecom-oauth-login-callback', external=True)
|
||||
redirect_uri += '?' + urlencode({'redirect_url': redirect_url})
|
||||
|
||||
url = self.get_oauth_url(redirect_uri)
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
@@ -156,7 +166,6 @@ class WeComOAuthLoginView(WeComOAuthMixin, View):
|
||||
class WeComOAuthLoginCallbackView(AuthMixin, WeComOAuthMixin, View):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
@post_save_next_to_session_if_guard_redirect
|
||||
def get(self, request: HttpRequest):
|
||||
code = request.GET.get('code')
|
||||
redirect_url = request.GET.get('redirect_url')
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
import time
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.test import Client
|
||||
from django.urls import URLPattern, URLResolver
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
|
||||
from jumpserver.urls import api_v1
|
||||
|
||||
@@ -80,8 +81,7 @@ known_unauth_urls = [
|
||||
"/api/v1/authentication/mfa/send-code/",
|
||||
"/api/v1/authentication/sso/login/",
|
||||
"/api/v1/authentication/user-session/",
|
||||
"/api/v1/settings/i18n/zh-hans/",
|
||||
"/api/v1/settings/client/versions/"
|
||||
"/api/v1/settings/i18n/zh-hans/"
|
||||
]
|
||||
|
||||
known_error_urls = [
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import os
|
||||
from ctypes import *
|
||||
|
||||
from .exception import PiicoError
|
||||
from .session import Session
|
||||
from .cipher import *
|
||||
from .digest import *
|
||||
from django.core.cache import cache
|
||||
from redis_lock import Lock as RedisLock
|
||||
|
||||
|
||||
class Device:
|
||||
@@ -18,7 +15,6 @@ class Device:
|
||||
self.__load_driver(driver_path)
|
||||
# open device
|
||||
self.__open_device()
|
||||
self.__reset_key_store()
|
||||
|
||||
def close(self):
|
||||
if self.__device is None:
|
||||
@@ -72,30 +68,3 @@ class Device:
|
||||
if ret != 0:
|
||||
raise PiicoError("open piico device failed", ret)
|
||||
self.__device = device
|
||||
|
||||
def __reset_key_store(self):
|
||||
redis_client = cache.client.get_client()
|
||||
server_hostname = os.environ.get("SERVER_HOSTNAME")
|
||||
RESET_LOCK_KEY = f"spiico:{server_hostname}:reset"
|
||||
LOCK_EXPIRE_SECONDS = 300
|
||||
|
||||
if self._driver is None:
|
||||
raise PiicoError("no driver loaded", 0)
|
||||
if self.__device is None:
|
||||
raise PiicoError("device not open", 0)
|
||||
|
||||
# ---- 分布式锁(Redis-Lock 实现 Redlock) ----
|
||||
lock = RedisLock(
|
||||
redis_client,
|
||||
RESET_LOCK_KEY,
|
||||
expire=LOCK_EXPIRE_SECONDS, # 锁自动过期
|
||||
auto_renewal=False, # 不自动续租
|
||||
)
|
||||
|
||||
# 尝试获取锁,拿不到直接返回
|
||||
if not lock.acquire(blocking=False):
|
||||
return
|
||||
# ---- 真正执行 reset ----
|
||||
ret = self._driver.SPII_ResetModule(self.__device)
|
||||
if ret != 0:
|
||||
raise PiicoError("reset device failed", ret)
|
||||
@@ -221,5 +221,11 @@ class WeComTool(object):
|
||||
}
|
||||
return URL.OAUTH_CONNECT + '?' + urlencode(params) + '#wechat_redirect'
|
||||
|
||||
def set_next_url_in_session(self, request, next_url):
|
||||
request.session[self.WECOM_STATE_NEXT_URL_KEY] = next_url
|
||||
|
||||
def get_next_url_from_session(self, request):
|
||||
return request.session.get(self.WECOM_STATE_NEXT_URL_KEY)
|
||||
|
||||
|
||||
wecom_tool = WeComTool()
|
||||
|
||||
@@ -30,30 +30,12 @@ __all__ = [
|
||||
"CommonSerializerMixin",
|
||||
"CommonBulkSerializerMixin",
|
||||
"SecretReadableMixin",
|
||||
"SecretReadableCheckMixin",
|
||||
"CommonModelSerializer",
|
||||
"CommonBulkModelSerializer",
|
||||
"ResourceLabelsMixin",
|
||||
]
|
||||
|
||||
|
||||
class SecretReadableCheckMixin(serializers.Serializer):
|
||||
"""
|
||||
根据 SECURITY_ACCOUNT_SECRET_READ 配置控制密码字段的可读性
|
||||
当配置为 False 时,密码字段返回 None
|
||||
"""
|
||||
|
||||
def to_representation(self, instance):
|
||||
ret = super().to_representation(instance)
|
||||
|
||||
if not settings.SECURITY_ACCOUNT_SECRET_READ:
|
||||
secret_fields = getattr(self.Meta, 'secret_fields', ['secret'])
|
||||
for field_name in secret_fields:
|
||||
if field_name in ret:
|
||||
ret[field_name] = '<REDACTED>'
|
||||
return ret
|
||||
|
||||
|
||||
class SecretReadableMixin(serializers.Serializer):
|
||||
"""加密字段 (EncryptedField) 可读性"""
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1636,8 +1636,7 @@
|
||||
"setVariable": "Set variable",
|
||||
"userId": "User ID",
|
||||
"userName": "User name",
|
||||
"AccountSecretReadDisabled": "Account secret reading has been disabled by administrator",
|
||||
"AccessToken": "Access tokens",
|
||||
"AccessTokenTip": "Access Token is a temporary credential generated through the OAuth2 (Authorization Code Grant) flow using the JumpServer client, which is used to access protected resources.",
|
||||
"Revoke": "Revoke"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "Distribución de visitas",
|
||||
"AccessIP": "Lista blanca de IP",
|
||||
"AccessKey": "Clave de acceso",
|
||||
"AccessToken": "Token de acceso",
|
||||
"AccessTokenTip": "El token de acceso es un certificado temporal generado a través del cliente JumpServer utilizando el flujo de OAuth2 (autorización por código) para acceder a recursos protegidos.",
|
||||
"Account": "Información de la cuenta",
|
||||
"AccountActivities": "Actividad de la cuenta",
|
||||
"AccountAndPasswordChangeRank": "Clasificación de cambio de contraseña de cuenta",
|
||||
@@ -46,7 +44,6 @@
|
||||
"AccountPushUpdate": "Actualizar la notificación de la cuenta",
|
||||
"AccountReport": "Informe de cuentas",
|
||||
"AccountResult": "Cambio de contraseña de cuenta exitoso/fallido",
|
||||
"AccountSecretReadDisabled": "La función de lectura de nombre de usuario y contraseña ha sido desactivada por el administrador",
|
||||
"AccountSelectHelpText": "La lista de cuentas agrega el nombre de usuario de la cuenta. Tipo de contraseña.",
|
||||
"AccountSessions": "Sesión de cuenta",
|
||||
"AccountStatisticsReport": "Informe estadístico de cuentas",
|
||||
@@ -282,7 +279,6 @@
|
||||
"CACertificate": "Certificado CA",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "Tianyi Cloud",
|
||||
"CTYunPrivate": "eCloud Nube Privada",
|
||||
"CalculationResults": "Error en la expresión cron",
|
||||
"CallRecords": "Registro de llamadas",
|
||||
@@ -1180,8 +1176,6 @@
|
||||
"RetrySelected": "Reintentar selección",
|
||||
"Review": "Revisión",
|
||||
"Reviewer": "Aprobador",
|
||||
"Revoke": "Revocar",
|
||||
"Risk": "Riesgo",
|
||||
"RiskDetection": "Detección de riesgos",
|
||||
"RiskDetectionDetail": "Detalles de detección de riesgos",
|
||||
"RiskyAccount": "Cuenta de riesgo",
|
||||
@@ -1645,7 +1639,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "Esta acción reemplazará todos los protocolos y puertos, ¿continuar?",
|
||||
"pleaseSelectAssets": "Por favor, seleccione un activo.",
|
||||
"removeWarningMsg": "¿Está seguro de que desea eliminar?",
|
||||
"selectFiles": "Se ha seleccionado el archivo número {number}",
|
||||
"selectedAssets": "Activos seleccionados",
|
||||
"setVariable": "configurar parámetros",
|
||||
"userId": "ID de usuario",
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "アクセス分布",
|
||||
"AccessIP": "IP ホワイトリスト",
|
||||
"AccessKey": "アクセスキー",
|
||||
"AccessToken": "アクセス・トークン",
|
||||
"AccessTokenTip": "アクセス・トークンは、JumpServer クライアントを通じて OAuth2(Authorization Code Grant)フローを使用して生成される一時的な証明書であり、保護されたリソースへのアクセスに使用されます。",
|
||||
"Account": "アカウント情報",
|
||||
"AccountActivities": "アカウント活動",
|
||||
"AccountAmount": "アカウント数",
|
||||
@@ -48,7 +46,6 @@
|
||||
"AccountPushUpdate": "アカウント更新プッシュ",
|
||||
"AccountReport": "アカウントレポート",
|
||||
"AccountResult": "アカウントパスワード変更成功/失敗",
|
||||
"AccountSecretReadDisabled": "アカウントパスワードの読み取り機能は管理者によって無効になっています。",
|
||||
"AccountSelectHelpText": "アカウント一覧に追加されている内容は、アカウントのユーザー名",
|
||||
"AccountSessions": " アカウントセッション ",
|
||||
"AccountStatisticsReport": "アカウント統計レポート",
|
||||
@@ -286,7 +283,6 @@
|
||||
"CACertificate": "CA 証明書",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "天翼クラウド",
|
||||
"CTYunPrivate": "イークラウド・プライベートクラウド",
|
||||
"CalculationResults": "cron 式のエラー",
|
||||
"CallRecords": "つうわきろく",
|
||||
@@ -1185,8 +1181,6 @@
|
||||
"RetrySelected": "選択したものを再試行",
|
||||
"Review": "審査",
|
||||
"Reviewer": "承認者",
|
||||
"Revoke": "取り消し",
|
||||
"Risk": "リスク",
|
||||
"RiskDetection": "リスク検出",
|
||||
"RiskDetectionDetail": "リスク検出の詳細",
|
||||
"RiskyAccount": "リスクアカウント",
|
||||
@@ -1650,7 +1644,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "この操作はすべてのプロトコルとポートを上書きしますが、続行してよろしいですか?",
|
||||
"pleaseSelectAssets": "資産を選択してください",
|
||||
"removeWarningMsg": "削除してもよろしいですか",
|
||||
"selectFiles": "{number}ファイルを選択しました。",
|
||||
"selectedAssets": "選択した資産",
|
||||
"setVariable": "パラメータ設定",
|
||||
"userId": "ユーザーID",
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "방문 분포",
|
||||
"AccessIP": "IP 화이트리스트",
|
||||
"AccessKey": "액세스 키",
|
||||
"AccessToken": "접속 토큰",
|
||||
"AccessTokenTip": "접속 토큰은 JumpServer 클라이언트를 통해 OAuth2(인증 코드 인증) 프로세스를 사용하여 생성된 임시 자격 증명으로, 보호된 리소스에 접근하는 데 사용됩니다.",
|
||||
"Account": "계정",
|
||||
"AccountActivities": "계정 활동",
|
||||
"AccountAndPasswordChangeRank": "계정 비밀번호 변경 순위",
|
||||
@@ -46,7 +44,6 @@
|
||||
"AccountPushUpdate": "계정 업데이트 푸시",
|
||||
"AccountReport": "계정 보고서",
|
||||
"AccountResult": "계정 비밀번호 변경 성공/실패",
|
||||
"AccountSecretReadDisabled": "계정 비밀번호 읽기 기능은 관리자가 비활성화하였습니다.",
|
||||
"AccountSelectHelpText": "계정 목록에 추가하는 것은 계정의 사용자 이름—암호 유형입니다.",
|
||||
"AccountSessions": "계정 세션",
|
||||
"AccountStatisticsReport": "계정 통계 보고서",
|
||||
@@ -282,7 +279,6 @@
|
||||
"CACertificate": "CA 인증서",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "천윳 클라우드",
|
||||
"CTYunPrivate": "천翼 개인 클라우드",
|
||||
"CalculationResults": "cron 표현식 오류",
|
||||
"CallRecords": "호출 기록",
|
||||
@@ -1180,8 +1176,6 @@
|
||||
"RetrySelected": "선택한 항목 재시도",
|
||||
"Review": "검토",
|
||||
"Reviewer": "승인자",
|
||||
"Revoke": "취소",
|
||||
"Risk": "위험",
|
||||
"RiskDetection": "위험 감지",
|
||||
"RiskDetectionDetail": "위험 감지 상세 정보",
|
||||
"RiskyAccount": "위험 계정",
|
||||
@@ -1645,7 +1639,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "이 작업은 모든 프로토콜과 포트를 덮어씌우게 됩니다. 계속하시겠습니까?",
|
||||
"pleaseSelectAssets": "자산을 선택해 주세요",
|
||||
"removeWarningMsg": "제거할 것인지 확실합니까?",
|
||||
"selectFiles": "선택한 파일 {number}개",
|
||||
"selectedAssets": "선택한 자산",
|
||||
"setVariable": "설정 매개변수",
|
||||
"userId": "사용자 ID",
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "Distribuição de Acesso",
|
||||
"AccessIP": "Lista branca de IP",
|
||||
"AccessKey": "Chave de Acesso",
|
||||
"AccessToken": "Token de acesso",
|
||||
"AccessTokenTip": "O token de acesso é um credencial temporário gerado pelo cliente JumpServer usando o fluxo OAuth2 (autorização por código), utilizado para acessar recursos protegidos.",
|
||||
"Account": "Informações da conta",
|
||||
"AccountActivities": "Atividades da conta",
|
||||
"AccountAndPasswordChangeRank": "Alteração de Senha por Classificação",
|
||||
@@ -46,7 +44,6 @@
|
||||
"AccountPushUpdate": " Atualização de notificação de conta ",
|
||||
"AccountReport": "Relatório de Contas",
|
||||
"AccountResult": "Alteração de senha da conta bem-sucedida/falhada",
|
||||
"AccountSecretReadDisabled": "A funcionalidade de leitura de nome de usuário e senha foi desativada pelo administrador",
|
||||
"AccountSelectHelpText": "A lista de contas inclui o nome de usuário da conta",
|
||||
"AccountSessions": "Conta de sessão ",
|
||||
"AccountStatisticsReport": "Relatório de Estatísticas de Contas",
|
||||
@@ -283,7 +280,6 @@
|
||||
"CACertificate": " Certificado CA",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "Tianyi Cloud",
|
||||
"CTYunPrivate": " eCloud Nuvem Privada",
|
||||
"CalculationResults": "Erro de expressão cron",
|
||||
"CallRecords": "Registro de chamadas",
|
||||
@@ -1181,8 +1177,6 @@
|
||||
"RetrySelected": "repetir a seleção",
|
||||
"Review": "Revisar",
|
||||
"Reviewer": "Aprovador",
|
||||
"Revoke": "Revogar",
|
||||
"Risk": "Risco",
|
||||
"RiskDetection": " Detecção de risco ",
|
||||
"RiskDetectionDetail": "Detalhes da Detecção de Risco",
|
||||
"RiskyAccount": " Conta de risco ",
|
||||
@@ -1646,7 +1640,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "Esta ação substituirá todos os protocolos e portas. Deseja continuar?",
|
||||
"pleaseSelectAssets": "Por favor, selecione um ativo.",
|
||||
"removeWarningMsg": "Tem certeza de que deseja remover",
|
||||
"selectFiles": "Foram selecionados {number} arquivos",
|
||||
"selectedAssets": "Ativos selecionados",
|
||||
"setVariable": "Parâmetros de configuração",
|
||||
"userId": "ID do usuário",
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "Распределение доступа",
|
||||
"AccessIP": "Белый список IP",
|
||||
"AccessKey": "Ключ доступа",
|
||||
"AccessToken": "Токен доступа",
|
||||
"AccessTokenTip": "Токен доступа создается через клиент JumpServer с использованием процесса OAuth2 (авторизация через код) в качестве временного удостоверения для доступа к защищенным ресурсам.",
|
||||
"Account": "Информация об УЗ",
|
||||
"AccountActivities": "Активность учетной записи",
|
||||
"AccountAndPasswordChangeRank": "Рейтинг изменений паролей и учётных записей",
|
||||
@@ -46,7 +44,6 @@
|
||||
"AccountPushUpdate": "Обновление УЗ для публикации",
|
||||
"AccountReport": "Отчет по УЗ",
|
||||
"AccountResult": "Успешное или неудачное изменение секрета УЗ",
|
||||
"AccountSecretReadDisabled": "Функция чтения логина и пароля была отключена администратором",
|
||||
"AccountSelectHelpText": "В списке учетных записей отображается имя пользователя",
|
||||
"AccountSessions": "Сессии учетной записи",
|
||||
"AccountStatisticsReport": "Отчет по учетным записям",
|
||||
@@ -282,7 +279,6 @@
|
||||
"CACertificate": "Сертификат ЦС",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "Tianyi Cloud",
|
||||
"CTYunPrivate": "eCloud Private Cloud",
|
||||
"CalculationResults": "Ошибка в выражении cron",
|
||||
"CallRecords": "Запись вызовов",
|
||||
@@ -1180,8 +1176,6 @@
|
||||
"RetrySelected": "Повторить выбранное",
|
||||
"Review": "Требовать одобрения",
|
||||
"Reviewer": "Утверждающий",
|
||||
"Revoke": "Отмена",
|
||||
"Risk": "Риск",
|
||||
"RiskDetection": "Выявление рисков",
|
||||
"RiskDetectionDetail": "Детали обнаружения риска",
|
||||
"RiskyAccount": "УЗ с риском",
|
||||
@@ -1645,7 +1639,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "Это действие заменит все протоколы и порты. Продолжить?",
|
||||
"pleaseSelectAssets": "Пожалуйста, выберите актив",
|
||||
"removeWarningMsg": "Вы уверены, что хотите удалить",
|
||||
"selectFiles": "Выбрано {number} файлов",
|
||||
"selectedAssets": "Выбранные активы",
|
||||
"setVariable": "Задать переменную",
|
||||
"userId": "ID пользователя",
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "Phân bố truy cập",
|
||||
"AccessIP": "Danh sách trắng IP",
|
||||
"AccessKey": "Khóa truy cập",
|
||||
"AccessToken": "Mã thông hành",
|
||||
"AccessTokenTip": "Mã thông hành là giấy chứng nhận tạm thời được tạo ra thông qua quy trình OAuth2 (ủy quyền mã) sử dụng khách hàng JumpServer, dùng để truy cập tài nguyên được bảo vệ.",
|
||||
"Account": "Tài khoản",
|
||||
"AccountActivities": "Tài khoản hoạt động",
|
||||
"AccountAndPasswordChangeRank": "Thay đổi mật khẩu tài khoản xếp hạng",
|
||||
@@ -46,7 +44,6 @@
|
||||
"AccountPushUpdate": "Cập nhật thông tin tài khoản",
|
||||
"AccountReport": "Báo cáo tài khoản",
|
||||
"AccountResult": "Thay đổi mật khẩu tài khoản thành công/thất bại",
|
||||
"AccountSecretReadDisabled": "Chức năng đọc tài khoản mật khẩu đã bị quản lý bởi quản trị viên vô hiệu hóa",
|
||||
"AccountSelectHelpText": "Danh sách tài khoản thêm tên người dùng của tài khoản",
|
||||
"AccountSessions": "Phiên tài khoản",
|
||||
"AccountStatisticsReport": "Báo cáo thống kê tài khoản",
|
||||
@@ -282,7 +279,6 @@
|
||||
"CACertificate": "Chứng chỉ CA",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "Điện toán đám mây Thiên Vân",
|
||||
"CTYunPrivate": "Đám mây riêng Tianyi",
|
||||
"CalculationResults": "Biểu thức cron sai",
|
||||
"CallRecords": "Ghi chép gọi",
|
||||
@@ -1180,8 +1176,6 @@
|
||||
"RetrySelected": "Thử lại đã chọn",
|
||||
"Review": "Xem xét",
|
||||
"Reviewer": "Người phê duyệt",
|
||||
"Revoke": "Huỷ bỏ",
|
||||
"Risk": "Rủi ro",
|
||||
"RiskDetection": "Phát hiện rủi ro",
|
||||
"RiskDetectionDetail": "Chi tiết phát hiện rủi ro",
|
||||
"RiskyAccount": "Tài khoản rủi ro",
|
||||
@@ -1645,7 +1639,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "Hành động này sẽ ghi đè lên tất cả các giao thức và cổng, có tiếp tục không?",
|
||||
"pleaseSelectAssets": "Vui lòng chọn tài sản.",
|
||||
"removeWarningMsg": "Bạn có chắc chắn muốn xóa bỏ?",
|
||||
"selectFiles": "Đã chọn chọn {number} tệp tin",
|
||||
"selectedAssets": "Tài sản đã chọn",
|
||||
"setVariable": "Cài đặt tham số",
|
||||
"userId": "ID người dùng",
|
||||
|
||||
@@ -1648,6 +1648,5 @@
|
||||
"selectFiles": "已选择选择{number}文件",
|
||||
"AccessToken": "访问令牌",
|
||||
"AccessTokenTip": "访问令牌是通过 JumpServer 客户端使用 OAuth2(授权码授权)流程生成的临时凭证,用于访问受保护的资源。",
|
||||
"Revoke": "撤销",
|
||||
"AccountSecretReadDisabled": "账号密码读取功能已被管理员禁用"
|
||||
}
|
||||
"Revoke": "撤销"
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
"AccessDistribution": "訪問分布",
|
||||
"AccessIP": "IP 白名單",
|
||||
"AccessKey": "訪問金鑰",
|
||||
"AccessToken": "訪問令牌",
|
||||
"AccessTokenTip": "訪問令牌是透過 JumpServer 客戶端使用 OAuth2(授權碼授權)流程生成的臨時憑證,用於訪問受保護的資源。",
|
||||
"Account": "雲帳號",
|
||||
"AccountActivities": "帳號活動",
|
||||
"AccountAmount": "帳號數量",
|
||||
@@ -48,7 +46,6 @@
|
||||
"AccountPushUpdate": "更新帳號推送",
|
||||
"AccountReport": "帳號報表",
|
||||
"AccountResult": "帳號改密成功/失敗",
|
||||
"AccountSecretReadDisabled": "帳號密碼讀取功能已被管理員禁用",
|
||||
"AccountSelectHelpText": "帳號清單所加入的是使用者名稱",
|
||||
"AccountSessions": "帳號會話",
|
||||
"AccountStatisticsReport": "帳號統計報告",
|
||||
@@ -286,7 +283,6 @@
|
||||
"CACertificate": "CA 證書",
|
||||
"CAS": "CAS",
|
||||
"CMPP2": "CMPP v2.0",
|
||||
"CTYun": "天翼雲",
|
||||
"CTYunPrivate": "天翼私有雲",
|
||||
"CalculationResults": "呼叫記錄",
|
||||
"CallRecords": "調用記錄",
|
||||
@@ -1185,8 +1181,6 @@
|
||||
"RetrySelected": "重新嘗試所選",
|
||||
"Review": "審查",
|
||||
"Reviewer": "審批人",
|
||||
"Revoke": "撤銷",
|
||||
"Risk": "風險",
|
||||
"RiskDetection": "風險檢測",
|
||||
"RiskDetectionDetail": "風險檢測詳情",
|
||||
"RiskyAccount": "風險帳號",
|
||||
@@ -1650,7 +1644,6 @@
|
||||
"overwriteProtocolsAndPortsMsg": "此操作將覆蓋所有協議和端口,是否繼續?",
|
||||
"pleaseSelectAssets": "請選擇資產",
|
||||
"removeWarningMsg": "你確定要移除",
|
||||
"selectFiles": "已選擇{number}文件",
|
||||
"selectedAssets": "已選資產",
|
||||
"setVariable": "設置參數",
|
||||
"userId": "用戶ID",
|
||||
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "Start time",
|
||||
"success": "Success",
|
||||
"system user": "System user",
|
||||
"user": "User",
|
||||
"tabLimits": "15 tabs are currently open.\nTo ensure system stability, would you like to open Luna in a new browser tab to continue?"
|
||||
"user": "User"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "Hora de inicio",
|
||||
"success": "Éxito",
|
||||
"system user": "Usuario del sistema",
|
||||
"tabLimits": "Actualmente tienes 15 pestañas abiertas. \n¿Para garantizar la estabilidad del sistema, deberías abrir Luna en una nueva pestaña del navegador para continuar con la operación?",
|
||||
"user": "Usuario"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "開始時間",
|
||||
"success": "成功",
|
||||
"system user": "システムユーザー",
|
||||
"tabLimits": "現在、15個のタブが開かれています。システムの安定性を確保するために、新しいブラウザのタブでLunaを開いて操作を続けますか?",
|
||||
"user": "ユーザー"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "시작 시간",
|
||||
"success": "성공",
|
||||
"system user": "시스템 사용자",
|
||||
"tabLimits": "현재 15개의 탭이 열려 있습니다. 시스템의 안정성을 위해 Luna를 계속 사용하려면 새로운 브라우저 탭에서 열어보시겠습니까?",
|
||||
"user": "사용자"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "Hora de início",
|
||||
"success": " Sucesso",
|
||||
"system user": "Usuário do Sistema",
|
||||
"tabLimits": "Atualmente, 15 abas estão abertas. Para garantir a estabilidade do sistema, você deseja abrir o Luna em uma nova aba do navegador para continuar a operação?",
|
||||
"user": "Usuário"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "время начала",
|
||||
"success": "успешно",
|
||||
"system user": "системный пользователь",
|
||||
"tabLimits": "В данный момент открыто 15 вкладок. \nЧтобы обеспечить стабильность системы, стоит ли открыть Luna в новой вкладке браузера для продолжения работы?",
|
||||
"user": "пользователь"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "Thời gian bắt đầu",
|
||||
"success": "Thành công",
|
||||
"system user": "Tên đăng nhập",
|
||||
"tabLimits": "Hiện tại đã mở 15 tab. \nĐể đảm bảo tính ổn định của hệ thống, có qua tab trình duyệt mới để mở Luna và tiếp tục thao tác không?",
|
||||
"user": "Người dùng"
|
||||
}
|
||||
@@ -288,6 +288,5 @@
|
||||
"start time": "开始时间",
|
||||
"success": "成功",
|
||||
"system user": "系统用户",
|
||||
"user": "用户",
|
||||
"tabLimits": "当前已打开 15 个标签页。\n为保证系统稳定是否在新的浏览器标签页中打开 Luna 以继续操作?"
|
||||
"user": "用户"
|
||||
}
|
||||
@@ -289,6 +289,5 @@
|
||||
"start time": "開始時間",
|
||||
"success": "成功",
|
||||
"system user": "系統用戶",
|
||||
"tabLimits": "當前已打開 15 個標籤頁。 \n為了確保系統穩定,是否在新的瀏覽器標籤頁中打開 Luna 以繼續操作?",
|
||||
"user": "用戶"
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
from collections import defaultdict
|
||||
|
||||
from django.core.cache import cache
|
||||
from django.db.models import Count, Max, F, CharField, Q
|
||||
from django.db.models.functions import Cast
|
||||
from django.http.response import JsonResponse
|
||||
@@ -145,7 +144,6 @@ class DateTimeMixin:
|
||||
|
||||
|
||||
class DatesLoginMetricMixin:
|
||||
days: int
|
||||
dates_list: list
|
||||
date_start_end: tuple
|
||||
command_type_queryset_list: list
|
||||
@@ -157,8 +155,6 @@ class DatesLoginMetricMixin:
|
||||
operate_logs_queryset: OperateLog.objects
|
||||
password_change_logs_queryset: PasswordChangeLog.objects
|
||||
|
||||
CACHE_TIMEOUT = 60
|
||||
|
||||
@lazyproperty
|
||||
def get_type_to_assets(self):
|
||||
result = Asset.objects.annotate(type=F('platform__type')). \
|
||||
@@ -218,34 +214,19 @@ class DatesLoginMetricMixin:
|
||||
return date_metrics_dict.get('id', [])
|
||||
|
||||
def get_dates_login_times_assets(self):
|
||||
cache_key = f"stats:top10_assets:{self.days}"
|
||||
data = cache.get(cache_key)
|
||||
if data is not None:
|
||||
return data
|
||||
|
||||
assets = self.sessions_queryset.values("asset") \
|
||||
.annotate(total=Count("asset")) \
|
||||
.annotate(last=Cast(Max("date_start"), output_field=CharField())) \
|
||||
.order_by("-total")
|
||||
|
||||
result = list(assets[:10])
|
||||
cache.set(cache_key, result, self.CACHE_TIMEOUT)
|
||||
return result
|
||||
return list(assets[:10])
|
||||
|
||||
def get_dates_login_times_users(self):
|
||||
cache_key = f"stats:top10_users:{self.days}"
|
||||
data = cache.get(cache_key)
|
||||
if data is not None:
|
||||
return data
|
||||
|
||||
users = self.sessions_queryset.values("user_id") \
|
||||
.annotate(total=Count("user_id")) \
|
||||
.annotate(user=Max('user')) \
|
||||
.annotate(last=Cast(Max("date_start"), output_field=CharField())) \
|
||||
.order_by("-total")
|
||||
result = list(users[:10])
|
||||
cache.set(cache_key, result, self.CACHE_TIMEOUT)
|
||||
return result
|
||||
return list(users[:10])
|
||||
|
||||
def get_dates_login_record_sessions(self):
|
||||
sessions = self.sessions_queryset.order_by('-date_start')
|
||||
|
||||
@@ -13,11 +13,11 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import types
|
||||
from importlib import import_module
|
||||
from urllib.parse import urljoin, urlparse, quote
|
||||
|
||||
import sys
|
||||
import yaml
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
@@ -575,7 +575,6 @@ class Config(dict):
|
||||
],
|
||||
'SECURITY_SERVICE_ACCOUNT_REGISTRATION': 'auto',
|
||||
'SECURITY_VIEW_AUTH_NEED_MFA': True,
|
||||
'SECURITY_ACCOUNT_SECRET_READ': True,
|
||||
'SECURITY_MAX_IDLE_TIME': 30,
|
||||
'SECURITY_MAX_SESSION_TIME': 24,
|
||||
'SECURITY_PASSWORD_EXPIRATION_TIME': 9999,
|
||||
@@ -699,7 +698,6 @@ class Config(dict):
|
||||
'LIMIT_SUPER_PRIV': False,
|
||||
|
||||
# Chat AI
|
||||
'IS_CUSTOM_MODEL': False,
|
||||
'CHAT_AI_ENABLED': False,
|
||||
'CHAT_AI_METHOD': 'api',
|
||||
'CHAT_AI_EMBED_URL': '',
|
||||
@@ -708,12 +706,10 @@ class Config(dict):
|
||||
'GPT_API_KEY': '',
|
||||
'GPT_PROXY': '',
|
||||
'GPT_MODEL': 'gpt-4o-mini',
|
||||
'CUSTOM_GPT_MODEL': 'gpt-4o-mini',
|
||||
'DEEPSEEK_BASE_URL': '',
|
||||
'DEEPSEEK_API_KEY': '',
|
||||
'DEEPSEEK_PROXY': '',
|
||||
'DEEPSEEK_MODEL': 'deepseek-chat',
|
||||
'CUSTOM_DEEPSEEK_MODEL': 'deepseek-chat',
|
||||
'VIRTUAL_APP_ENABLED': False,
|
||||
|
||||
'FILE_UPLOAD_SIZE_LIMIT_MB': 200,
|
||||
@@ -721,6 +717,11 @@ class Config(dict):
|
||||
'TICKET_APPLY_ASSET_SCOPE': 'all',
|
||||
'LEAK_PASSWORD_DB_PATH': os.path.join(PROJECT_DIR, 'data', 'system', 'leak_passwords.db'),
|
||||
|
||||
# Ansible Receptor
|
||||
'RECEPTOR_ENABLED': False,
|
||||
'ANSIBLE_RECEPTOR_GATEWAY_PROXY_HOST': 'jms_celery',
|
||||
'ANSIBLE_RECEPTOR_TCP_LISTEN_ADDRESS': 'receptor:7521',
|
||||
|
||||
'FILE_UPLOAD_TEMP_DIR': None,
|
||||
|
||||
'LOKI_LOG_ENABLED': False,
|
||||
|
||||
@@ -160,7 +160,6 @@ CAS_USERNAME_ATTRIBUTE = CONFIG.CAS_USERNAME_ATTRIBUTE
|
||||
CAS_APPLY_ATTRIBUTES_TO_USER = CONFIG.CAS_APPLY_ATTRIBUTES_TO_USER
|
||||
CAS_RENAME_ATTRIBUTES = CONFIG.CAS_RENAME_ATTRIBUTES
|
||||
CAS_CREATE_USER = True
|
||||
CAS_STORE_NEXT = True
|
||||
|
||||
# SSO auth
|
||||
AUTH_SSO = CONFIG.AUTH_SSO
|
||||
|
||||
@@ -60,7 +60,6 @@ VERIFY_CODE_TTL = CONFIG.VERIFY_CODE_TTL
|
||||
SECURITY_MFA_VERIFY_TTL = CONFIG.SECURITY_MFA_VERIFY_TTL
|
||||
SECURITY_UNCOMMON_USERS_TTL = CONFIG.SECURITY_UNCOMMON_USERS_TTL
|
||||
SECURITY_VIEW_AUTH_NEED_MFA = CONFIG.SECURITY_VIEW_AUTH_NEED_MFA
|
||||
SECURITY_ACCOUNT_SECRET_READ = CONFIG.SECURITY_ACCOUNT_SECRET_READ
|
||||
SECURITY_SERVICE_ACCOUNT_REGISTRATION = CONFIG.SECURITY_SERVICE_ACCOUNT_REGISTRATION
|
||||
SECURITY_LOGIN_CAPTCHA_ENABLED = CONFIG.SECURITY_LOGIN_CAPTCHA_ENABLED
|
||||
SECURITY_MFA_IN_LOGIN_PAGE = CONFIG.SECURITY_MFA_IN_LOGIN_PAGE
|
||||
@@ -239,9 +238,6 @@ LIMIT_SUPER_PRIV = CONFIG.LIMIT_SUPER_PRIV
|
||||
ASSET_SIZE = 'small'
|
||||
|
||||
# Chat AI
|
||||
IS_CUSTOM_MODEL = CONFIG.IS_CUSTOM_MODEL
|
||||
CUSTOM_GPT_MODEL = CONFIG.CUSTOM_GPT_MODEL
|
||||
CUSTOM_DEEPSEEK_MODEL = CONFIG.CUSTOM_DEEPSEEK_MODEL
|
||||
CHAT_AI_ENABLED = CONFIG.CHAT_AI_ENABLED
|
||||
CHAT_AI_METHOD = CONFIG.CHAT_AI_METHOD
|
||||
CHAT_AI_EMBED_URL = CONFIG.CHAT_AI_EMBED_URL
|
||||
@@ -261,10 +257,15 @@ FILE_UPLOAD_SIZE_LIMIT_MB = CONFIG.FILE_UPLOAD_SIZE_LIMIT_MB
|
||||
|
||||
TICKET_APPLY_ASSET_SCOPE = CONFIG.TICKET_APPLY_ASSET_SCOPE
|
||||
|
||||
# Ansible Receptor
|
||||
RECEPTOR_ENABLED = CONFIG.RECEPTOR_ENABLED
|
||||
ANSIBLE_RECEPTOR_GATEWAY_PROXY_HOST = CONFIG.ANSIBLE_RECEPTOR_GATEWAY_PROXY_HOST
|
||||
ANSIBLE_RECEPTOR_TCP_LISTEN_ADDRESS = CONFIG.ANSIBLE_RECEPTOR_TCP_LISTEN_ADDRESS
|
||||
|
||||
LOKI_LOG_ENABLED = CONFIG.LOKI_LOG_ENABLED
|
||||
LOKI_BASE_URL = CONFIG.LOKI_BASE_URL
|
||||
|
||||
TOOL_USER_ENABLED = CONFIG.TOOL_USER_ENABLED
|
||||
|
||||
SUGGESTION_LIMIT = CONFIG.SUGGESTION_LIMIT
|
||||
MCP_ENABLED = CONFIG.MCP_ENABLED
|
||||
MCP_ENABLED = CONFIG.MCP_ENABLED
|
||||
@@ -2,7 +2,6 @@
|
||||
#
|
||||
import os
|
||||
import time
|
||||
|
||||
from .base import (
|
||||
REDIS_SSL_CA, REDIS_SSL_CERT, REDIS_SSL_KEY, REDIS_SSL_REQUIRED, REDIS_USE_SSL,
|
||||
REDIS_PROTOCOL, REDIS_SENTINEL_SERVICE_NAME, REDIS_SENTINELS, REDIS_SENTINEL_PASSWORD,
|
||||
@@ -31,11 +30,11 @@ REST_FRAMEWORK = {
|
||||
),
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
# 'rest_framework.authentication.BasicAuthentication',
|
||||
"oauth2_provider.contrib.rest_framework.OAuth2Authentication",
|
||||
'authentication.backends.drf.AccessTokenAuthentication',
|
||||
'authentication.backends.drf.PrivateTokenAuthentication',
|
||||
'authentication.backends.drf.ServiceAuthentication',
|
||||
'authentication.backends.drf.SignatureAuthentication',
|
||||
'authentication.backends.drf.PrivateTokenAuthentication',
|
||||
'authentication.backends.drf.AccessTokenAuthentication',
|
||||
"oauth2_provider.contrib.rest_framework.OAuth2Authentication",
|
||||
'authentication.backends.drf.SessionAuthentication',
|
||||
),
|
||||
'DEFAULT_FILTER_BACKENDS': (
|
||||
@@ -233,8 +232,4 @@ OAUTH2_PROVIDER = {
|
||||
'REFRESH_TOKEN_EXPIRE_SECONDS': CONFIG.OAUTH2_PROVIDER_REFRESH_TOKEN_EXPIRE_SECONDS,
|
||||
}
|
||||
OAUTH2_PROVIDER_CLIENT_REDIRECT_URI = 'jms://auth/callback'
|
||||
OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME = 'JumpServer Client'
|
||||
|
||||
if CONFIG.DEBUG_DEV:
|
||||
OAUTH2_PROVIDER['ALLOWED_REDIRECT_URI_SCHEMES'].append('http')
|
||||
OAUTH2_PROVIDER_CLIENT_REDIRECT_URI += ' http://127.0.0.1:14876/auth/callback'
|
||||
OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME = 'JumpServer Client'
|
||||
@@ -115,11 +115,7 @@ LOGGING = {
|
||||
'azure': {
|
||||
'handlers': ['null'],
|
||||
'level': 'ERROR'
|
||||
},
|
||||
'oauth2_provider': {
|
||||
'handlers': ['console', 'file'],
|
||||
'level': LOG_LEVEL,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ class ResourceDownload(TemplateView):
|
||||
OPENSSH_VERSION=v9.4.0.0
|
||||
TINKER_VERSION=v0.1.6
|
||||
VIDEO_PLAYER_VERSION=0.6.0
|
||||
CLIENT_VERSION=4.1.0
|
||||
CLIENT_VERSION=4.0.0
|
||||
"""
|
||||
|
||||
def get_meta_json(self):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from django.conf import settings
|
||||
from django.utils.functional import LazyObject
|
||||
|
||||
from ops.ansible import AnsibleNativeRunner
|
||||
@@ -14,7 +15,9 @@ class _LazyRunnerInterface(LazyObject):
|
||||
@staticmethod
|
||||
def make_interface():
|
||||
runner_type = AnsibleNativeRunner
|
||||
return RunnerInterface(runner_type=runner_type, gateway_proxy_host='127.0.0.1')
|
||||
gateway_host = settings.ANSIBLE_RECEPTOR_GATEWAY_PROXY_HOST \
|
||||
if settings.ANSIBLE_RECEPTOR_GATEWAY_PROXY_HOST else '127.0.0.1'
|
||||
return RunnerInterface(runner_type=runner_type, gateway_proxy_host=gateway_host)
|
||||
|
||||
|
||||
interface = _LazyRunnerInterface()
|
||||
|
||||
@@ -187,9 +187,6 @@ verbose_name_mapper = {
|
||||
'rbac.view_permission': _('View permission tree'),
|
||||
'authentication.passkey': _("Passkey"),
|
||||
'oauth2_provider.accesstoken': _("Access token"),
|
||||
'oauth2_provider.view_accesstoken': _("View access token"),
|
||||
'oauth2_provider.delete_accesstoken': _("Revoke access token"),
|
||||
|
||||
}
|
||||
|
||||
xpack_nodes = [
|
||||
|
||||
@@ -42,22 +42,16 @@ class ChatAITestingAPI(GenericAPIView):
|
||||
)
|
||||
|
||||
tp = config['CHAT_AI_TYPE']
|
||||
is_custom_model = config['IS_CUSTOM_MODEL']
|
||||
if tp == ChatAITypeChoices.gpt:
|
||||
url = config['GPT_BASE_URL']
|
||||
api_key = config['GPT_API_KEY']
|
||||
proxy = config['GPT_PROXY']
|
||||
model = config['GPT_MODEL']
|
||||
custom_model = config['CUSTOM_GPT_MODEL']
|
||||
else:
|
||||
url = config['DEEPSEEK_BASE_URL']
|
||||
api_key = config['DEEPSEEK_API_KEY']
|
||||
proxy = config['DEEPSEEK_PROXY']
|
||||
model = config['DEEPSEEK_MODEL']
|
||||
custom_model = config['CUSTOM_DEEPSEEK_MODEL']
|
||||
|
||||
model = custom_model or model \
|
||||
if is_custom_model else model
|
||||
|
||||
kwargs = {
|
||||
'base_url': url or None,
|
||||
|
||||
@@ -222,4 +222,4 @@ class ClientVersionView(APIView):
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
return Response(['4.0.0', '4.1.0'], status=status.HTTP_200_OK)
|
||||
return Response(['4.0.0'], status=status.HTTP_200_OK)
|
||||
|
||||
@@ -19,23 +19,11 @@ class ChatAITypeChoices(TextChoices):
|
||||
|
||||
|
||||
class GPTModelChoices(TextChoices):
|
||||
# 🚀 Latest flagship dialogue model
|
||||
GPT_5_2 = 'gpt-5.2', 'gpt-5.2'
|
||||
GPT_5_2_PRO = 'gpt-5.2-pro', 'gpt-5.2-pro'
|
||||
|
||||
GPT_5_1 = 'gpt-5.1', 'gpt-5.1'
|
||||
GPT_5 = 'gpt-5', 'gpt-5'
|
||||
|
||||
# 💡 Lightweight & Cost-Friendly Version
|
||||
GPT_5_MINI = 'gpt-5-mini', 'gpt-5-mini'
|
||||
GPT_5_NANO = 'gpt-5-nano', 'gpt-5-nano'
|
||||
|
||||
# 🧠 GPT-4 series of dialogues (still supports chat tasks)
|
||||
GPT_4O = 'gpt-4o', 'gpt-4o'
|
||||
GPT_4O_MINI = 'gpt-4o-mini', 'gpt-4o-mini'
|
||||
GPT_4_1 = 'gpt-4.1', 'gpt-4.1'
|
||||
GPT_4_1_MINI = 'gpt-4.1-mini', 'gpt-4.1-mini'
|
||||
GPT_4_1_NANO = 'gpt-4.1-nano', 'gpt-4.1-nano'
|
||||
gpt_4o_mini = 'gpt-4o-mini', 'gpt-4o-mini'
|
||||
gpt_4o = 'gpt-4o', 'gpt-4o'
|
||||
o3_mini = 'o3-mini', 'o3-mini'
|
||||
o1_mini = 'o1-mini', 'o1-mini'
|
||||
o1 = 'o1', 'o1'
|
||||
|
||||
|
||||
class DeepSeekModelChoices(TextChoices):
|
||||
|
||||
@@ -203,16 +203,12 @@ def get_chatai_data():
|
||||
'proxy': settings.GPT_PROXY,
|
||||
'model': settings.GPT_MODEL,
|
||||
}
|
||||
custom_model = settings.CUSTOM_GPT_MODEL
|
||||
if settings.CHAT_AI_TYPE != ChatAITypeChoices.gpt:
|
||||
data['url'] = settings.DEEPSEEK_BASE_URL
|
||||
data['api_key'] = settings.DEEPSEEK_API_KEY
|
||||
data['proxy'] = settings.DEEPSEEK_PROXY
|
||||
data['model'] = settings.DEEPSEEK_MODEL
|
||||
custom_model = settings.CUSTOM_DEEPSEEK_MODEL
|
||||
|
||||
data['model'] = custom_model or data['model'] \
|
||||
if settings.IS_CUSTOM_MODEL else data['model']
|
||||
return data
|
||||
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ class ChatAISettingSerializer(serializers.Serializer):
|
||||
help_text=_('The proxy server address of the GPT service. For example: http://ip:port')
|
||||
)
|
||||
GPT_MODEL = serializers.ChoiceField(
|
||||
default=GPTModelChoices.GPT_4_1_MINI, choices=GPTModelChoices.choices,
|
||||
default=GPTModelChoices.gpt_4o_mini, choices=GPTModelChoices.choices,
|
||||
label=_("GPT Model"), required=False,
|
||||
)
|
||||
DEEPSEEK_BASE_URL = serializers.CharField(
|
||||
@@ -168,18 +168,6 @@ class ChatAISettingSerializer(serializers.Serializer):
|
||||
default=DeepSeekModelChoices.deepseek_chat, choices=DeepSeekModelChoices.choices,
|
||||
label=_("DeepSeek Model"), required=False,
|
||||
)
|
||||
IS_CUSTOM_MODEL = serializers.BooleanField(
|
||||
required=False, default=False, label=_("Custom Model"),
|
||||
help_text=_("Whether to use a custom model")
|
||||
)
|
||||
CUSTOM_GPT_MODEL = serializers.CharField(
|
||||
max_length=256, allow_blank=True,
|
||||
required=False, label=_('Custom gpt model'),
|
||||
)
|
||||
CUSTOM_DEEPSEEK_MODEL = serializers.CharField(
|
||||
max_length=256, allow_blank=True,
|
||||
required=False, label=_('Custom DeepSeek model'),
|
||||
)
|
||||
|
||||
|
||||
class TicketSettingSerializer(serializers.Serializer):
|
||||
|
||||
@@ -21,7 +21,6 @@ class PrivateSettingSerializer(PublicSettingSerializer):
|
||||
TICKET_AUTHORIZE_DEFAULT_TIME_UNIT = serializers.CharField()
|
||||
AUTH_LDAP_SYNC_ORG_IDS = serializers.ListField()
|
||||
SECURITY_MAX_IDLE_TIME = serializers.IntegerField()
|
||||
SECURITY_ACCOUNT_SECRET_READ = serializers.BooleanField()
|
||||
SECURITY_VIEW_AUTH_NEED_MFA = serializers.BooleanField()
|
||||
SECURITY_MFA_AUTH = serializers.IntegerField()
|
||||
SECURITY_MFA_VERIFY_TTL = serializers.IntegerField()
|
||||
|
||||
@@ -12,8 +12,6 @@ from settings.utils import generate_ips
|
||||
|
||||
# From /usr/include/linux/icmp.h; your milage may vary.
|
||||
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
|
||||
ICMPV6_ECHO_REQUEST = 128
|
||||
ICMPV6_ECHO_REPLY = 129
|
||||
|
||||
|
||||
def checksum(source_string):
|
||||
@@ -43,15 +41,7 @@ def checksum(source_string):
|
||||
return answer
|
||||
|
||||
|
||||
def _get_icmp_header_offset(received_packet, family):
|
||||
if family != socket.AF_INET6:
|
||||
return 20
|
||||
if received_packet and (received_packet[0] >> 4) == 6:
|
||||
return 40
|
||||
return 0
|
||||
|
||||
|
||||
def receive_one_ping(my_socket, id, timeout, family):
|
||||
def receive_one_ping(my_socket, id, timeout):
|
||||
"""
|
||||
Receive the ping from the socket.
|
||||
"""
|
||||
@@ -65,20 +55,11 @@ def receive_one_ping(my_socket, id, timeout, family):
|
||||
|
||||
time_received = time.time()
|
||||
received_packet, addr = my_socket.recvfrom(1024)
|
||||
header_offset = _get_icmp_header_offset(received_packet, family)
|
||||
icmpHeader = received_packet[header_offset:header_offset + 8]
|
||||
if len(icmpHeader) < 8:
|
||||
continue
|
||||
type, code, checksum, packet_id, sequence = struct.unpack("BBHHH", icmpHeader)
|
||||
if family == socket.AF_INET6 and type != ICMPV6_ECHO_REPLY:
|
||||
continue
|
||||
icmpHeader = received_packet[20:28]
|
||||
type, code, checksum, packet_id, sequence = struct.unpack("bbHHh", icmpHeader)
|
||||
if packet_id == id:
|
||||
bytes = struct.calcsize("d")
|
||||
if len(received_packet) < header_offset + 8 + bytes:
|
||||
continue
|
||||
time_sent = struct.unpack(
|
||||
"d", received_packet[header_offset + 8: header_offset + 8 + bytes]
|
||||
)[0]
|
||||
time_sent = struct.unpack("d", received_packet[28: 28 + bytes])[0]
|
||||
return time_received - time_sent
|
||||
|
||||
time_left -= how_long_in_select
|
||||
@@ -86,19 +67,11 @@ def receive_one_ping(my_socket, id, timeout, family):
|
||||
return
|
||||
|
||||
|
||||
def send_one_ping(my_socket, dest_addr, id, psize, family):
|
||||
def send_one_ping(my_socket, dest_addr, id, psize):
|
||||
"""
|
||||
Send one ping to the given >dest_addr<.
|
||||
"""
|
||||
if family == socket.AF_INET6:
|
||||
dest_addr = dest_addr
|
||||
icmp_type = ICMPV6_ECHO_REQUEST
|
||||
else:
|
||||
if isinstance(dest_addr, tuple):
|
||||
dest_addr = (dest_addr[0], 1)
|
||||
else:
|
||||
dest_addr = (socket.gethostbyname(dest_addr), 1)
|
||||
icmp_type = ICMP_ECHO_REQUEST
|
||||
dest_addr = socket.gethostbyname(dest_addr)
|
||||
|
||||
# Remove header size from packet size
|
||||
# psize = psize - 8
|
||||
@@ -111,45 +84,33 @@ def send_one_ping(my_socket, dest_addr, id, psize, family):
|
||||
my_checksum = 0
|
||||
|
||||
# Make a dummy heder with a 0 checksum.
|
||||
header = struct.pack("BBHHH", icmp_type, 0, my_checksum, id, 1)
|
||||
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, id, 1)
|
||||
bytes = struct.calcsize("d")
|
||||
data = (psize - bytes) * b"Q"
|
||||
data = struct.pack("d", time.time()) + data
|
||||
|
||||
if family != socket.AF_INET6:
|
||||
# Calculate the checksum on the data and the dummy header.
|
||||
my_checksum = checksum(header + data)
|
||||
# Calculate the checksum on the data and the dummy header.
|
||||
my_checksum = checksum(header + data)
|
||||
|
||||
# Now that we have the right checksum, we put that in. It's just easier
|
||||
# to make up a new header than to stuff it into the dummy.
|
||||
header = struct.pack(
|
||||
"BBHHH", icmp_type, 0, socket.htons(my_checksum), id, 1
|
||||
"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), id, 1
|
||||
)
|
||||
packet = header + data
|
||||
my_socket.sendto(packet, dest_addr)
|
||||
|
||||
|
||||
def resolve_dest_addr(dest_addr):
|
||||
addrinfos = socket.getaddrinfo(
|
||||
dest_addr, None, socket.AF_UNSPEC, socket.SOCK_DGRAM
|
||||
)
|
||||
family, _, _, _, sockaddr = addrinfos[0]
|
||||
return family, sockaddr
|
||||
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
|
||||
|
||||
|
||||
def ping(dest_addr, timeout, psize, flag=0):
|
||||
"""
|
||||
Returns either the delay (in seconds) or none on timeout.
|
||||
"""
|
||||
family, dest_sockaddr = resolve_dest_addr(dest_addr)
|
||||
if family == socket.AF_INET6:
|
||||
icmp = socket.IPPROTO_ICMPV6
|
||||
sock_type = socket.SOCK_DGRAM
|
||||
else:
|
||||
icmp = socket.getprotobyname("icmp")
|
||||
sock_type = socket.SOCK_DGRAM if os.getuid() != 0 else socket.SOCK_RAW
|
||||
icmp = socket.getprotobyname("icmp")
|
||||
try:
|
||||
my_socket = socket.socket(family, sock_type, icmp)
|
||||
if os.getuid() != 0:
|
||||
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, icmp)
|
||||
else:
|
||||
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
|
||||
except socket.error as e:
|
||||
if e.errno == 1:
|
||||
# Operation not permitted
|
||||
@@ -161,8 +122,8 @@ def ping(dest_addr, timeout, psize, flag=0):
|
||||
flag &= 0x00FF
|
||||
my_id = process_pre | flag
|
||||
|
||||
send_one_ping(my_socket, dest_sockaddr, my_id, psize, family)
|
||||
delay = receive_one_ping(my_socket, my_id, timeout, family)
|
||||
send_one_ping(my_socket, dest_addr, my_id, psize)
|
||||
delay = receive_one_ping(my_socket, my_id, timeout)
|
||||
|
||||
my_socket.close()
|
||||
return delay
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
.alert.alert-msg {
|
||||
background: #F5F5F7;
|
||||
}
|
||||
|
||||
.target-url {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
@@ -14,99 +18,29 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
vertical-align: middle;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 重定向中的样式 */
|
||||
.confirm-container {
|
||||
transition: opacity 0.3s ease-out;
|
||||
}
|
||||
</style>
|
||||
<div>
|
||||
<!-- 确认内容 -->
|
||||
<div class="confirm-container" id="confirmContainer">
|
||||
<p>
|
||||
<div class="alert {% if error %} alert-danger {% else %} alert-info {% endif %}" id="messages">
|
||||
{% trans 'You are about to be redirected to an external website.' %}
|
||||
<br/>
|
||||
<br/>
|
||||
{% trans 'Please confirm that you trust this link: ' %}
|
||||
<br/>
|
||||
<br/>
|
||||
<a class="target-url" href="javascript:void(0)" onclick="handleRedirect(event)">{{ target_url }}</a>
|
||||
</div>
|
||||
</p>
|
||||
<p>
|
||||
<div class="alert {% if error %} alert-danger {% else %} alert-info {% endif %}" id="messages">
|
||||
{% trans 'You are about to be redirected to an external website. Please confirm that you trust this link: ' %}
|
||||
<a class="target-url" href="{{ target_url }}">{{ target_url }}</a>
|
||||
</div>
|
||||
</p>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-sm-3">
|
||||
<a id="backBtn" href="/" class="btn btn-default block full-width m-b">
|
||||
{% trans 'Back' %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="col-sm-3">
|
||||
<a href="javascript:void(0)" onclick="handleRedirect(event)" class="btn btn-primary block full-width m-b">
|
||||
{% trans 'Confirm' %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-sm-3">
|
||||
<a href="/" class="btn btn-default block full-width m-b">
|
||||
{% trans 'Cancel' %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="col-sm-3">
|
||||
<a href="{{ target_url }}" class="btn btn-primary block full-width m-b">
|
||||
{% trans 'Confirm' %}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script>
|
||||
if (sessionStorage.getItem('page_refreshed')) {
|
||||
// 用户刷新了页面,清除标记并跳转到首页
|
||||
sessionStorage.removeItem('page_refreshed');
|
||||
window.location.href = '/';
|
||||
} else {
|
||||
// 第一次加载,设置标记
|
||||
window.addEventListener('beforeunload', function() {
|
||||
sessionStorage.setItem('page_refreshed', 'true');
|
||||
});
|
||||
}
|
||||
|
||||
const targetUrl = '{{ target_url }}';
|
||||
|
||||
let countdownTimer = null;
|
||||
let countdownSeconds = 30;
|
||||
let startedCountdown = false;
|
||||
|
||||
function handleRedirect(event) {
|
||||
if (event) {
|
||||
event.preventDefault();
|
||||
}
|
||||
setTimeout(() => {
|
||||
if (targetUrl.startsWith('jms://')) {
|
||||
if (startedCountdown) {
|
||||
// 已经开始倒计时,直接跳转但不再重置倒计时
|
||||
window.location.href = targetUrl;
|
||||
return;
|
||||
}
|
||||
startedCountdown = true;
|
||||
countdownSeconds = 30;
|
||||
window.location.href = targetUrl;
|
||||
const backBtn = document.getElementById('backBtn');
|
||||
if (backBtn) {
|
||||
const backButtonContent = backBtn.textContent;
|
||||
backBtn.textContent = `${backButtonContent} (${countdownSeconds})`;
|
||||
countdownTimer = setInterval(() => {
|
||||
countdownSeconds--;
|
||||
if (countdownSeconds > 0) {
|
||||
backBtn.textContent = `${backButtonContent} (${countdownSeconds})`;
|
||||
} else {
|
||||
backBtn.textContent = `${backButtonContent}`;
|
||||
clearInterval(countdownTimer);
|
||||
countdownTimer = null;
|
||||
window.location.href = '/';
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
} else {
|
||||
window.location.href = targetUrl;
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ class Handler(BaseHandler):
|
||||
self._create_asset_permission()
|
||||
|
||||
def _create_asset_permission(self):
|
||||
self.ticket.refresh_from_db()
|
||||
org_id = self.ticket.org_id
|
||||
with tmp_to_org(org_id):
|
||||
asset_permission = AssetPermission.objects.filter(id=self.ticket.id).first()
|
||||
|
||||
@@ -139,7 +139,7 @@ class BlockUtilBase:
|
||||
username = username.lower() if username else ''
|
||||
self.username = username
|
||||
self.ip = ip
|
||||
self.limit_key = self.LIMIT_KEY_TMPL.format(username)
|
||||
self.limit_key = self.LIMIT_KEY_TMPL.format(username, ip)
|
||||
self.block_key = self.BLOCK_KEY_TMPL.format(username)
|
||||
self.key_ttl = int(settings.SECURITY_LOGIN_LIMIT_TIME) * 60
|
||||
|
||||
@@ -236,12 +236,12 @@ class BlockGlobalIpUtilBase:
|
||||
|
||||
|
||||
class LoginBlockUtil(BlockUtilBase):
|
||||
LIMIT_KEY_TMPL = "_LOGIN_LIMIT_{}"
|
||||
LIMIT_KEY_TMPL = "_LOGIN_LIMIT_{}_{}"
|
||||
BLOCK_KEY_TMPL = "_LOGIN_BLOCK_{}"
|
||||
|
||||
|
||||
class MFABlockUtils(BlockUtilBase):
|
||||
LIMIT_KEY_TMPL = "_MFA_LIMIT_{}"
|
||||
LIMIT_KEY_TMPL = "_MFA_LIMIT_{}_{}"
|
||||
BLOCK_KEY_TMPL = "_MFA_BLOCK_{}"
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ dependencies = [
|
||||
'aiofiles==23.1.0',
|
||||
'amqp==5.1.1',
|
||||
'ansible-core',
|
||||
'ansible==7.1.0',
|
||||
'ansible==12.2.0',
|
||||
'ansible-runner',
|
||||
'asn1crypto==1.5.1',
|
||||
'bcrypt==4.0.1',
|
||||
|
||||
@@ -19,3 +19,10 @@ fi
|
||||
echo "4. For Apple processor"
|
||||
LDFLAGS="-L$(brew --prefix freetds)/lib -L$(brew --prefix openssl@1.1)/lib" CFLAGS="-I$(brew --prefix freetds)/include" pip install $(grep 'pymssql' requirements.txt)
|
||||
export PKG_CONFIG_PATH="/opt/homebrew/opt/mysql-client/lib/pkgconfig"
|
||||
|
||||
|
||||
echo "5. Install Ansible Receptor"
|
||||
export RECEPTOR_VERSION=v1.4.5
|
||||
export ARCH=`arch`
|
||||
wget -O ${TMPDIR}receptor.tar.gz https://github.com/ansible/receptor/releases/download/${RECEPTOR_VERSION}/receptor_${RECEPTOR_VERSION/v/}_darwin_${ARCH}.tar.gz
|
||||
tar -xf ${TMPDIR}receptor.tar.gz -C /opt/homebrew/bin/
|
||||
Reference in New Issue
Block a user