jumpserver/apps/assets/forms/domain.py

68 lines
2.2 KiB
Python
Raw Normal View History

2018-03-23 11:46:46 +00:00
# -*- coding: utf-8 -*-
#
from django import forms
from django.utils.translation import gettext_lazy as _
2018-07-17 09:09:36 +00:00
from orgs.mixins import OrgModelForm
2018-03-23 11:46:46 +00:00
from ..models import Domain, Asset, Gateway
from .user import PasswordAndKeyAuthForm
__all__ = ['DomainForm', 'GatewayForm']
class DomainForm(forms.ModelForm):
assets = forms.ModelMultipleChoiceField(
2018-07-14 16:55:05 +00:00
queryset=Asset.objects.all(), label=_('Asset'), required=False,
2018-03-23 11:46:46 +00:00
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')}
)
)
class Meta:
model = Domain
fields = ['name', 'comment', 'assets']
def __init__(self, *args, **kwargs):
if kwargs.get('instance', None):
initial = kwargs.get('initial', {})
initial['assets'] = kwargs['instance'].assets.all()
super().__init__(*args, **kwargs)
def save(self, commit=True):
instance = super().save(commit=commit)
assets = self.cleaned_data['assets']
instance.assets.set(assets)
return instance
2018-07-17 09:09:36 +00:00
class GatewayForm(PasswordAndKeyAuthForm, OrgModelForm):
2018-08-15 09:44:06 +00:00
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
password_field = self.fields.get('password')
password_field.help_text = _('Password should not contain special characters')
protocol_field = self.fields.get('protocol')
protocol_field.choices = [Gateway.PROTOCOL_CHOICES[0]]
2018-03-23 11:46:46 +00:00
def save(self, commit=True):
# Because we define custom field, so we need rewrite :method: `save`
instance = super().save()
password = self.cleaned_data.get('password')
private_key, public_key = super().gen_keys()
instance.set_auth(password=password, private_key=private_key)
return instance
class Meta:
model = Gateway
fields = [
'name', 'ip', 'port', 'username', 'protocol', 'domain', 'password',
'private_key_file', 'is_active', 'comment',
]
widgets = {
'name': forms.TextInput(attrs={'placeholder': _('Name')}),
'username': forms.TextInput(attrs={'placeholder': _('Username')}),
}
help_texts = {
'name': '* required',
'username': '* required',
}