perf: add TERMINAL_SSH_KEY_LIMIT_COUNT conf

This commit is contained in:
wangruidong
2024-08-13 16:06:01 +08:00
committed by Bryan
parent 3b1701b1aa
commit 32ae77c42d
12 changed files with 167 additions and 36 deletions

View File

@@ -1,14 +1,22 @@
# -*- coding: utf-8 -*-
#
from django.utils import timezone
from django.db.models import TextChoices
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from common.serializers.fields import ReadableHiddenField
from common.serializers.fields import ReadableHiddenField, LabeledChoiceField
from ..models import SSHKey
from common.utils import validate_ssh_public_key
from users.exceptions import CreateSSHKeyExceedLimit
__all__ = ['SSHKeySerializer']
__all__ = ['SSHKeySerializer', 'GenerateKeyType']
class GenerateKeyType(TextChoices):
auto = 'auto', _('Automatically Generate Key Pair')
# 目前只支持sftp方式
load = 'load', _('Import Existing Key Pair')
class SSHKeySerializer(serializers.ModelSerializer):
@@ -19,16 +27,22 @@ class SSHKeySerializer(serializers.ModelSerializer):
public_key_hash_md5 = serializers.CharField(
source='get_public_key_hash_md5', required=False, read_only=True, max_length=128
)
generate_key_type = LabeledChoiceField(
choices=GenerateKeyType.choices, label=_('Create Type'), default=GenerateKeyType.auto.value, required=False,
help_text=_(
'Please download the private key after creation. Each private key can only be downloaded once'
)
)
class Meta:
model = SSHKey
fields_mini = ['name']
fields_small = fields_mini + [
'public_key', 'is_active',
'public_key', 'is_active', 'comment'
]
read_only_fields = [
'id', 'user', 'public_key_comment', 'public_key_hash_md5',
'date_last_used', 'date_created', 'date_updated'
'date_last_used', 'date_created', 'date_updated', 'generate_key_type',
]
fields = fields_small + read_only_fields
@@ -42,3 +56,9 @@ class SSHKeySerializer(serializers.ModelSerializer):
if not validate_ssh_public_key(value):
raise serializers.ValidationError(_('Not a valid ssh public key'))
return value
def create(self, validated_data):
if not self.context["request"].user.can_create_ssh_key():
raise CreateSSHKeyExceedLimit()
validated_data.pop('generate_key_type', None)
return super().create(validated_data)