Compare commits

..

1 Commits

Author SHA1 Message Date
老广
4be20515ca Add issue spam configuration file 2025-11-06 18:13:26 +08:00
137 changed files with 3927 additions and 5410 deletions

View File

@@ -1,72 +1,74 @@
name: Build and Push Base Image
on:
pull_request:
branches:
- 'dev'
- 'v*'
paths:
- poetry.lock
- pyproject.toml
- Dockerfile-base
- package.json
- go.mod
- yarn.lock
- pom.xml
- install_deps.sh
- utils/clean_site_packages.sh
types:
- opened
- synchronize
- reopened
pull_request:
branches:
- 'dev'
- 'v*'
paths:
- poetry.lock
- pyproject.toml
- Dockerfile-base
- package.json
- go.mod
- yarn.lock
- pom.xml
- install_deps.sh
- utils/clean_site_packages.sh
types:
- opened
- synchronize
- reopened
jobs:
build-and-push:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
build-and-push:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
image: tonistiigi/binfmt:qemu-v7.0.0-28
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract date
id: vars
run: echo "IMAGE_TAG=$(date +'%Y%m%d_%H%M%S')" >> $GITHUB_ENV
- name: Extract date
id: vars
run: echo "IMAGE_TAG=$(date +'%Y%m%d_%H%M%S')" >> $GITHUB_ENV
- name: Extract repository name
id: repo
run: echo "REPO=$(basename ${{ github.repository }})" >> $GITHUB_ENV
- name: Extract repository name
id: repo
run: echo "REPO=$(basename ${{ github.repository }})" >> $GITHUB_ENV
- name: Build and push multi-arch image
uses: docker/build-push-action@v6
with:
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile-base
tags: jumpserver/core-base:${{ env.IMAGE_TAG }}
- name: Build and push multi-arch image
uses: docker/build-push-action@v6
with:
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile-base
tags: jumpserver/core-base:${{ env.IMAGE_TAG }}
- name: Update Dockerfile
run: |
sed -i 's|-base:.* AS stage-build|-base:${{ env.IMAGE_TAG }} AS stage-build|' Dockerfile
- name: Update Dockerfile
run: |
sed -i 's|-base:.* AS stage-build|-base:${{ env.IMAGE_TAG }} AS stage-build|' Dockerfile
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add Dockerfile
git commit -m "perf: Update Dockerfile with new base image tag"
git push origin ${{ github.event.pull_request.head.ref }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add Dockerfile
git commit -m "perf: Update Dockerfile with new base image tag"
git push origin ${{ github.event.pull_request.head.ref }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,33 +1,10 @@
on:
push:
pull_request:
types: [opened, synchronize, closed]
release:
types: [created]
on: [push, pull_request, release]
name: JumpServer repos generic handler
jobs:
handle_pull_request:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: jumpserver/action-generic-handler@master
env:
GITHUB_TOKEN: ${{ secrets.PRIVATE_TOKEN }}
I18N_TOKEN: ${{ secrets.I18N_TOKEN }}
handle_push:
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- uses: jumpserver/action-generic-handler@master
env:
GITHUB_TOKEN: ${{ secrets.PRIVATE_TOKEN }}
I18N_TOKEN: ${{ secrets.I18N_TOKEN }}
handle_release:
if: github.event_name == 'release'
generic_handler:
name: Run generic handler
runs-on: ubuntu-latest
steps:
- uses: jumpserver/action-generic-handler@master

View File

@@ -1,4 +1,4 @@
FROM jumpserver/core-base:20251128_025056 AS stage-build
FROM jumpserver/core-base:20251014_095903 AS stage-build
ARG VERSION
@@ -19,7 +19,7 @@ RUN set -ex \
&& python manage.py compilemessages
FROM python:3.11-slim-trixie
FROM jumpserver/core-base:python-3.11-slim-bullseye-v1
ENV LANG=en_US.UTF-8 \
PATH=/opt/py3/bin:$PATH
@@ -39,7 +39,7 @@ ARG TOOLS=" \
ARG APT_MIRROR=http://deb.debian.org
RUN set -ex \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list.d/debian.sources \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& apt-get update > /dev/null \
&& apt-get -y install --no-install-recommends ${DEPENDENCIES} \

View File

@@ -1,5 +1,6 @@
FROM python:3.11.14-slim-trixie
FROM jumpserver/core-base:python-3.11-slim-bullseye-v1
ARG TARGETARCH
COPY --from=ghcr.io/astral-sh/uv:0.6.14 /uv /uvx /usr/local/bin/
# Install APT dependencies
ARG DEPENDENCIES=" \
ca-certificates \
@@ -21,7 +22,7 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,id=core \
set -ex \
&& rm -f /etc/apt/apt.conf.d/docker-clean \
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list.d/debian.sources \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list \
&& apt-get update > /dev/null \
&& apt-get -y install --no-install-recommends ${DEPENDENCIES} \
&& echo "no" | dpkg-reconfigure dash
@@ -40,10 +41,12 @@ RUN set -ex \
WORKDIR /opt/jumpserver
ARG PIP_MIRROR=https://pypi.org/simple
ENV POETRY_PYPI_MIRROR_URL=${PIP_MIRROR}
ENV ANSIBLE_COLLECTIONS_PATHS=/opt/py3/lib/python3.11/site-packages/ansible_collections
ENV LANG=en_US.UTF-8 \
PATH=/opt/py3/bin:$PATH
ENV SETUPTOOLS_SCM_PRETEND_VERSION=3.4.5
ENV UV_LINK_MODE=copy
RUN --mount=type=cache,target=/root/.cache \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
@@ -51,7 +54,6 @@ RUN --mount=type=cache,target=/root/.cache \
--mount=type=bind,source=requirements/collections.yml,target=collections.yml \
--mount=type=bind,source=requirements/static_files.sh,target=utils/static_files.sh \
set -ex \
&& pip install uv -i${PIP_MIRROR} \
&& uv venv \
&& uv pip install -i${PIP_MIRROR} -r pyproject.toml \
&& ln -sf $(pwd)/.venv /opt/py3 \

View File

@@ -13,7 +13,7 @@ ARG TOOLS=" \
nmap \
telnet \
vim \
postgresql-client \
postgresql-client-13 \
wget \
poppler-utils"

11
Dockerfile-python Normal file
View File

@@ -0,0 +1,11 @@
FROM python:3.11-slim-bullseye
ARG TARGETARCH
# Install APT dependencies
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
apt-get update; \
apt-get -y --no-install-recommends upgrade; \
rm -rf /var/lib/apt/lists/*
# upgrade pip and setuptools
RUN pip install --no-cache-dir --upgrade pip setuptools wheel

View File

@@ -77,8 +77,7 @@ JumpServer consists of multiple key components, which collectively form the func
| [Luna](https://github.com/jumpserver/luna) | <a href="https://github.com/jumpserver/luna/releases"><img alt="Luna release" src="https://img.shields.io/github/release/jumpserver/luna.svg" /></a> | JumpServer Web Terminal |
| [KoKo](https://github.com/jumpserver/koko) | <a href="https://github.com/jumpserver/koko/releases"><img alt="Koko release" src="https://img.shields.io/github/release/jumpserver/koko.svg" /></a> | JumpServer Character Protocol Connector |
| [Lion](https://github.com/jumpserver/lion) | <a href="https://github.com/jumpserver/lion/releases"><img alt="Lion release" src="https://img.shields.io/github/release/jumpserver/lion.svg" /></a> | JumpServer Graphical Protocol Connector |
| [Chen](https://github.com/jumpserver/chen) | <a href="https://github.com/jumpserver/chen/releases"><img alt="Chen release" src="https://img.shields.io/github/release/jumpserver/chen.svg" /> | JumpServer Web DB
| [Client](https://github.com/jumpserver/clients) | <a href="https://github.com/jumpserver/clients/releases"><img alt="Clients release" src="https://img.shields.io/github/release/jumpserver/clients.svg" /> | JumpServer Client |
| [Chen](https://github.com/jumpserver/chen) | <a href="https://github.com/jumpserver/chen/releases"><img alt="Chen release" src="https://img.shields.io/github/release/jumpserver/chen.svg" /> | JumpServer Web DB |
| [Tinker](https://github.com/jumpserver/tinker) | <img alt="Tinker" src="https://img.shields.io/badge/release-private-red" /> | JumpServer Remote Application Connector (Windows) |
| [Panda](https://github.com/jumpserver/Panda) | <img alt="Panda" src="https://img.shields.io/badge/release-private-red" /> | JumpServer EE Remote Application Connector (Linux) |
| [Razor](https://github.com/jumpserver/razor) | <img alt="Chen" src="https://img.shields.io/badge/release-private-red" /> | JumpServer EE RDP Proxy Connector |

View File

@@ -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 _
@@ -6,7 +5,7 @@ from rest_framework import serializers as drf_serializers
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework.status import HTTP_200_OK
from accounts import serializers
from accounts.const import ChangeSecretRecordStatusChoice
@@ -167,7 +166,7 @@ class AccountViewSet(OrgBulkModelViewSet):
class AccountSecretsViewSet(AccountRecordViewLogMixin, AccountViewSet):
"""
因为可能要导出所有账号,所以单独建立了一个 viewset
因为可能要导出所有账号所以单独建立了一个 viewset
"""
serializer_classes = {
'default': serializers.AccountSecretSerializer,
@@ -204,19 +203,9 @@ class AssetAccountBulkCreateApi(CreateAPIView):
templates = base_payload.pop("template", None)
assets = self.get_all_assets(base_payload)
if not assets.exists():
error = _("No valid assets found for account creation.")
return Response(
data={
"detail": error,
"code": "no_valid_assets"
},
status=HTTP_400_BAD_REQUEST
)
result = []
errors = []
def handle_one(_payload):
try:
ser = self.get_serializer(data=_payload)

View File

@@ -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})

View File

@@ -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

View File

@@ -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

View File

@@ -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):

View File

@@ -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):

View File

@@ -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):

View File

@@ -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']

View File

@@ -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()

View File

@@ -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

View File

@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.conf import settings
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
from django_filters import rest_framework as drf_filters
@@ -180,18 +181,33 @@ class AssetViewSet(SuggestionMixin, BaseAssetViewSet):
def sync_platform_protocols(self, request, *args, **kwargs):
platform_id = request.data.get('platform_id')
platform = get_object_or_404(Platform, pk=platform_id)
asset_ids = list(platform.assets.values_list('id', flat=True))
platform_protocols = list(platform.protocols.values('name', 'port'))
assets = platform.assets.all()
with transaction.atomic():
if asset_ids:
Protocol.objects.filter(asset_id__in=asset_ids).delete()
if asset_ids and platform_protocols:
objs = []
for aid in asset_ids:
for p in platform_protocols:
objs.append(Protocol(name=p['name'], port=p['port'], asset_id=aid))
Protocol.objects.bulk_create(objs)
platform_protocols = {
p['name']: p['port']
for p in platform.protocols.values('name', 'port')
}
asset_protocols_map = defaultdict(set)
protocols = assets.prefetch_related('protocols').values_list(
'id', 'protocols__name'
)
for asset_id, protocol in protocols:
asset_id = str(asset_id)
asset_protocols_map[asset_id].add(protocol)
objs = []
for asset_id, protocols in asset_protocols_map.items():
protocol_names = set(platform_protocols) - protocols
if not protocol_names:
continue
for name in protocol_names:
objs.append(
Protocol(
name=name,
port=platform_protocols[name],
asset_id=asset_id,
)
)
Protocol.objects.bulk_create(objs)
return Response(status=status.HTTP_200_OK)
def filter_bulk_update_data(self):

View File

@@ -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)

View File

@@ -268,14 +268,6 @@ class Protocol(ChoicesMixin, models.TextChoices):
'port_from_addr': True,
'required': True,
'secret_types': ['token'],
'setting': {
'namespace': {
'type': 'str',
'required': False,
'default': '',
'label': _('Namespace')
}
}
},
cls.http: {
'port': 80,

View File

@@ -28,8 +28,7 @@ class MyAsset(JMSBaseModel):
@staticmethod
def set_asset_custom_value(assets, user):
asset_ids = [asset.id for asset in assets]
my_assets = MyAsset.objects.filter(asset_id__in=asset_ids, user=user).all()
my_assets = MyAsset.objects.filter(asset__in=assets, user=user).all()
customs = {my_asset.asset.id: my_asset.custom_to_dict() for my_asset in my_assets}
for asset in assets:
custom = customs.get(asset.id)

View File

@@ -84,7 +84,6 @@ class PlatformAutomationSerializer(serializers.ModelSerializer):
class PlatformProtocolSerializer(serializers.ModelSerializer):
setting = MethodSerializer(required=False, label=_("Setting"))
port_from_addr = serializers.BooleanField(label=_("Port from addr"), read_only=True)
port = serializers.IntegerField(label=_("Port"), required=False, min_value=0, max_value=65535)
class Meta:
model = PlatformProtocol

View File

@@ -43,7 +43,7 @@ from .serializers import (
OperateLogSerializer, OperateLogActionDetailSerializer,
PasswordChangeLogSerializer, ActivityUnionLogSerializer,
FileSerializer, UserSessionSerializer, JobsAuditSerializer,
ServiceAccessLogSerializer, OperateLogFullSerializer
ServiceAccessLogSerializer
)
from .utils import construct_userlogin_usernames, record_operate_log_and_activity_log
@@ -256,9 +256,7 @@ class OperateLogViewSet(OrgReadonlyModelViewSet):
def get_serializer_class(self):
if self.is_action_detail:
return OperateLogActionDetailSerializer
elif self.request.query_params.get('format'):
return OperateLogFullSerializer
return OperateLogSerializer
return super().get_serializer_class()
def get_queryset(self):
current_org_id = str(current_org.id)

View File

@@ -127,21 +127,6 @@ class OperateLogSerializer(BulkOrgResourceModelSerializer):
return i18n_trans(instance.resource)
class DiffFieldSerializer(serializers.JSONField):
def to_file_representation(self, value):
row = getattr(self, '_row') or {}
attrs = {'diff': value, 'resource_type': row.get('resource_type')}
instance = type('OperateLog', (), attrs)
return OperateLogStore.convert_diff_friendly(instance)
class OperateLogFullSerializer(OperateLogSerializer):
diff = DiffFieldSerializer(label=_("Diff"))
class Meta(OperateLogSerializer.Meta):
fields = OperateLogSerializer.Meta.fields + ['diff']
class PasswordChangeLogSerializer(serializers.ModelSerializer):
class Meta:
model = models.PasswordChangeLog

View File

@@ -47,21 +47,20 @@ def on_m2m_changed(sender, action, instance, reverse, model, pk_set, **kwargs):
objs = model.objects.filter(pk__in=pk_set)
objs_display = [str(o) for o in objs]
action = M2M_ACTION[action]
changed_field = current_instance.get(field_name, {})
changed_value = changed_field.get('value', [])
changed_field = current_instance.get(field_name, [])
after, before, before_value = None, None, None
if action == ActionChoices.create:
before_value = list(set(changed_value) - set(objs_display))
before_value = list(set(changed_field) - set(objs_display))
elif action == ActionChoices.delete:
before_value = list(set(changed_value).symmetric_difference(set(objs_display)))
before_value = list(
set(changed_field).symmetric_difference(set(objs_display))
)
if changed_field:
after = {field_name: changed_field}
if before_value:
before_change_field = changed_field.copy()
before_change_field['value'] = before_value
before = {field_name: before_change_field}
before = {field_name: before_value}
if sorted(str(before)) == sorted(str(after)):
return

View File

@@ -16,4 +16,3 @@ from .sso import *
from .temp_token import *
from .token import *
from .face import *
from .access_token import *

View File

@@ -1,47 +0,0 @@
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND
from oauth2_provider.models import get_access_token_model
from common.api import JMSModelViewSet
from rbac.permissions import RBACPermission
from ..serializers import AccessTokenSerializer
AccessToken = get_access_token_model()
class AccessTokenViewSet(JMSModelViewSet):
"""
OAuth2 Access Token 管理视图集
用户只能查看和撤销自己的 access token
"""
serializer_class = AccessTokenSerializer
permission_classes = [RBACPermission]
http_method_names = ['get', 'options', 'delete']
rbac_perms = {
'revoke': 'oauth2_provider.delete_accesstoken',
}
def get_queryset(self):
"""只返回当前用户的 access token按创建时间倒序"""
return AccessToken.objects.filter(user=self.request.user).order_by('-created')
@action(methods=['DELETE'], detail=True, url_path='revoke')
def revoke(self, request, *args, **kwargs):
"""
撤销 access token 及其关联的 refresh token
如果 token 不存在或不属于当前用户,返回 404
"""
token = get_object_or_404(
AccessToken.objects.filter(user=request.user),
id=kwargs['pk']
)
# 优先撤销 refresh token会自动撤销关联的 access token
token_to_revoke = token.refresh_token if token.refresh_token else token
token_to_revoke.revoke()
return Response(status=HTTP_204_NO_CONTENT)

View File

@@ -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

View File

@@ -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')

View File

@@ -1,22 +1,51 @@
# -*- coding: utf-8 -*-
#
import threading
from django.conf import settings
from django.contrib.auth import get_user_model
from django_cas_ng.backends import CASBackend as _CASBackend
from common.utils import get_logger
from ..base import JMSBaseAuthBackend
__all__ = ['CASBackend']
__all__ = ['CASBackend', 'CASUserDoesNotExist']
logger = get_logger(__name__)
class CASUserDoesNotExist(Exception):
"""Exception raised when a CAS user does not exist."""
pass
class CASBackend(JMSBaseAuthBackend, _CASBackend):
@staticmethod
def is_enabled():
return settings.AUTH_CAS
def authenticate(self, request, ticket, service):
# 这里做个hack ,让父类始终走CAS_CREATE_USER=True的逻辑然后调用 authentication/mixins.py 中的 custom_get_or_create 方法
settings.CAS_CREATE_USER = True
return super().authenticate(request, ticket, service)
UserModel = get_user_model()
manager = UserModel._default_manager
original_get_by_natural_key = manager.get_by_natural_key
thread_local = threading.local()
thread_local.thread_id = threading.get_ident()
logger.debug(f"CASBackend.authenticate: thread_id={thread_local.thread_id}")
def get_by_natural_key(self, username):
logger.debug(f"CASBackend.get_by_natural_key: thread_id={threading.get_ident()}, username={username}")
if threading.get_ident() != thread_local.thread_id:
return original_get_by_natural_key(username)
try:
user = original_get_by_natural_key(username)
except UserModel.DoesNotExist:
raise CASUserDoesNotExist(username)
return user
try:
manager.get_by_natural_key = get_by_natural_key.__get__(manager, type(manager))
user = super().authenticate(request, ticket=ticket, service=service)
finally:
manager.get_by_natural_key = original_get_by_natural_key
return user

View File

@@ -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'),
]

View File

@@ -3,20 +3,31 @@ from django.http import HttpResponseRedirect
from django.utils.translation import gettext_lazy as _
from django_cas_ng.views import LoginView
from authentication.views.mixins import FlashMessageMixin
from authentication.backends.base import BaseAuthCallbackClientView
from common.utils import FlashMessageUtil
from .backends import CASUserDoesNotExist
__all__ = ['LoginView']
class CASLoginView(LoginView, FlashMessageMixin):
class CASLoginView(LoginView):
def get(self, request):
try:
resp = super().get(request)
except PermissionDenied:
resp = HttpResponseRedirect('/')
error_message = getattr(request, 'error_message', '')
if error_message:
response = self.get_failed_response('/', title=_('CAS Error'), msg=error_message)
return response
else:
return resp
except PermissionDenied:
return HttpResponseRedirect('/')
except CASUserDoesNotExist as e:
message_data = {
'title': _('User does not exist: {}').format(e),
'error': _(
'CAS login was successful, but no corresponding local user was found in the system, and automatic '
'user creation is disabled in the CAS authentication configuration. Login failed.'),
'interval': 10,
'redirect_url': '/',
}
return FlashMessageUtil.gen_and_redirect_to(message_data)
class CASCallbackClientView(BaseAuthCallbackClientView):
pass

View File

@@ -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:

View File

@@ -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')
]

View File

@@ -3,37 +3,29 @@ from django.contrib import auth
from django.http import HttpResponseRedirect
from django.urls import reverse
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
from common.utils import get_logger, safe_next_url
from common.utils import get_logger
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)
redirect_uri = build_absolute_uri(
request, path=reverse(settings.AUTH_OAUTH2_AUTH_LOGIN_CALLBACK_URL_NAME)
)
redirect_uri = f"{redirect_uri}?{query}"
query_dict = {
'client_id': settings.AUTH_OAUTH2_CLIENT_ID, 'response_type': 'code',
'scope': settings.AUTH_OAUTH2_SCOPE,
'redirect_uri': redirect_uri
'redirect_uri': build_absolute_uri(
request, path=reverse(settings.AUTH_OAUTH2_AUTH_LOGIN_CALLBACK_URL_NAME)
)
}
if '?' in settings.AUTH_OAUTH2_PROVIDER_AUTHORIZATION_ENDPOINT:
@@ -52,7 +44,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,17 +58,19 @@ 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)
else:
if getattr(request, 'error_message', ''):
response = self.get_failed_response('/', title=_('OAuth2 Error'), msg=request.error_message)
return response
return HttpResponseRedirect(
settings.AUTH_OAUTH2_AUTHENTICATION_REDIRECT_URI
)
logger.debug(log_prompt.format('Redirect'))
redirect_url = settings.AUTH_OAUTH2_PROVIDER_END_SESSION_ENDPOINT or '/'
return HttpResponseRedirect(redirect_url)
class OAuth2AuthCallbackClientView(BaseAuthCallbackClientView):
pass
class OAuth2EndSessionView(View):
http_method_names = ['get', 'post', ]

View File

@@ -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()

View File

@@ -1,14 +0,0 @@
# -*- coding: utf-8 -*-
#
from django.urls import path
from oauth2_provider import views as op_views
from . import views
urlpatterns = [
path("authorize/", op_views.AuthorizationView.as_view(), name="authorize"),
path("token/", op_views.TokenView.as_view(), name="token"),
path("revoke/", op_views.RevokeTokenView.as_view(), name="revoke-token"),
path(".well-known/oauth-authorization-server", views.OAuthAuthorizationServerView.as_view(), name="oauth-authorization-server"),
]

View File

@@ -1,31 +0,0 @@
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()
application, created = Application.objects.get_or_create(
name=settings.OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME,
defaults={
'client_type': Application.CLIENT_PUBLIC,
'authorization_grant_type': Application.GRANT_AUTHORIZATION_CODE,
'redirect_uris': settings.OAUTH2_PROVIDER_CLIENT_REDIRECT_URI,
'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)

View File

@@ -1,77 +0,0 @@
from django.views.generic import View
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
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
@method_decorator(csrf_exempt, name='dispatch')
@method_decorator(cache_page(timeout=60 * 60 * 24, key_prefix=CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX), name='dispatch')
class OAuthAuthorizationServerView(View):
"""
OAuth 2.0 Authorization Server Metadata Endpoint
RFC 8414: https://datatracker.ietf.org/doc/html/rfc8414
This endpoint provides machine-readable information about the
OAuth 2.0 authorization server's configuration.
"""
def get_base_url(self, request) -> str:
scheme = 'https' if request.is_secure() else 'http'
host = request.get_host()
return f"{scheme}://{host}"
def get_supported_scopes(self) -> List[str]:
scopes_config = oauth2_settings.SCOPES
if isinstance(scopes_config, dict):
return list(scopes_config.keys())
return []
def get_metadata(self, request) -> Dict[str, Any]:
base_url = self.get_base_url(request)
application = get_or_create_jumpserver_client_application()
metadata = {
"issuer": base_url,
"client_id": application.client_id if application else "Not found any application.",
"authorization_endpoint": base_url + reverse('authentication:oauth2-provider:authorize'),
"token_endpoint": base_url + reverse('authentication:oauth2-provider:token'),
"revocation_endpoint": base_url + reverse('authentication:oauth2-provider:revoke-token'),
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"scopes_supported": self.get_supported_scopes(),
"token_endpoint_auth_methods_supported": ["none"],
"revocation_endpoint_auth_methods_supported": ["none"],
"code_challenge_methods_supported": ["S256"],
"response_modes_supported": ["query"],
}
if hasattr(oauth2_settings, 'ACCESS_TOKEN_EXPIRE_SECONDS'):
metadata["token_expires_in"] = oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS
if hasattr(oauth2_settings, 'REFRESH_TOKEN_EXPIRE_SECONDS'):
if oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS:
metadata["refresh_token_expires_in"] = oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS
return metadata
def get(self, request, *args, **kwargs):
metadata = self.get_metadata(request)
response = JsonResponse(metadata)
self.add_cors_headers(response)
return response
def options(self, request, *args, **kwargs):
response = JsonResponse({})
self.add_cors_headers(response)
return response
@staticmethod
def add_cors_headers(response):
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
response['Access-Control-Max-Age'] = '3600'

View File

@@ -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'),
]

View File

@@ -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.

View File

@@ -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'),
]

View File

@@ -17,8 +17,9 @@ from onelogin.saml2.idp_metadata_parser import (
)
from authentication.views.mixins import FlashMessageMixin
from common.utils import get_logger, safe_next_url
from common.utils import get_logger
from .settings import JmsSaml2Settings
from ..base import BaseAuthCallbackClientView
logger = get_logger(__file__)
@@ -207,16 +208,13 @@ class Saml2AuthRequestView(View, PrepareRequestMixin):
log_prompt = "Process SAML GET requests: {}"
logger.debug(log_prompt.format('Start'))
request_params = request.GET.dict()
try:
saml_instance = self.init_saml_auth(request)
except OneLogin_Saml2_Error as error:
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 = safe_next_url(next_url, request=request)
next_url = settings.AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT
url = saml_instance.login(return_to=next_url)
logger.debug(log_prompt.format('Redirect login url'))
return HttpResponseRedirect(url)
@@ -254,7 +252,6 @@ class Saml2AuthCallbackView(View, PrepareRequestMixin, FlashMessageMixin):
def post(self, request):
log_prompt = "Process SAML2 POST requests: {}"
post_data = request.POST
error_title = _("SAML2 Error")
try:
saml_instance = self.init_saml_auth(request)
@@ -282,24 +279,20 @@ class Saml2AuthCallbackView(View, PrepareRequestMixin, FlashMessageMixin):
try:
user = auth.authenticate(request=request, saml_user_data=saml_user_data)
except IntegrityError as e:
title = _("SAML2 Error")
msg = _('Please check if a user with the same username or email already exists')
logger.error(e, exc_info=True)
response = self.get_failed_response('/', error_title, msg)
response = self.get_failed_response('/', title, msg)
return response
if user and user.is_valid:
logger.debug(log_prompt.format('Login: {}'.format(user)))
auth.login(self.request, user)
if not user and getattr(request, 'error_message', ''):
response = self.get_failed_response('/', title=error_title, msg=request.error_message)
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 +300,10 @@ class Saml2AuthCallbackView(View, PrepareRequestMixin, FlashMessageMixin):
return super().dispatch(*args, **kwargs)
class Saml2AuthCallbackClientView(BaseAuthCallbackClientView):
pass
class Saml2AuthMetadataView(View, PrepareRequestMixin):
def get(self, request):

View File

@@ -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'

View File

@@ -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

View File

@@ -114,12 +114,12 @@ class BlockMFAError(AuthFailedNeedLogMixin, AuthFailedError):
super().__init__(username=username, request=request, ip=ip)
class BlockLoginError(AuthFailedNeedLogMixin, AuthFailedNeedBlockMixin, AuthFailedError):
class BlockLoginError(AuthFailedNeedBlockMixin, AuthFailedError):
error = 'block_login'
def __init__(self, username, ip, request):
def __init__(self, username, ip):
self.msg = const.block_user_login_msg.format(settings.SECURITY_LOGIN_LIMIT_TIME)
super().__init__(username=username, ip=ip, request=request)
super().__init__(username=username, ip=ip)
class SessionEmptyError(AuthFailedError):

View File

@@ -1,75 +0,0 @@
# -*- coding: utf-8 -*-
#
from django.core.management.base import BaseCommand
from django.db.utils import OperationalError, ProgrammingError
from django.conf import settings
class Command(BaseCommand):
help = 'Initialize OAuth2 Provider - Create default JumpServer Client application'
def add_arguments(self, parser):
parser.add_argument(
'--force',
action='store_true',
help='Force recreate the application even if it exists',
)
def handle(self, *args, **options):
force = options.get('force', False)
try:
from authentication.backends.oauth2_provider.utils import (
get_or_create_jumpserver_client_application
)
from oauth2_provider.models import get_application_model
Application = get_application_model()
# 检查表是否存在
try:
Application.objects.exists()
except (OperationalError, ProgrammingError) as e:
self.stdout.write(
self.style.ERROR(
f'OAuth2 Provider tables not found. Please run migrations first:\n'
f' python manage.py migrate oauth2_provider\n'
f'Error: {e}'
)
)
return
# 如果强制重建,先删除已存在的应用
if force:
deleted_count, _ = Application.objects.filter(
name=settings.OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME
).delete()
if deleted_count > 0:
self.stdout.write(
self.style.WARNING(f'Deleted {deleted_count} existing application(s)')
)
# 创建或获取应用
application = get_or_create_jumpserver_client_application()
if application:
self.stdout.write(
self.style.SUCCESS(
f'✓ OAuth2 JumpServer Client application initialized successfully\n'
f' - Client ID: {application.client_id}\n'
f' - Client Type: {application.get_client_type_display()}\n'
f' - Grant Type: {application.get_authorization_grant_type_display()}\n'
f' - Redirect URIs: {application.redirect_uris}\n'
f' - Skip Authorization: {application.skip_authorization}'
)
)
else:
self.stdout.write(
self.style.ERROR('Failed to create OAuth2 application')
)
except Exception as e:
self.stdout.write(
self.style.ERROR(f'Error initializing OAuth2 Provider: {e}')
)
raise

View File

@@ -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:

View File

@@ -6,7 +6,6 @@ import time
import uuid
from functools import partial
from typing import Callable
from werkzeug.local import Local
from django.conf import settings
from django.contrib import auth
@@ -17,7 +16,6 @@ from django.contrib.auth import (
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Q
from django.shortcuts import reverse, redirect, get_object_or_404
from django.utils.http import urlencode
from django.utils.translation import gettext as _
@@ -33,87 +31,6 @@ from .signals import post_auth_success, post_auth_failed
logger = get_logger(__name__)
# 模块级别的线程上下文,用于 authenticate 函数中标记当前线程
_auth_thread_context = Local()
# 保存 Django 原始的 get_or_create 方法(在模块加载时保存一次)
def _save_original_get_or_create():
"""保存 Django 原始的 get_or_create 方法"""
from django.contrib.auth import get_user_model as get_user_model_func
UserModel = get_user_model_func()
return UserModel.objects.get_or_create
_django_original_get_or_create = _save_original_get_or_create()
class OnlyAllowExistUserAuthError(Exception):
pass
def _authenticate_context(func):
"""
装饰器:管理 authenticate 函数的执行上下文
功能:
1. 执行前:
- 在线程本地存储中标记当前正在执行 authenticate
- 临时替换 UserModel.objects.get_or_create 方法
2. 执行后:
- 清理线程本地存储标记
- 恢复 get_or_create 为 Django 原始方法
作用:
- 确保 get_or_create 行为仅在 authenticate 生命周期内生效
- 支持 ONLY_ALLOW_EXIST_USER_AUTH 配置的线程安全实现
- 防止跨请求或跨线程的状态污染
"""
from functools import wraps
@wraps(func)
def wrapper(request=None, **credentials):
from django.contrib.auth import get_user_model
UserModel = get_user_model()
def custom_get_or_create(*args, **kwargs):
create_username = kwargs.get('username')
logger.debug(f"get_or_create: thread_id={threading.get_ident()}, username={create_username}")
# 如果当前线程正在执行 authenticate 且仅允许已存在用户认证,则提前判断用户是否存在
if (
getattr(_auth_thread_context, 'in_authenticate', False) and
settings.ONLY_ALLOW_EXIST_USER_AUTH
):
try:
UserModel.objects.get(username=create_username)
except UserModel.DoesNotExist:
raise OnlyAllowExistUserAuthError
# 调用 Django 原始方法(已是绑定方法,直接传参)
return _django_original_get_or_create(*args, **kwargs)
try:
# 执行前:设置线程上下文和 monkey-patch
setattr(_auth_thread_context, 'in_authenticate', True)
UserModel.objects.get_or_create = custom_get_or_create
# 执行原函数
return func(request, **credentials)
finally:
# 执行后:清理线程上下文和恢复原始方法
try:
if hasattr(_auth_thread_context, 'in_authenticate'):
delattr(_auth_thread_context, 'in_authenticate')
except Exception:
pass
try:
UserModel.objects.get_or_create = _django_original_get_or_create
except Exception:
pass
return wrapper
def _get_backends(return_tuples=False):
backends = []
@@ -131,16 +48,39 @@ def _get_backends(return_tuples=False):
return backends
class OnlyAllowExistUserAuthError(Exception):
pass
auth._get_backends = _get_backends
@_authenticate_context
def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
之所以 hack 这个 authenticate
"""
temp_user = None
UserModel = get_user_model()
original_get_or_create = UserModel.objects.get_or_create
thread_local = threading.local()
thread_local.thread_id = threading.get_ident()
def custom_get_or_create(self, *args, **kwargs):
logger.debug(f"get_or_create: thread_id={threading.get_ident()}, username={username}")
if threading.get_ident() != thread_local.thread_id or not settings.ONLY_ALLOW_EXIST_USER_AUTH:
return original_get_or_create(*args, **kwargs)
create_username = kwargs.get('username')
try:
UserModel.objects.get(username=create_username)
except UserModel.DoesNotExist:
raise OnlyAllowExistUserAuthError
return original_get_or_create(*args, **kwargs)
username = credentials.get('username')
temp_user = None
for backend, backend_path in _get_backends(return_tuples=True):
# 检查用户名是否允许认证 (预先检查,不浪费认证时间)
logger.info('Try using auth backend: {}'.format(str(backend)))
@@ -154,28 +94,27 @@ def authenticate(request=None, **credentials):
except TypeError:
# This backend doesn't accept these credentials as arguments. Try the next one.
continue
try:
UserModel.objects.get_or_create = custom_get_or_create.__get__(UserModel.objects)
user = backend.authenticate(request, **credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be allowed in at all.
break
except OnlyAllowExistUserAuthError:
if request:
request.error_message = _(
'''The administrator has enabled "Only allow existing users to log in",
and the current user is not in the user list. Please contact the administrator.'''
)
request.error_message = _(
'''The administrator has enabled "Only allow existing users to log in",
and the current user is not in the user list. Please contact the administrator.'''
)
continue
finally:
UserModel.objects.get_or_create = original_get_or_create
if user is None:
continue
if not user.is_valid:
temp_user = user
temp_user.backend = backend_path
if request:
request.error_message = _('User is invalid')
request.error_message = _('User is invalid')
return temp_user
# 检查用户是否允许认证
@@ -190,11 +129,8 @@ def authenticate(request=None, **credentials):
else:
if temp_user is not None:
source_display = temp_user.source_display
if request:
request.error_message = _(
''' The administrator has enabled 'Only allow login from user source'.
The current user source is {}. Please contact the administrator. '''
).format(source_display)
request.error_message = _('''The administrator has enabled 'Only allow login from user source'.
The current user source is {}. Please contact the administrator.''').format(source_display)
return temp_user
# The credentials supplied are invalid to all backends, fire signal
@@ -273,9 +209,9 @@ class AuthPreCheckMixin:
if not is_block:
return
logger.warning('Ip was blocked' + ': ' + username + ':' + ip)
exception = errors.BlockLoginError(username=username, ip=ip, request=self.request)
exception = errors.BlockLoginError(username=username, ip=ip)
if raise_exception:
raise exception
raise errors.BlockLoginError(username=username, ip=ip)
else:
return exception
@@ -292,8 +228,7 @@ class AuthPreCheckMixin:
if not settings.ONLY_ALLOW_EXIST_USER_AUTH:
return
q = Q(username=username) | Q(email=username)
exist = User.objects.filter(q).exists()
exist = User.objects.filter(username=username).exists()
if not exist:
logger.error(f"Only allow exist user auth, login failed: {username}")
self.raise_credential_error(errors.reason_user_not_exist)

View File

@@ -9,12 +9,11 @@ from common.utils import get_object_or_none, random_string
from users.models import User
from users.serializers import UserProfileSerializer
from ..models import AccessKey, TempToken
from oauth2_provider.models import get_access_token_model
__all__ = [
'AccessKeySerializer', 'BearerTokenSerializer',
'SSOTokenSerializer', 'TempTokenSerializer',
'AccessKeyCreateSerializer', 'AccessTokenSerializer',
'AccessKeyCreateSerializer'
]
@@ -115,28 +114,3 @@ class TempTokenSerializer(serializers.ModelSerializer):
token = TempToken(**kwargs)
token.save()
return token
class AccessTokenSerializer(serializers.ModelSerializer):
token_preview = serializers.SerializerMethodField(label=_("Token"))
class Meta:
model = get_access_token_model()
fields = [
'id', 'user', 'token_preview', 'is_valid',
'is_expired', 'expires', 'scope', 'created', 'updated',
]
read_only_fields = fields
extra_kwargs = {
'scope': { 'label': _('Scope') },
'expires': { 'label': _('Date expired') },
'updated': { 'label': _('Date updated') },
'created': { 'label': _('Date created') },
}
def get_token_preview(self, obj):
token_string = obj.token
if len(token_string) > 16:
return f"{token_string[:6]}...{token_string[-4:]}"
return "****"

View File

@@ -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)

View File

@@ -47,9 +47,3 @@ def clean_expire_token():
count = TempToken.objects.filter(date_expired__lt=expired_time).delete()
logging.info('Deleted %d temporary tokens.', count[0])
logging.info('Cleaned expired temporary and connection tokens.')
@register_as_period_task(crontab=CRONTAB_AT_AM_TWO)
def clear_oauth2_provider_expired_tokens():
from oauth2_provider.models import clear_expired
clear_expired()

View File

@@ -16,7 +16,6 @@ router.register('super-connection-token', api.SuperConnectionTokenViewSet, 'supe
router.register('admin-connection-token', api.AdminConnectionTokenViewSet, 'admin-connection-token')
router.register('confirm', api.UserConfirmationViewSet, 'confirm')
router.register('ssh-key', api.SSHkeyViewSet, 'ssh-key')
router.register('access-tokens', api.AccessTokenViewSet, 'access-token')
urlpatterns = [
path('<str:backend>/qr/unbind/', api.QRUnBindForUserApi.as_view(), name='qr-unbind'),

View File

@@ -83,6 +83,4 @@ urlpatterns = [
path('oauth2/', include(('authentication.backends.oauth2.urls', 'authentication'), namespace='oauth2')),
path('captcha/', include('captcha.urls')),
path('oauth2-provider/', include(('authentication.backends.oauth2_provider.urls', 'authentication'), namespace='oauth2-provider'))
]

View File

@@ -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
@@ -73,7 +72,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 +110,8 @@ 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'
return self.redirect_to_guard_view()

View File

@@ -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')

View File

@@ -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({

View File

@@ -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')

View File

@@ -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):

View File

@@ -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({

View File

@@ -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,19 @@ 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):
redirect_url = request.GET.get('redirect_url') or reverse('index')
next_url = self.get_next_url_from_meta() or reverse('index')
next_url = safe_next_url(next_url, request=request)
redirect_uri = reverse('authentication:wecom-qr-login-callback', external=True)
redirect_uri += '?' + urlencode({'redirect_url': redirect_url})
redirect_uri += '?' + urlencode({
'redirect_url': redirect_url,
'next': next_url,
})
url = self.get_qr_url(redirect_uri)
return HttpResponseRedirect(url)
@@ -144,11 +148,12 @@ class WeComQRLoginCallbackView(WeComQRMixin, BaseLoginCallbackView):
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 +161,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')

View File

@@ -183,7 +183,6 @@ class BaseFileRenderer(LogMixin, BaseRenderer):
for item in data:
row = []
for field in render_fields:
field._row = item
value = item.get(field.field_name)
value = self.render_value(field, value)
row.append(value)

View File

@@ -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 = [

View File

@@ -2,7 +2,6 @@
#
import datetime
import inspect
import sys
if sys.version_info.major == 3 and sys.version_info.minor >= 10:
@@ -335,10 +334,6 @@ class ES(object):
def is_keyword(props: dict, field: str) -> bool:
return props.get(field, {}).get("type", "keyword") == "keyword"
@staticmethod
def is_long(props: dict, field: str) -> bool:
return props.get(field, {}).get("type") == "long"
def get_query_body(self, **kwargs):
new_kwargs = {}
for k, v in kwargs.items():
@@ -366,10 +361,10 @@ class ES(object):
if index_in_field in kwargs:
index['values'] = kwargs[index_in_field]
mapping = self.es.indices.get_mapping(index=self.index)
mapping = self.es.indices.get_mapping(index=self.query_index)
props = (
mapping
.get(self.index, {})
.get(self.query_index, {})
.get('mappings', {})
.get('properties', {})
)
@@ -380,9 +375,6 @@ class ES(object):
if k in ("org_id", "session") and self.is_keyword(props, k):
exact[k] = v
elif self.is_long(props, k):
exact[k] = v
elif k in common_keyword_able:
exact[f"{k}.keyword"] = v

View File

@@ -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)

View File

@@ -192,7 +192,6 @@ class WeCom(RequestMixin):
class WeComTool(object):
WECOM_STATE_SESSION_KEY = '_wecom_state'
WECOM_STATE_VALUE = 'wecom'
WECOM_STATE_NEXT_URL_KEY = 'wecom_oauth_next_url'
@lazyproperty
def qr_cb_url(self):

View File

@@ -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) 可读性"""

View File

@@ -1,16 +1,137 @@
import json
import threading
import time
import redis
from django.core.cache import cache
from redis.client import PubSub
from common.db.utils import safe_db_connection
from common.utils import get_logger
logger = get_logger(__name__)
import threading
from concurrent.futures import ThreadPoolExecutor
_PUBSUB_HUBS = {}
def _get_pubsub_hub(db=10):
hub = _PUBSUB_HUBS.get(db)
if not hub:
hub = PubSubHub(db=db)
_PUBSUB_HUBS[db] = hub
return hub
class PubSubHub:
def __init__(self, db=10):
self.db = db
self.redis = get_redis_client(db)
self.pubsub = self.redis.pubsub()
self.handlers = {}
self.lock = threading.RLock()
self.listener = None
self.running = False
self.executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix='pubsub_handler')
def __del__(self):
self.executor.shutdown(wait=True)
def start(self):
with self.lock:
if self.listener and self.listener.is_alive():
return
self.running = True
self.listener = threading.Thread(name='pubsub_listen', target=self._listen_loop, daemon=True)
self.listener.start()
def _listen_loop(self):
backoff = 1
while self.running:
try:
for msg in self.pubsub.listen():
if msg.get("type") != "message":
continue
ch = msg.get("channel")
if isinstance(ch, bytes):
ch = ch.decode()
data = msg.get("data")
try:
if isinstance(data, bytes):
item = json.loads(data.decode())
elif isinstance(data, str):
item = json.loads(data)
else:
item = data
except Exception:
item = data
# 使用线程池处理消息
future = self.executor.submit(self._dispatch, ch, msg, item)
future.add_done_callback(
lambda f: f.exception() and logger.error(f"handle pubsub msg {msg} failed: {f.exception()}"))
backoff = 1
except Exception as e:
logger.error(f'PubSub listen error: {e}')
time.sleep(backoff)
backoff = min(backoff * 2, 30)
try:
self._reconnect()
except Exception as re:
logger.error(f'PubSub reconnect error: {re}')
def _dispatch(self, ch, raw_msg, item):
with self.lock:
handler = self.handlers.get(ch)
if not handler:
return
_next, error, _complete = handler
try:
with safe_db_connection():
_next(item)
except Exception as e:
logger.error(f'Subscribe handler handle msg error: {e}')
try:
if error:
error(raw_msg, item)
except Exception:
pass
def add_subscription(self, pb, _next, error, complete):
ch = pb.ch
with self.lock:
existed = bool(self.handlers.get(ch))
self.handlers[ch] = (_next, error, complete)
try:
if not existed:
self.pubsub.subscribe(ch)
except Exception as e:
logger.error(f'Subscribe channel {ch} error: {e}')
self.start()
return Subscription(pb=pb, hub=self, ch=ch, handler=(_next, error, complete))
def remove_subscription(self, sub):
ch = sub.ch
with self.lock:
existed = self.handlers.pop(ch, None)
if existed:
try:
self.pubsub.unsubscribe(ch)
except Exception as e:
logger.warning(f'Unsubscribe {ch} error: {e}')
def _reconnect(self):
with self.lock:
channels = [ch for ch, h in self.handlers.items() if h]
try:
self.pubsub.close()
except Exception:
pass
self.redis = get_redis_client(self.db)
self.pubsub = self.redis.pubsub()
if channels:
self.pubsub.subscribe(channels)
def get_redis_client(db=0):
client = cache.client.get_client()
@@ -25,15 +146,11 @@ class RedisPubSub:
self.redis = get_redis_client(db)
def subscribe(self, _next, error=None, complete=None):
ps = self.redis.pubsub()
ps.subscribe(self.ch)
sub = Subscription(self, ps)
sub.keep_handle_msg(_next, error, complete)
return sub
hub = _get_pubsub_hub(self.db)
return hub.add_subscription(self, _next, error, complete)
def resubscribe(self, _next, error=None, complete=None):
self.redis = get_redis_client(self.db)
self.subscribe(_next, error, complete)
return self.subscribe(_next, error, complete)
def publish(self, data):
data_json = json.dumps(data)
@@ -42,85 +159,19 @@ class RedisPubSub:
class Subscription:
def __init__(self, pb: RedisPubSub, sub: PubSub):
def __init__(self, pb: RedisPubSub, hub: PubSubHub, ch: str, handler):
self.pb = pb
self.ch = pb.ch
self.sub = sub
self.ch = ch
self.hub = hub
self.handler = handler
self.unsubscribed = False
def _handle_msg(self, _next, error, complete):
"""
handle arg is the pub published
:param _next: next msg handler
:param error: error msg handler
:param complete: complete msg handler
:return:
"""
msgs = self.sub.listen()
if error is None:
error = lambda m, i: None
if complete is None:
complete = lambda: None
try:
for msg in msgs:
if msg["type"] != "message":
continue
item = None
try:
item_json = msg['data'].decode()
item = json.loads(item_json)
with safe_db_connection():
_next(item)
except Exception as e:
error(msg, item)
logger.error('Subscribe handler handle msg error: {}'.format(e))
except Exception as e:
if self.unsubscribed:
logger.debug('Subscription unsubscribed')
else:
logger.error('Consume msg error: {}'.format(e))
self.retry(_next, error, complete)
return
try:
complete()
except Exception as e:
logger.error('Complete subscribe error: {}'.format(e))
pass
try:
self.unsubscribe()
except Exception as e:
logger.error("Redis observer close error: {}".format(e))
def keep_handle_msg(self, _next, error, complete):
t = threading.Thread(target=self._handle_msg, args=(_next, error, complete))
t.daemon = True
t.start()
return t
def unsubscribe(self):
if self.unsubscribed:
return
self.unsubscribed = True
logger.info(f"Unsubscribed from channel: {self.sub}")
logger.info(f"Unsubscribed from channel: {self.ch}")
try:
self.sub.close()
self.hub.remove_subscription(self)
except Exception as e:
logger.warning(f'Unsubscribe msg error: {e}')
def retry(self, _next, error, complete):
logger.info('Retry subscribe channel: {}'.format(self.ch))
times = 0
while True:
try:
self.unsubscribe()
self.pb.resubscribe(_next, error, complete)
break
except Exception as e:
logger.error('Retry #{} {} subscribe channel error: {}'.format(times, self.ch, e))
times += 1
time.sleep(times * 2)

View File

@@ -101,7 +101,7 @@ def get_ip_city(ip):
info = get_ip_city_by_ipip(ip)
if info:
city = info.get('city') or _("Unknown")
city = info.get('city', _("Unknown"))
country = info.get('country')
# 国内城市 并且 语言是中文就使用国内

View File

@@ -61,10 +61,8 @@ def contains_time_period(time_periods, ctime=None):
"""
time_periods: [{"id": 1, "value": "00:00~07:30、10:00~13:00"}, {"id": 2, "value": "00:00~00:00"}]
"""
if not time_periods or all(item['value'] == "" for item in time_periods):
# 需要处理 [{"id":1,"value":""},{"id":2,"value":""},{"id":3,"value":""},...]情况
# 都没选择相当于全选
return True
if not time_periods:
return None
if ctime is None:
ctime = local_now()

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

View File

@@ -199,7 +199,7 @@
"AuditsDashboard": "Audits dashboard",
"Auth": "Authentication",
"AuthConfig": "Authentication",
"AuthIntegration": "Auth Integration",
"AuthIntegration": "AuthIntegration",
"AuthLimit": "Login restriction",
"AuthSAMLCertHelpText": "Save after uploading the certificate key, then view sp metadata",
"AuthSAMLKeyHelpText": "Sp certificates and keys are used for encrypted communication with idp",
@@ -280,8 +280,7 @@
"CACertificate": "Ca certificate",
"CAS": "CAS",
"CMPP2": "Cmpp v2.0",
"CTYun": "State Cloud",
"CTYunPrivate": "State Cloud(Private)",
"CTYunPrivate": "eCloud Private Cloud",
"CalculationResults": "Error in cron expression",
"CallRecords": "Call Records",
"CanDragSelect": "Select by dragging; Empty means all selected",
@@ -774,7 +773,6 @@
"LdapBulkImport": "User import",
"LdapConnectTest": "Test connection",
"LdapLoginTest": "Test login",
"LeakPasswordList": "Leaked password list",
"LeakedPassword": "Leaked password",
"Length": "Length",
"LessEqualThan": "Less than or equal to",
@@ -1026,7 +1024,6 @@
"PleaseAgreeToTheTerms": "Please agree to the terms",
"PleaseEnterReason": "Please enter a reason",
"PleaseSelect": "Please select ",
"PleaseSelectAssetOrNode": "Please select at least one asset or node",
"PleaseSelectTheDataYouWantToCheck": "Please select the data you want to check",
"PolicyName": "Policy name",
"Port": "Port",
@@ -1622,22 +1619,14 @@
"assetAddress": "Asset address",
"assetId": "Asset ID",
"assetName": "Asset name",
"clickToAdd": "Click to add",
"currentTime": "Current time",
"description": "No data yet",
"disallowSelfUpdateFields": "Not allowed to modify the current fields yourself",
"forceEnableMFAHelpText": "If force enable, user can not disable by themselves",
"isConsoleCanUse": "is Console page can use",
"overwriteProtocolsAndPortsMsg": "This operation will overwrite the protocols and ports of the selected assets. Are you sure you want to continue?",
"pleaseSelectAssets": "Please select assets",
"removeWarningMsg": "Are you sure you want to remove",
"selectFiles": "Selected {number} files",
"selectedAssets": "Selected assets",
"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"
"LeakPasswordList": "Leaked password list"
}

View File

@@ -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",
@@ -1032,7 +1028,6 @@
"PleaseAgreeToTheTerms": "Por favor, acepte los términos",
"PleaseEnterReason": "Por favor, introduzca el motivo",
"PleaseSelect": "Por favor seleccione",
"PleaseSelectAssetOrNode": "Por favor, seleccione un activo o nodo",
"PleaseSelectTheDataYouWantToCheck": "Por favor, seleccione los datos que necesita marcar.",
"PolicyName": "Nombre de la estrategia",
"Port": "Puerto",
@@ -1180,8 +1175,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",
@@ -1635,18 +1628,13 @@
"assetAddress": "Dirección de activo",
"assetId": "ID de activo",
"assetName": "Nombre de activo",
"clickToAdd": "Haga clic en agregar",
"currentTime": "Hora actual",
"description": "Sin datos disponibles.",
"disallowSelfUpdateFields": "No se permite modificar el campo actual.",
"forceEnableMFAHelpText": "Si se habilita forzosamente, el usuario no podrá desactivarlo por sí mismo",
"isConsoleCanUse": "¿Está disponible la página de gestión?< -SEP->Agregar puerta de enlace al dominio",
"name": "Nombre de usuario",
"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",
"userName": "Nombre de usuario"

View File

@@ -8,8 +8,6 @@
"AccessDistribution": "アクセス分布",
"AccessIP": "IP ホワイトリスト",
"AccessKey": "アクセスキー",
"AccessToken": "アクセス・トークン",
"AccessTokenTip": "アクセス・トークンは、JumpServer クライアントを通じて OAuth2Authorization 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": "つうわきろく",
@@ -1037,7 +1033,6 @@
"PleaseAgreeToTheTerms": "規約に同意してください",
"PleaseEnterReason": "理由を入力してください",
"PleaseSelect": "選択してくださ",
"PleaseSelectAssetOrNode": "資産またはノードを選択してください",
"PleaseSelectTheDataYouWantToCheck": "選択するデータをチェックしてください",
"PolicyName": "ポリシー名称",
"Port": "ポート",
@@ -1185,8 +1180,6 @@
"RetrySelected": "選択したものを再試行",
"Review": "審査",
"Reviewer": "承認者",
"Revoke": "取り消し",
"Risk": "リスク",
"RiskDetection": "リスク検出",
"RiskDetectionDetail": "リスク検出の詳細",
"RiskyAccount": "リスクアカウント",
@@ -1640,18 +1633,13 @@
"assetAddress": "資産アドレス",
"assetId": "資産ID",
"assetName": "資産名",
"clickToAdd": "追加をクリック",
"currentTime": "現在の時間",
"description": "データはありません。",
"disallowSelfUpdateFields": "現在のフィールドを自分で変更することは許可されていません",
"forceEnableMFAHelpText": "強制的に有効化すると、ユーザーは自分で無効化することができません。",
"isConsoleCanUse": "管理ページの利用可能性",
"name": "ユーザー名",
"overwriteProtocolsAndPortsMsg": "この操作はすべてのプロトコルとポートを上書きしますが、続行してよろしいですか?",
"pleaseSelectAssets": "資産を選択してください",
"removeWarningMsg": "削除してもよろしいですか",
"selectFiles": "{number}ファイルを選択しました。",
"selectedAssets": "選択した資産",
"setVariable": "パラメータ設定",
"userId": "ユーザーID",
"userName": "ユーザー名"

View File

@@ -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": "호출 기록",
@@ -1032,7 +1028,6 @@
"PleaseAgreeToTheTerms": "약관 동의 부탁드립니다",
"PleaseEnterReason": "이유를 입력하세요",
"PleaseSelect": "선택해주세요",
"PleaseSelectAssetOrNode": "자산 또는 노드를 선택해 주세요",
"PleaseSelectTheDataYouWantToCheck": "선택할 데이터를 선택해 주십시오.",
"PolicyName": "전략 이름",
"Port": "포트",
@@ -1180,8 +1175,6 @@
"RetrySelected": "선택한 항목 재시도",
"Review": "검토",
"Reviewer": "승인자",
"Revoke": "취소",
"Risk": "위험",
"RiskDetection": "위험 감지",
"RiskDetectionDetail": "위험 감지 상세 정보",
"RiskyAccount": "위험 계정",
@@ -1635,18 +1628,13 @@
"assetAddress": "자산 주소",
"assetId": "자산 ID",
"assetName": "자산 이름",
"clickToAdd": "추가를 클릭해 주세요",
"currentTime": "현재 시간",
"description": "데이터가 없습니다.",
"disallowSelfUpdateFields": "현재 필드를 스스로 수정할 수 없음",
"forceEnableMFAHelpText": "강제로 활성화하면 사용자가 스스로 비활성화할 수 없음",
"isConsoleCanUse": "관리 페이지 사용 가능 여부",
"name": "사용자 이름",
"overwriteProtocolsAndPortsMsg": "이 작업은 모든 프로토콜과 포트를 덮어씌우게 됩니다. 계속하시겠습니까?",
"pleaseSelectAssets": "자산을 선택해 주세요",
"removeWarningMsg": "제거할 것인지 확실합니까?",
"selectFiles": "선택한 파일 {number}개",
"selectedAssets": "선택한 자산",
"setVariable": "설정 매개변수",
"userId": "사용자 ID",
"userName": "사용자명"

View File

@@ -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",
@@ -1033,7 +1029,6 @@
"PleaseAgreeToTheTerms": "Por favor, concorde com os termos",
"PleaseEnterReason": "Por favor, insira o motivo",
"PleaseSelect": "Por favor, selecione",
"PleaseSelectAssetOrNode": "Por favor, selecione um ativo ou nó",
"PleaseSelectTheDataYouWantToCheck": "Por favor, selecione os dados que deseja marcar.",
"PolicyName": "Nome da Política",
"Port": "Porta",
@@ -1181,8 +1176,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 ",
@@ -1636,18 +1629,13 @@
"assetAddress": "Endereço do ativo",
"assetId": "ID do ativo",
"assetName": "Nome do ativo",
"clickToAdd": "Clique para adicionar",
"currentTime": "Hora atual",
"description": "Nenhum dado disponível.",
"disallowSelfUpdateFields": "Não é permitido alterar o campo atual",
"forceEnableMFAHelpText": "Se for habilitado forçosamente, o usuário não pode desativar por conta própria",
"isConsoleCanUse": "Se a página de gerenciamento está disponível",
"name": "Nome de usuário",
"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",
"userName": "Usuário"

View File

@@ -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": "Отчет по учетным записям",
@@ -125,7 +122,7 @@
"AppletHelpText": "В процессе загрузки, если приложение отсутствует, оно будет создано; если уже существует, будет выполнено обновление.",
"AppletHostCreate": "Добавить сервер RemoteApp",
"AppletHostDetail": "Подробности о хосте RemoteApp",
"AppletHostSelectHelpMessage": "При подключении к активу выбор сервера публикации приложения происходит случайным образом (но предпочтение отдается последнему использованному).<br>\nЕсли необходимо закрепить сервер публикации за конкретным активом, можно указать один из тегов:\n[AppletHost:имя_сервера], [AppletHostOnly:имя_сервера].<br>\nПри подключении к выбранному серверу публикации и выборе учётной записи применяются следующие правила:<br>\nв перечисленных ниже случаях будет использована <b>учетная запись пользователя с тем же именем</b> или <b>специальная учётная запись (начинающаяся с js)</b>,<br>\nв противном случае будет использоваться общая учётная запись (начинающаяся с jms)<br>\n1. И сервер публикации, и приложение поддерживают одновременные подключения;<br>\n2. Сервер публикации поддерживает одновременные подключения, а приложение — нет, и текущее приложение не использует специальную учётную запись;<br>\n3. Сервер публикации не поддерживает одновременные подключения, а приложение может как поддерживать, так и не поддерживать одновременные подключения, и ни одно приложение не использует специализированную учетную запись;<br>\n\nПримечание: поддержка одновременных подключений со стороны приложения определяется разработчиком,<br>\nа поддержка одновременных подключений со стороны хоста определяется настройкой «один пользователь — одна сессия» в настройках сервера публикации.",
"AppletHostSelectHelpMessage": "При подключении к активу выбор сервера публикации приложения происходит случайным образом (но предпочтение отдается последнему использованному).<br>\nЕсли необходимо закрепить сервер публикации за конкретным активом, можно указать один из тегов:\n[AppletHost:имя_сервера], [AppletHostOnly:имя_сервера].<br>\nПри подключении к выбранному серверу публикации и выборе учётной записи применяются следующие правила:<br>\nв перечисленных ниже случаях будет использована <b>учетная запись пользователя с тем же именем</b> или <b>специальная учётная запись (начинающаяся с js)</b>,<br>\nв противном случае будет использоваться общая учётная запись (начинающаяся с jms)<br>\n 1. И сервер публикации, и приложение поддерживают одновременные подключения;<br>\n 2. Сервер публикации поддерживает одновременные подключения, а приложение — нет, и текущее приложение не использует специальную учётную запись;<br>\n 3. Сервер публикации не поддерживает одновременные подключения, а приложение может как поддерживать, так и не поддерживать одновременные подключения, и ни одно приложение не использует специализированную учетную запись;<br>\n\nПримечание: поддержка одновременных подключений со стороны приложения определяется разработчиком,<br>\nа поддержка одновременных подключений со стороны хоста определяется настройкой «один пользователь — одна сессия» в настройках сервера публикации.",
"AppletHostUpdate": "Обновить машину публикации RemoteApp",
"AppletHostZoneHelpText": "Эта зона принадлежит Системной организации",
"AppletHosts": "Хост RemoteApp",
@@ -282,7 +279,6 @@
"CACertificate": "Сертификат ЦС",
"CAS": "CAS",
"CMPP2": "CMPP v2.0",
"CTYun": "Tianyi Cloud",
"CTYunPrivate": "eCloud Private Cloud",
"CalculationResults": "Ошибка в выражении cron",
"CallRecords": "Запись вызовов",
@@ -495,7 +491,7 @@
"DeleteOrgMsg": "Пользователь, Группа пользователей, Актив, Папка, Тег, Зона, Разрешение",
"DeleteOrgTitle": "Пожалуйста, сначала удалите следующие ресурсы в организации",
"DeleteReleasedAssets": "Удалить освобожденные активы",
"DeleteRemoteAccount": "Удалить УЗ на активе",
"DeleteRemoteAccount": "Удалить удаленный аккаунт",
"DeleteSelected": "Удалить выбранное",
"DeleteSuccess": "Успешно удалено",
"DeleteSuccessMsg": "Успешно удалено",
@@ -733,7 +729,7 @@
"InstanceName": "Название экземпляра",
"InstanceNamePartIp": "Название экземпляра и часть IP",
"InstancePlatformName": "Название платформы экземпляра",
"Integration": "Интеграция",
"Integration": "Интеграция приложений",
"Interface": "Сетевой интерфейс",
"InterfaceSettings": "Настройки интерфейса",
"Interval": "Интервал",
@@ -1032,7 +1028,6 @@
"PleaseAgreeToTheTerms": "Пожалуйста, согласитесь с условиями",
"PleaseEnterReason": "Введите причину",
"PleaseSelect": "Пожалуйста, выберите ",
"PleaseSelectAssetOrNode": "Пожалуйста, выберите актив или узел.",
"PleaseSelectTheDataYouWantToCheck": "Пожалуйста, выберите данные, которые нужно отметить",
"PolicyName": "Название политики",
"Port": "Порт",
@@ -1122,7 +1117,7 @@
"RelevantCommand": "Команда",
"RelevantSystemUser": "Системный пользователь",
"RemoteAddr": "Удалённый адрес",
"RemoteAssetFoundAccountDeleteMsg": "Удалить УЗ, обнаруженные на удалённых активах",
"RemoteAssetFoundAccountDeleteMsg": "Удалить аккаунты, обнаруженные с удалённых активов",
"RemoteLoginProtocolUsageDistribution": "Распределение протоколов входа в активы",
"Remove": "Удалить",
"RemoveAssetFromNode": "Удалить активы из папки",
@@ -1180,8 +1175,6 @@
"RetrySelected": "Повторить выбранное",
"Review": "Требовать одобрения",
"Reviewer": "Утверждающий",
"Revoke": "Отмена",
"Risk": "Риск",
"RiskDetection": "Выявление рисков",
"RiskDetectionDetail": "Детали обнаружения риска",
"RiskyAccount": "УЗ с риском",
@@ -1635,18 +1628,13 @@
"assetAddress": "Адрес актива",
"assetId": "ID актива",
"assetName": "Название актива",
"clickToAdd": "Нажмите, чтобы добавить",
"currentTime": "Текущее время",
"description": "Нет данных",
"disallowSelfUpdateFields": "Не разрешено самостоятельно изменять текущие поля.",
"forceEnableMFAHelpText": "При принудительном включении пользователь не может отключить самостоятельно",
"isConsoleCanUse": "Доступна ли Консоль",
"name": "Имя пользователя",
"overwriteProtocolsAndPortsMsg": "Это действие заменит все протоколы и порты. Продолжить?",
"pleaseSelectAssets": "Пожалуйста, выберите актив",
"removeWarningMsg": "Вы уверены, что хотите удалить",
"selectFiles": "Выбрано {number} файлов",
"selectedAssets": "Выбранные активы",
"setVariable": "Задать переменную",
"userId": "ID пользователя",
"userName": "Имя пользователя"

View File

@@ -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",
@@ -1032,7 +1028,6 @@
"PleaseAgreeToTheTerms": "Vui lòng đồng ý với các điều khoản",
"PleaseEnterReason": "Vui lòng nhập lý do",
"PleaseSelect": "Vui lòng chọn",
"PleaseSelectAssetOrNode": "Vui lòng chọn tài sản hoặc nút",
"PleaseSelectTheDataYouWantToCheck": "Vui lòng chọn dữ liệu cần đánh dấu",
"PolicyName": "Tên chính sách",
"Port": "Cổng",
@@ -1180,8 +1175,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",
@@ -1635,18 +1628,13 @@
"assetAddress": "Địa chỉ tài sản",
"assetId": "ID tài sản",
"assetName": "Tên tài sản",
"clickToAdd": "Nhấp để thêm",
"currentTime": "Thời gian hiện tại",
"description": "Chưa có dữ liệu.",
"disallowSelfUpdateFields": "Không cho phép tự chỉnh sửa trường hiện tại",
"forceEnableMFAHelpText": "Nếu buộc kích hoạt, người dùng sẽ không thể tự động vô hiệu hóa",
"isConsoleCanUse": "Trang quản lý có khả dụng không",
"name": "Tên người dùng",
"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",
"userName": "Tên người dùng"

View File

@@ -279,7 +279,6 @@
"CACertificate": "CA 证书",
"CAS": "CAS",
"CMPP2": "CMPP v2.0",
"CTYun": "天翼云",
"CTYunPrivate": "天翼私有云",
"CalculationResults": "cron 表达式错误",
"CallRecords": "调用记录",
@@ -730,7 +729,7 @@
"InstanceName": "实例名称",
"InstanceNamePartIp": "实例名称和部分IP",
"InstancePlatformName": "实例平台名称",
"Integration": "集成",
"Integration": "应用集成",
"Interface": "网络接口",
"InterfaceSettings": "界面设置",
"Interval": "间隔",
@@ -1029,7 +1028,6 @@
"PleaseAgreeToTheTerms": "请同意条款",
"PleaseEnterReason": "请输入原因",
"PleaseSelect": "请选择",
"PleaseSelectAssetOrNode": "请选择资产或节点",
"PleaseSelectTheDataYouWantToCheck": "请选择需要勾选的数据",
"PolicyName": "策略名称",
"Port": "端口",
@@ -1630,24 +1628,14 @@
"assetAddress": "资产地址",
"assetId": "资产 ID",
"assetName": "资产名称",
"clickToAdd": "点击添加",
"currentTime": "当前时间",
"description": "暂无数据",
"disallowSelfUpdateFields": "不允许自己修改当前字段",
"forceEnableMFAHelpText": "如果强制启用,用户无法自行禁用",
"isConsoleCanUse": "管理页面是否可用",
"name": "用户名称",
"overwriteProtocolsAndPortsMsg": "此操作将覆盖所有协议和端口,是否继续?",
"pleaseSelectAssets": "请选择资产",
"removeWarningMsg": "你确定要移除",
"selectedAssets": "已选资产",
"setVariable": "设置参数",
"userId": "用户ID",
"userName": "用户名",
"Risk": "风险",
"selectFiles": "已选择选择{number}文件",
"AccessToken": "访问令牌",
"AccessTokenTip": "访问令牌是通过 JumpServer 客户端使用 OAuth2授权码授权流程生成的临时凭证用于访问受保护的资源。",
"Revoke": "撤销",
"AccountSecretReadDisabled": "账号密码读取功能已被管理员禁用"
"userName": "用户名"
}

View File

@@ -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": "調用記錄",
@@ -1037,7 +1033,6 @@
"PleaseAgreeToTheTerms": "請同意條款",
"PleaseEnterReason": "請輸入原因",
"PleaseSelect": "請選擇",
"PleaseSelectAssetOrNode": "請選擇資產或節點",
"PleaseSelectTheDataYouWantToCheck": "請選擇需要勾選的數據",
"PolicyName": "策略名稱",
"Port": "端口",
@@ -1185,8 +1180,6 @@
"RetrySelected": "重新嘗試所選",
"Review": "審查",
"Reviewer": "審批人",
"Revoke": "撤銷",
"Risk": "風險",
"RiskDetection": "風險檢測",
"RiskDetectionDetail": "風險檢測詳情",
"RiskyAccount": "風險帳號",
@@ -1640,18 +1633,13 @@
"assetAddress": "資產地址",
"assetId": "資產 ID",
"assetName": "資產名稱",
"clickToAdd": "點擊添加",
"currentTime": "當前時間",
"description": "目前沒有數據。",
"disallowSelfUpdateFields": "不允許自己修改當前欄位",
"forceEnableMFAHelpText": "如果強制啟用,用戶無法自行禁用",
"isConsoleCanUse": "管理頁面是否可用",
"name": "用戶名稱",
"overwriteProtocolsAndPortsMsg": "此操作將覆蓋所有協議和端口,是否繼續?",
"pleaseSelectAssets": "請選擇資產",
"removeWarningMsg": "你確定要移除",
"selectFiles": "已選擇{number}文件",
"selectedAssets": "已選資產",
"setVariable": "設置參數",
"userId": "用戶ID",
"userName": "用戶名"

View File

@@ -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"
}

View File

@@ -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"
}

View File

@@ -288,6 +288,5 @@
"start time": "開始時間",
"success": "成功",
"system user": "システムユーザー",
"tabLimits": "現在、15個のタブが開かれています。システムの安定性を確保するために、新しいブラウザのタブでLunaを開いて操作を続けますか",
"user": "ユーザー"
}

View File

@@ -288,6 +288,5 @@
"start time": "시작 시간",
"success": "성공",
"system user": "시스템 사용자",
"tabLimits": "현재 15개의 탭이 열려 있습니다. 시스템의 안정성을 위해 Luna를 계속 사용하려면 새로운 브라우저 탭에서 열어보시겠습니까?",
"user": "사용자"
}

View File

@@ -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"
}

View File

@@ -151,7 +151,7 @@
"No": "Нет",
"No account available": "Нет доступных учетных записей",
"No available connect method": "Нет доступного метода подключения",
"No facial features": "Данные лица отсутствуют. Пожалуйста, перейдите на страницу личной информации, чтобы привязать их. ",
"No facial features": "Нет характеристик лица, пожалуйста, перейдите в личную инфрмацию для привязки",
"No matching found": "Совпадений не найдено",
"No permission": "Нет разрешений",
"No protocol available": "Нет доступных протоколов",
@@ -288,6 +288,5 @@
"start time": "время начала",
"success": "успешно",
"system user": "системный пользователь",
"tabLimits": "В данный момент открыто 15 вкладок. \nЧтобы обеспечить стабильность системы, стоит ли открыть Luna в новой вкладке браузера для продолжения работы?",
"user": "пользователь"
}

View File

@@ -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"
}

View File

@@ -288,6 +288,5 @@
"start time": "开始时间",
"success": "成功",
"system user": "系统用户",
"user": "用户",
"tabLimits": "当前已打开 15 个标签页。\n为保证系统稳定是否在新的浏览器标签页中打开 Luna 以继续操作?"
"user": "用户"
}

View File

@@ -289,6 +289,5 @@
"start time": "開始時間",
"success": "成功",
"system user": "系統用戶",
"tabLimits": "當前已打開 15 個標籤頁。 \n為了確保系統穩定是否在新的瀏覽器標籤頁中打開 Luna 以繼續操作?",
"user": "用戶"
}

View File

@@ -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')

Some files were not shown because too many files have changed in this diff Show More