jumpserver/apps/assets/forms.py

330 lines
12 KiB
Python
Raw Normal View History

2016-08-14 14:10:10 +00:00
# coding:utf-8
from django import forms
2016-11-06 16:39:26 +00:00
from django.utils.translation import gettext_lazy as _
2016-08-14 14:10:10 +00:00
2017-03-24 06:48:18 +00:00
from .models import IDC, Asset, AssetGroup, AdminUser, SystemUser
2017-03-09 06:55:33 +00:00
from common.utils import validate_ssh_private_key, ssh_pubkey_gen, ssh_key_gen, get_logger
logger = get_logger(__file__)
2016-08-14 14:10:10 +00:00
2016-09-17 15:43:41 +00:00
class AssetCreateForm(forms.ModelForm):
2016-08-14 14:10:10 +00:00
class Meta:
model = Asset
fields = [
2017-04-12 03:50:15 +00:00
'hostname', 'ip', 'public_ip', 'port', 'type', 'comment',
'admin_user', 'idc', 'groups', 'status', 'env', 'is_active'
2017-03-15 16:19:47 +00:00
]
widgets = {
2017-04-12 03:50:15 +00:00
'groups': forms.SelectMultiple(
attrs={'class': 'select2',
'data-placeholder': _('Select asset groups')}),
'admin_user': forms.Select(
attrs={'class': 'select2',
'data-placeholder': _('Select asset admin user')}),
2017-03-15 16:19:47 +00:00
}
help_texts = {
'hostname': '* required',
'ip': '* required',
2017-04-12 03:50:15 +00:00
'system_users': _('System user will be granted for user to login '
'assets (using ansible create automatic)'),
'admin_user': _('Admin user should be exist on asset already, '
'And have sudo ALL permission'),
2017-03-15 16:19:47 +00:00
}
2017-04-09 09:59:14 +00:00
def clean_admin_user(self):
if not self.cleaned_data['admin_user']:
raise forms.ValidationError(_('Select admin user'))
return self.cleaned_data['admin_user']
2017-03-15 16:19:47 +00:00
2017-04-11 09:29:53 +00:00
class AssetUpdateForm(forms.ModelForm):
2017-03-15 16:19:47 +00:00
class Meta:
model = Asset
fields = [
'hostname', 'ip', 'port', 'groups', 'admin_user', 'idc', 'is_active',
'type', 'env', 'status', 'public_ip', 'remote_card_ip', 'cabinet_no',
2017-03-24 06:48:18 +00:00
'cabinet_pos', 'number', 'comment'
2016-08-14 14:10:10 +00:00
]
2016-09-04 11:12:31 +00:00
widgets = {
2017-04-12 03:50:15 +00:00
'groups': forms.SelectMultiple(
attrs={'class': 'select2',
'data-placeholder': _('Select asset groups')}),
'admin_user': forms.Select(
attrs={'class': 'select2',
'data-placeholder': _('Select asset admin user')}),
2016-09-17 15:43:41 +00:00
}
help_texts = {
'hostname': '* required',
'ip': '* required',
2017-04-12 03:50:15 +00:00
'system_users': _('System user will be granted for user '
'to login assets (using ansible create automatic)'),
'admin_user': _('Admin user should be exist on asset '
'already, And have sudo ALL permission'),
2016-09-04 11:12:31 +00:00
}
2016-08-14 14:10:10 +00:00
2017-04-11 09:29:53 +00:00
class AssetBulkUpdateForm(forms.ModelForm):
2017-04-12 03:50:15 +00:00
assets = forms.MultipleChoiceField(
required=True,
help_text='* required',
label=_('Select assets'),
2017-04-12 10:06:32 +00:00
# choices=[(asset.id, asset.hostname) for asset in Asset.objects.all()],
2017-04-12 03:50:15 +00:00
widget=forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('Select assets')
}
)
)
port = forms.IntegerField(min_value=1, max_value=65535,
required=False, label=_('Port'))
2017-04-11 09:29:53 +00:00
class Meta:
model = Asset
fields = [
2017-04-12 03:50:15 +00:00
'assets', 'port', 'groups', 'admin_user', 'idc',
2017-04-11 09:29:53 +00:00
'type', 'env', 'status',
]
widgets = {
'groups': forms.SelectMultiple(
attrs={'class': 'select2',
'data-placeholder': _('Select asset groups')}),
'admin_user': forms.Select(
attrs={'class': 'select2',
'data-placeholder': _('Select asset admin user')}),
}
2017-04-12 03:50:15 +00:00
def save(self, commit=True):
cleaned_data = {k: v for k, v in self.cleaned_data.items() if v is not None}
assets_id = cleaned_data.pop('assets')
groups = cleaned_data.pop('groups')
assets = Asset.objects.filter(id__in=assets_id)
assets.update(**cleaned_data)
if groups:
for asset in assets:
asset.groups.set(groups)
return assets
2017-04-11 09:29:53 +00:00
2016-08-14 14:10:10 +00:00
class AssetGroupForm(forms.ModelForm):
2016-09-08 14:54:05 +00:00
# See AdminUserForm comment same it
2017-03-24 06:48:18 +00:00
assets = forms.ModelMultipleChoiceField(
queryset=Asset.objects.all(),
label=_('Asset'),
required=False,
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')})
)
2016-09-05 16:49:42 +00:00
def __init__(self, *args, **kwargs):
2016-09-19 16:39:33 +00:00
if kwargs.get('instance', None):
2016-09-05 16:49:42 +00:00
initial = kwargs.get('initial', {})
initial['assets'] = kwargs['instance'].assets.all()
super(AssetGroupForm, self).__init__(*args, **kwargs)
def _save_m2m(self):
super(AssetGroupForm, self)._save_m2m()
assets = self.cleaned_data['assets']
self.instance.assets.clear()
self.instance.assets.add(*tuple(assets))
2016-08-14 14:10:10 +00:00
class Meta:
model = AssetGroup
fields = [
2017-04-07 08:59:09 +00:00
"name", "comment",
2016-08-14 14:10:10 +00:00
]
2016-09-07 12:05:42 +00:00
help_texts = {
'name': '* required',
}
2016-08-14 14:10:10 +00:00
2016-09-07 12:51:33 +00:00
class IDCForm(forms.ModelForm):
2016-09-08 14:54:05 +00:00
# See AdminUserForm comment same it
2017-04-07 08:59:09 +00:00
assets = forms.ModelMultipleChoiceField(
queryset=Asset.objects.all(),
label=_('Asset'),
required=False,
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')})
)
2016-09-07 12:51:33 +00:00
def __init__(self, *args, **kwargs):
if kwargs.get('instance'):
initial = kwargs.get('initial', {})
initial['assets'] = kwargs['instance'].assets.all()
super(IDCForm, self).__init__(*args, **kwargs)
def _save_m2m(self):
super(IDCForm, self)._save_m2m()
assets = self.cleaned_data['assets']
self.instance.assets.clear()
self.instance.assets.add(*tuple(assets))
2016-08-14 14:10:10 +00:00
class Meta:
model = IDC
2017-03-06 13:05:00 +00:00
fields = ['name', "bandwidth", "operator", 'contact',
'phone', 'address', 'intranet', 'extranet', 'comment']
2016-08-14 14:10:10 +00:00
widgets = {
2016-09-07 12:51:33 +00:00
'name': forms.TextInput(attrs={'placeholder': _('Name')}),
2016-09-19 09:25:41 +00:00
'intranet': forms.Textarea(
attrs={'placeholder': 'IP段之间用逗号隔开192.168.1.0/24,192.168.1.0/24'}),
'extranet': forms.Textarea(
attrs={'placeholder': 'IP段之间用逗号隔开201.1.32.1/24,202.2.32.1/24'})
2016-08-14 14:10:10 +00:00
}
2017-03-04 08:38:26 +00:00
help_texts = {
'name': '* required'
}
2016-09-07 16:59:00 +00:00
2016-09-08 10:12:53 +00:00
class AdminUserForm(forms.ModelForm):
2016-09-08 14:54:05 +00:00
# Admin user assets define, let user select, save it in form not in view
2017-01-20 12:13:22 +00:00
assets = forms.ModelMultipleChoiceField(
queryset=Asset.objects.all(),
label=_('Asset'),
required=False,
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')})
)
2016-09-08 14:54:05 +00:00
# Form field name can not start with `_`, so redefine it,
2017-01-20 12:13:22 +00:00
password = forms.CharField(
widget=forms.PasswordInput, max_length=100,
min_length=8, strip=True, required=False,
help_text=_('If also set private key, use that first'),
)
2016-09-08 14:54:05 +00:00
# Need use upload private key file except paste private key content
2016-09-08 10:12:53 +00:00
private_key_file = forms.FileField(required=False)
2016-09-07 16:59:00 +00:00
def __init__(self, *args, **kwargs):
2016-09-08 14:54:05 +00:00
# When update a admin user instance, initial it
2016-09-07 16:59:00 +00:00
if kwargs.get('instance'):
initial = kwargs.get('initial', {})
initial['assets'] = kwargs['instance'].assets.all()
2016-09-08 10:12:53 +00:00
super(AdminUserForm, self).__init__(*args, **kwargs)
2016-09-07 16:59:00 +00:00
def _save_m2m(self):
2016-09-08 14:54:05 +00:00
# Save assets relation with admin user
2016-09-08 10:12:53 +00:00
super(AdminUserForm, self)._save_m2m()
2016-09-07 16:59:00 +00:00
assets = self.cleaned_data['assets']
self.instance.assets.clear()
self.instance.assets.add(*tuple(assets))
2016-09-08 10:12:53 +00:00
def save(self, commit=True):
2016-09-08 14:54:05 +00:00
# Because we define custom field, so we need rewrite :method: `save`
2016-09-08 10:12:53 +00:00
admin_user = super(AdminUserForm, self).save(commit=commit)
password = self.cleaned_data['password']
2016-11-06 16:39:26 +00:00
private_key = self.cleaned_data['private_key_file']
2016-09-08 10:12:53 +00:00
if password:
admin_user.password = password
2016-11-06 16:39:26 +00:00
if private_key:
2017-01-20 12:13:22 +00:00
public_key = ssh_pubkey_gen(private_key)
2016-11-06 16:39:26 +00:00
admin_user.private_key = private_key
admin_user.public_key = public_key
2016-09-08 10:12:53 +00:00
admin_user.save()
2016-11-06 16:39:26 +00:00
return admin_user
def clean_private_key_file(self):
private_key_file = self.cleaned_data['private_key_file']
if private_key_file:
private_key = private_key_file.read()
if not validate_ssh_private_key(private_key):
raise forms.ValidationError(_('Invalid private key'))
return private_key
return private_key_file
def clean(self):
password = self.cleaned_data['password']
private_key_file = self.cleaned_data.get('private_key_file', '')
2017-01-20 12:13:22 +00:00
if not self.instance and not (password or private_key_file):
raise forms.ValidationError(
_('Password and private key file must be input one'))
2016-09-08 10:12:53 +00:00
2016-09-07 16:59:00 +00:00
class Meta:
2016-09-08 10:12:53 +00:00
model = AdminUser
2017-03-06 13:05:00 +00:00
fields = ['name', 'username', 'password',
'private_key_file', 'comment']
2016-09-07 16:59:00 +00:00
widgets = {
'name': forms.TextInput(attrs={'placeholder': _('Name')}),
2016-09-08 10:12:53 +00:00
'username': forms.TextInput(attrs={'placeholder': _('Username')}),
}
help_texts = {
'name': '* required',
'username': '* required',
}
2016-09-08 16:09:49 +00:00
class SystemUserForm(forms.ModelForm):
# Admin user assets define, let user select, save it in form not in view
2017-01-10 15:41:14 +00:00
auto_generate_key = forms.BooleanField(initial=True, required=False)
2016-09-08 16:09:49 +00:00
# Form field name can not start with `_`, so redefine it,
2017-03-09 06:55:33 +00:00
password = forms.CharField(widget=forms.PasswordInput, required=False,
max_length=100, min_length=8, strip=True)
2016-09-08 16:09:49 +00:00
# Need use upload private key file except paste private key content
private_key_file = forms.FileField(required=False)
def __init__(self, *args, **kwargs):
super(SystemUserForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
# Because we define custom field, so we need rewrite :method: `save`
system_user = super(SystemUserForm, self).save(commit=commit)
password = self.cleaned_data['password']
2017-03-09 06:55:33 +00:00
private_key_file = self.cleaned_data.get('private_key_file')
2016-09-08 16:09:49 +00:00
2017-01-10 15:41:14 +00:00
if system_user.auth_method == 'P':
if password:
system_user.password = password
2017-03-09 06:55:33 +00:00
elif system_user.auth_method == 'K':
if self.cleaned_data['auto_generate_key']:
private_key, public_key = ssh_key_gen(username=system_user.name)
logger.info('Generate private key and public key')
else:
private_key = private_key_file.read().strip()
public_key = ssh_pubkey_gen(private_key=private_key)
system_user.private_key = private_key
system_user.public_key = public_key
2016-09-08 16:09:49 +00:00
system_user.save()
return self.instance
2017-03-09 06:55:33 +00:00
def clean_private_key_file(self):
if self.data['auth_method'] == 'K' and \
not self.cleaned_data['auto_generate_key']:
if not self.cleaned_data['private_key_file']:
raise forms.ValidationError(_('Private key required'))
else:
key_string = self.cleaned_data['private_key_file'].read()
self.cleaned_data['private_key_file'].seek(0)
if not validate_ssh_private_key(key_string):
2017-04-07 08:59:09 +00:00
raise forms.ValidationError(_('Invalid private key'))
2017-03-09 06:55:33 +00:00
return self.cleaned_data['private_key_file']
def clean_password(self):
if self.data['auth_method'] == 'P':
if not self.cleaned_data.get('password'):
raise forms.ValidationError(_('Password required'))
return self.cleaned_data['password']
2017-01-10 15:41:14 +00:00
2016-09-08 16:09:49 +00:00
class Meta:
model = SystemUser
fields = [
2017-03-09 06:55:33 +00:00
'name', 'username', 'protocol', 'auto_generate_key', 'password',
'private_key_file', 'auth_method', 'auto_push', 'sudo',
'comment', 'shell'
2016-09-08 16:09:49 +00:00
]
widgets = {
'name': forms.TextInput(attrs={'placeholder': _('Name')}),
'username': forms.TextInput(attrs={'placeholder': _('Username')}),
}
help_texts = {
'name': '* required',
'username': '* required',
2016-12-29 11:17:00 +00:00
'auto_push': 'Auto push system user to asset',
2016-10-08 10:33:00 +00:00
}
2016-10-31 11:31:56 +00:00
2016-11-27 06:37:50 +00:00
class FileForm(forms.Form):
file = forms.FileField()