class SetAccessControlsAction(workflows.Action): keypair = forms.DynamicChoiceField(label=_("Key Pair"), required=False, help_text=_("Key pair to use for " "authentication."), add_item_link=KEYPAIR_IMPORT_URL) admin_pass = forms.RegexField( label=_("Admin Pass"), required=False, widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_admin_pass = forms.CharField( label=_("Confirm Admin Pass"), required=False, widget=forms.PasswordInput(render_value=False)) groups = forms.MultipleChoiceField(label=_("Security Groups"), initial=["default"], widget=forms.CheckboxSelectMultiple(), help_text=_("Launch instance in these " "security groups.")) class Meta: name = _("Access & Security") help_text = _("Control access to your instance via key pairs, " "security groups, and other mechanisms.") def __init__(self, request, *args, **kwargs): super(SetAccessControlsAction, self).__init__(request, *args, **kwargs) if not api.nova.can_set_server_password(): del self.fields['admin_pass'] del self.fields['confirm_admin_pass'] def populate_keypair_choices(self, request, context): try: keypairs = api.nova.keypair_list(request) keypair_list = [(kp.name, kp.name) for kp in keypairs] except Exception: keypair_list = [] exceptions.handle(request, _('Unable to retrieve key pairs.')) if keypair_list: if len(keypair_list) == 1: self.fields['keypair'].initial = keypair_list[0][0] keypair_list.insert(0, ("", _("Select a key pair"))) else: keypair_list = (("", _("No key pairs available")), ) return keypair_list def populate_groups_choices(self, request, context): try: groups = api.network.security_group_list(request) security_group_list = [(sg.name, sg.name) for sg in groups] except Exception: exceptions.handle(request, _('Unable to retrieve list of security groups')) security_group_list = [] return security_group_list def clean(self): '''Check to make sure password fields match.''' cleaned_data = super(SetAccessControlsAction, self).clean() if 'admin_pass' in cleaned_data: if cleaned_data['admin_pass'] != cleaned_data.get( 'confirm_admin_pass', None): raise forms.ValidationError(_('Passwords do not match.')) return cleaned_data
def __init__(self, request, *args, **kwargs): super(RegistrForm, self).__init__(request, *args, **kwargs) self.registr_err = None initial = kwargs['initial'] if 'initial' in kwargs else dict() self.fields['username'] = forms.CharField( label=_('User name'), max_length=OS_LNAME_LEN, widget=forms.HiddenInput if 'username' in initial else forms.TextInput ) self.fields['federated'] = forms.CharField( max_length=OS_LNAME_LEN, widget=forms.HiddenInput ) self.fields['givenname'] = forms.CharField( label=_('First name'), max_length=OS_LNAME_LEN, widget=forms.HiddenInput if 'givenname' in initial else forms.TextInput ) self.fields['sn'] = forms.CharField( label=_('Last name'), max_length=OS_LNAME_LEN, widget=forms.HiddenInput if 'sn' in initial else forms.TextInput ) if initial['needpwd']: self.fields['pwd'] = forms.RegexField( label=_("Password"), max_length=PWD_LEN, widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()} ) self.fields['repwd'] = forms.CharField( label=_("Confirm Password"), max_length=PWD_LEN, widget=forms.PasswordInput(render_value=False) ) self.fields['email'] = forms.EmailField( label=_('Email Address'), max_length=EMAIL_LEN, widget=forms.HiddenInput if 'email' in initial else forms.TextInput ) self.fields['prjaction'] = forms.ChoiceField( label=_('Project action'), #choices = <see later> widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'actsource' }) ) self.fields['newprj'] = forms.CharField( label=_('Personal project'), max_length=OS_SNAME_LEN, required=False, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Project name') }) ) self.fields['prjdescr'] = forms.CharField( label=_("Project description"), required=False, widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Project description') }) ) self.fields['prjpriv'] = forms.BooleanField( label=_("Private project"), required=False, initial=False, widget=forms.widgets.CheckboxInput(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Private project') }) ) self.fields['selprj'] = forms.MultipleChoiceField( label=_('Available projects'), required=False, widget=forms.SelectMultiple(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-selprj': _('Select existing project') }), ) self.fields['organization'] = forms.CharField( label=_('Organization'), required=True, widget=forms.HiddenInput if 'organization' in initial else forms.TextInput ) phone_regex = settings.HORIZON_CONFIG.get('phone_regex', '^\s*\+*[0-9]+[0-9\s.]+\s*$') self.fields['phone'] = forms.RegexField( label=_('Phone number'), required=True, regex=phone_regex, error_messages={'invalid': _("Wrong phone format")} ) self.fields['contactper'] = forms.CharField( label=_('Contact person'), required=False ) self.fields['notes'] = forms.CharField( label=_('Notes'), required=False, widget=forms.widgets.Textarea() ) self.fields['aupok'] = forms.CharField( widget=forms.HiddenInput, initial='reject' ) import_guest_project() missing_guest = True avail_prjs = list() for prj_entry in Project.objects.exclude(status=PRJ_PRIVATE): if prj_entry.status == PRJ_GUEST: missing_guest = False elif prj_entry.projectid: avail_prjs.append((prj_entry.projectname, prj_entry.projectname)) self.fields['selprj'].choices = avail_prjs if missing_guest: p_choices = [ ('selprj', _('Select existing projects')), ('newprj', _('Create new project')) ] else: p_choices = [ ('selprj', _('Select existing projects')), ('newprj', _('Create new project')), ('guestprj', _('Use guest project')) ] self.fields['prjaction'].choices = p_choices
class CreateUserForm(BaseUserForm): # Hide the domain_id and domain_name by default domain_id = hforms.CharField(label=_("Domain ID"), required=False, widget=hforms.HiddenInput()) domain_name = hforms.CharField(label=_("Domain Name"), required=False, widget=hforms.HiddenInput()) name = hforms.CharField(label=_("User Name")) email = hforms.EmailField(label=_("Email"), required=False) password = hforms.RegexField( label=_("Password"), widget=hforms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_password = hforms.CharField( label=_("Confirm Password"), required=False, widget=hforms.PasswordInput(render_value=False)) #registration : creat project named user's name while creat user , form hide this item project = hforms.ChoiceField(label=_("Primary Project")) #registration : role is default 'member', form hide this item role_id = hforms.ChoiceField(label=_("Role")) def __init__(self, *args, **kwargs): # roles = kwargs.pop('roles') # super(CreateUserForm, self).__init__(*args, **kwargs) # role_choices = [(role.id, role.name) for role in roles] # self.fields['role_id'].choices = role_choices # For keystone V3, display the two fields in read-only if api.keystone.VERSIONS.active >= 3: readonlyInput = hforms.TextInput(attrs={'readonly': 'readonly'}) self.fields["domain_id"].widget = readonlyInput self.fields["domain_name"].widget = readonlyInput # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data') def handle(self, request, data): domain = api.keystone.get_default_domain(self.request) #creat project named user's name cproject = api.keystone.tenant_create(request, name=data['name'], description='', enabled=True, domain=domain.id) try: LOG.info('Creating user with name "%s"' % data['name']) #creat user , write the data into database new_user = api.keystone.user_create(request, name=data['name'], email=data['email'], password=data['password'], project=cproject.id, enabled=True, domain=domain.id) #display in the web messages.success( request, _('User "%s" was successfully created registered.') % data['name']) #if user is specified a role , then Adds a role for a user on a tenant. if data['role_id']: try: api.keystone.add_tenant_user_role(request, cproject.id, new_user.id, data['role_id']) except Exception: exceptions.handle( request, _('Unable to add user ' 'to primary project.')) return new_user except Exception: exceptions.handle(request, _('Unable to create user.'))
class CreateUserForm(BaseUserForm): failure_url = 'horizon:vsm:usermgmt:index' name = forms.CharField(label=_("User name"), max_length=255, min_length=1, error_messages={ 'required': _('This field is required.'), 'invalid': _("Please enter a vaild User Name") }, validators=[ validate_user_name, ]) password = forms.RegexField( label=_("Password"), widget=forms.PasswordInput(render_value=False), regex=password_validate_regrex, required=False, max_length=255, min_length=8, error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.RegexField( label=_("Confirm Password"), widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), required=False, error_messages={'invalid': validators.password_validator_msg()}) # email = forms.CharField(label=_("Email"), # max_length=255, # min_length=1, # required=False, # error_messages={ # 'required': _('This field is required.'), # 'invalid': _('Please enter an email address.'), # },) def handle(self, request, data): LOG.error("CEPH_LOG> data %s " % data) data['email'] = '' try: admin_tenant = get_admin_tenant(request) tenant_id = admin_tenant.id ret = api.keystone.user_create(request, data['name'], data['email'], data['password'], tenant_id, enabled=True) LOG.error("CEPH_LOG> ret: %s " % ret) roles = api.keystone.role_list(request) for role in roles: if role.name in ['admin', 'KeystoneAdmin']: api.keystone.add_tenant_user_role(request, tenant_id, ret.id, role.id) LOG.error(api.keystone.user_get(request, ret.id)) messages.success(request, _('Successfully created user: %s') % data['name']) return ret except: redirect = reverse("horizon:vsm:usermgmt:index") exceptions.handle(request, _('Unable to create User.'), redirect=redirect)
class UpdateUserForm(BaseUserForm): # Hide the domain_id and domain_name by default domain_id = forms.CharField(label=_("Domain ID"), required=False, widget=forms.HiddenInput()) domain_name = forms.CharField(label=_("Domain Name"), required=False, widget=forms.HiddenInput()) id = forms.CharField(label=_("ID"), widget=forms.HiddenInput) name = forms.CharField(label=_("User Name")) email = forms.EmailField( label=_("Email"), required=False) password = forms.RegexField( label=_("Password"), widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), required=False, error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Password"), widget=forms.PasswordInput(render_value=False), required=False) project = forms.ChoiceField(label=_("Primary Project")) def __init__(self, request, *args, **kwargs): super(UpdateUserForm, self).__init__(request, *args, **kwargs) if api.keystone.keystone_can_edit_user() is False: for field in ('name', 'email', 'password', 'confirm_password'): self.fields.pop(field) # For keystone V3, display the two fields in read-only if api.keystone.VERSIONS.active >= 3: readonlyInput = forms.TextInput(attrs={'readonly': 'readonly'}) self.fields["domain_id"].widget = readonlyInput self.fields["domain_name"].widget = readonlyInput # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data', 'password') def handle(self, request, data): user = data.pop('id') # Throw away the password confirmation, we're done with it. data.pop('confirm_password', None) data.pop('domain_id') data.pop('domain_name') try: if "email" in data: data['email'] = data['email'] or None response = api.keystone.user_update(request, user, **data) messages.success(request, _('User has been updated successfully.')) except Exception: response = exceptions.handle(request, ignore=True) messages.error(request, _('Unable to update the user.')) if isinstance(response, http.HttpResponse): return response else: return True
class CreateUserForm(BaseUserForm): # Hide the domain_id and domain_name by default domain_id = forms.CharField(label=_("Domain ID"), required=False, widget=forms.HiddenInput()) domain_name = forms.CharField(label=_("Domain Name"), required=False, widget=forms.HiddenInput()) name = forms.CharField(label=_("User Name")) email = forms.EmailField(label=_("Email"), required=False) password = forms.RegexField( label=_("Password"), widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Password"), widget=forms.PasswordInput(render_value=False)) project = forms.DynamicChoiceField(label=_("Primary Project"), add_item_link=ADD_PROJECT_URL) role_id = forms.ChoiceField(label=_("Role")) def __init__(self, *args, **kwargs): roles = kwargs.pop('roles') super(CreateUserForm, self).__init__(*args, **kwargs) role_choices = [(role.id, role.name) for role in roles] self.fields['role_id'].choices = role_choices # For keystone V3, display the two fields in read-only if api.keystone.VERSIONS.active >= 3: readonlyInput = forms.TextInput(attrs={'readonly': 'readonly'}) self.fields["domain_id"].widget = readonlyInput self.fields["domain_name"].widget = readonlyInput # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data') def handle(self, request, data): domain = api.keystone.get_default_domain(self.request) try: LOG.info('Creating user with name "%s"' % data['name']) new_user = api.keystone.user_create(request, name=data['name'], email=data['email'], password=data['password'], project=data['project'], enabled=True, domain=domain.id) messages.success( request, _('User "%s" was successfully created.') % data['name']) if data['role_id']: try: api.keystone.add_tenant_user_role(request, data['project'], new_user.id, data['role_id']) except Exception: exceptions.handle( request, _('Unable to add user ' 'to primary project.')) return new_user except Exception: exceptions.handle(request, _('Unable to create user.'))
class UpdateUserForm(BaseUserForm): id = forms.CharField(label=_("ID"), widget=forms.HiddenInput) name = forms.CharField(label=_("User Name")) email = forms.EmailField(label=_("Email")) password = forms.RegexField( label=_("Password"), widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), required=False, error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Password"), widget=forms.PasswordInput(render_value=False), required=False) tenant_id = forms.ChoiceField(label=_("Primary Project")) def __init__(self, request, *args, **kwargs): super(UpdateUserForm, self).__init__(request, *args, **kwargs) if api.keystone_can_edit_user() == False: for field in ('name', 'email', 'password', 'confirm_password'): self.fields.pop(field) # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data', 'password') def handle(self, request, data): failed, succeeded = [], [] user_is_editable = api.keystone_can_edit_user() user = data.pop('id') tenant = data.pop('tenant_id') data.pop('method') if user_is_editable: password = data.pop('password') data.pop('confirm_password', None) if user_is_editable: # Update user details msg_bits = (_('name'), _('email')) try: api.keystone.user_update(request, user, **data) succeeded.extend(msg_bits) except: failed.extend(msg_bits) exceptions.handle(request, ignore=True) # Update default tenant msg_bits = (_('primary project'), ) try: api.user_update_tenant(request, user, tenant) succeeded.extend(msg_bits) except: failed.append(msg_bits) exceptions.handle(request, ignore=True) if user_is_editable: # If present, update password # FIXME(gabriel): password change should be its own form and view if password: msg_bits = (_('password'), ) try: api.user_update_password(request, user, password) succeeded.extend(msg_bits) except: failed.extend(msg_bits) exceptions.handle(request, ignore=True) if succeeded: messages.success(request, _('User has been updated successfully.')) if failed: failed = map(force_unicode, failed) messages.error( request, _('Unable to update %(attributes)s for the user.') % {"attributes": ", ".join(failed)}) return shortcuts.redirect('horizon:syspanel:users:index')
class BoardManagementAction(workflows.Action): FIELD_LABEL_BM_IP = _("Board Management Controller IP Address") FIELD_LABEL_BM_USERNAME = _("Board Management Controller User Name") FIELD_LABEL_BM_PASSWORD = _("Board Management Controller Password") FIELD_LABEL_BM_CONFIRM_PASSWORD = _("Confirm Password") bm_type = forms.ChoiceField(label=_("Board Management Controller Type "), choices=BM_TYPES_CHOICES, required=False, widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'bm_type' })) bm_ip = forms.IPField( label=FIELD_LABEL_BM_IP, required=False, help_text=_("IP address of the Board Management Controller" " (e.g. 172.25.0.0)"), version=forms.IPv4 | forms.IPv6, mask=False, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'bm_type', 'data-bm_type-' + stx_api.sysinv.BM_TYPE_GENERIC: FIELD_LABEL_BM_IP })) bm_username = forms.CharField( label=FIELD_LABEL_BM_USERNAME, required=False, widget=forms.TextInput( attrs={ 'autocomplete': 'off', 'class': 'switched', 'data-switch-on': 'bm_type', 'data-bm_type-' + stx_api.sysinv.BM_TYPE_GENERIC: FIELD_LABEL_BM_USERNAME })) bm_password = forms.RegexField( label=FIELD_LABEL_BM_PASSWORD, widget=forms.PasswordInput( render_value=False, attrs={ 'autocomplete': 'off', 'class': 'switched', 'data-switch-on': 'bm_type', 'data-bm_type-' + stx_api.sysinv.BM_TYPE_GENERIC: FIELD_LABEL_BM_PASSWORD }), regex=validators.password_validator(), required=False, error_messages={'invalid': validators.password_validator_msg()}) bm_confirm_password = forms.CharField( label=FIELD_LABEL_BM_CONFIRM_PASSWORD, widget=forms.PasswordInput( render_value=False, attrs={ 'autocomplete': 'off', 'class': 'switched', 'data-switch-on': 'bm_type', 'data-bm_type-' + stx_api.sysinv.BM_TYPE_GENERIC: FIELD_LABEL_BM_CONFIRM_PASSWORD }), required=False) def clean(self): cleaned_data = super(BoardManagementAction, self).clean() if cleaned_data.get('bm_type'): if 'bm_ip' not in cleaned_data or not cleaned_data['bm_ip']: raise forms.ValidationError( _('Board management IP address is required.')) raise forms.ValidationError( _('Board management MAC address is required.')) if 'bm_username' not in cleaned_data or not \ cleaned_data['bm_username']: raise forms.ValidationError( _('Board management user name is required.')) if 'bm_password' in cleaned_data: if cleaned_data['bm_password'] != cleaned_data.get( 'bm_confirm_password', None): raise forms.ValidationError( _('Board management passwords do not match.')) else: cleaned_data.pop('bm_ip') cleaned_data.pop('bm_username') return cleaned_data # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data') def handle(self, request, data): # Throw away the password confirmation, we're done with it. data.pop('bm_confirm_password', None)
class RebuildInstanceForm(forms.SelfHandlingForm): instance_id = forms.CharField(widget=forms.HiddenInput()) image = forms.ChoiceField( label=_("Select Image"), widget=forms.SelectWidget( attrs={'class': 'image-selector'}, data_attrs=('size', 'display-name'), transform=_image_choice_title)) password = forms.RegexField( label=_("Rebuild Password"), required=False, widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Rebuild Password"), required=False, widget=forms.PasswordInput(render_value=False)) disk_config = forms.ChoiceField(label=_("Disk Partition"), required=False) description = forms.CharField( label=_("Description"), widget=forms.Textarea(attrs={'rows': 4}), max_length=255, required=False ) def __init__(self, request, *args, **kwargs): super(RebuildInstanceForm, self).__init__(request, *args, **kwargs) if not api.nova.is_feature_available(request, "instance_description"): del self.fields['description'] instance_id = kwargs.get('initial', {}).get('instance_id') self.fields['instance_id'].initial = instance_id images = image_utils.get_available_images(request, request.user.tenant_id) choices = [(image.id, image) for image in images] if choices: choices.insert(0, ("", _("Select Image"))) else: choices.insert(0, ("", _("No images available"))) self.fields['image'].choices = choices if not api.nova.can_set_server_password(): del self.fields['password'] del self.fields['confirm_password'] try: if not api.nova.extension_supported("DiskConfig", request): del self.fields['disk_config'] else: # Set our disk_config choices config_choices = [("AUTO", _("Automatic")), ("MANUAL", _("Manual"))] self.fields['disk_config'].choices = config_choices except Exception: exceptions.handle(request, _('Unable to retrieve extensions ' 'information.')) def clean(self): cleaned_data = super(RebuildInstanceForm, self).clean() if 'password' in cleaned_data: passwd = cleaned_data.get('password') confirm = cleaned_data.get('confirm_password') if passwd is not None and confirm is not None: if passwd != confirm: raise forms.ValidationError(_("Passwords do not match.")) return cleaned_data # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data', 'password') def handle(self, request, data): instance = data.get('instance_id') image = data.get('image') password = data.get('password') or None disk_config = data.get('disk_config', None) description = data.get('description', None) try: api.nova.server_rebuild(request, instance, image, password, disk_config, description=description) messages.info(request, _('Rebuilding instance %s.') % instance) except Exception: redirect = reverse('horizon:project:instances:index') exceptions.handle(request, _("Unable to rebuild instance."), redirect=redirect) return True
def __init__(self, request, *args, **kwargs): super(RegistrForm, self).__init__(request, *args, **kwargs) self.registr_err = None initial = kwargs['initial'] if 'initial' in kwargs else dict() self.fields['username'] = forms.CharField( label=_('User name'), max_length=OS_LNAME_LEN, widget=forms.HiddenInput if 'username' in initial else forms.TextInput) self.fields['federated'] = forms.CharField(max_length=OS_LNAME_LEN, widget=forms.HiddenInput) self.fields['givenname'] = forms.CharField( label=_('First name'), max_length=OS_LNAME_LEN, widget=forms.HiddenInput if 'givenname' in initial else forms.TextInput) self.fields['sn'] = forms.CharField( label=_('Last name'), max_length=OS_LNAME_LEN, widget=forms.HiddenInput if 'sn' in initial else forms.TextInput) if initial['needpwd']: self.fields['pwd'] = forms.RegexField( label=_("Password"), max_length=PWD_LEN, widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={ 'invalid': validators.password_validator_msg() }) self.fields['repwd'] = forms.CharField( label=_("Confirm Password"), max_length=PWD_LEN, widget=forms.PasswordInput(render_value=False)) self.fields['email'] = forms.EmailField( label=_('Email Address'), max_length=EMAIL_LEN, widget=forms.HiddenInput if 'email' in initial else forms.TextInput) self.fields['prjaction'] = forms.ChoiceField( label=_('Project action'), #choices = <see later> widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'actsource' })) self.fields['newprj'] = forms.CharField( label=_('Personal project'), max_length=OS_SNAME_LEN, required=False, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Project name') })) self.fields['prjdescr'] = forms.CharField( label=_("Project description"), required=False, widget=forms.widgets.Textarea( attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Project description') })) self.fields['prjpriv'] = forms.BooleanField( label=_("Private project"), required=False, initial=False, widget=forms.widgets.CheckboxInput( attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Private project') })) self.fields['selprj'] = forms.MultipleChoiceField( label=_('Available projects'), required=False, widget=forms.SelectMultiple( attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-selprj': _('Select existing project') }), ) self.fields['organization'] = forms.CharField( label=_('Organization'), required=True, widget=forms.HiddenInput if 'organization' in initial else forms.TextInput) phone_regex = settings.HORIZON_CONFIG.get( 'phone_regex', '^\s*\+*[0-9]+[0-9\s.]+\s*$') self.fields['phone'] = forms.RegexField( label=_('Phone number'), required=True, regex=phone_regex, error_messages={'invalid': _("Wrong phone format")}) self.fields['contactper'] = forms.CharField(label=_('Contact person'), required=False) self.fields['notes'] = forms.CharField(label=_('Notes'), required=False, widget=forms.widgets.Textarea()) self.fields['aupok'] = forms.CharField(widget=forms.HiddenInput, initial='reject') import_guest_project() missing_guest = True avail_prjs = list() for prj_entry in Project.objects.exclude(status=PRJ_PRIVATE): if prj_entry.status == PRJ_GUEST: missing_guest = False elif prj_entry.projectid: avail_prjs.append( (prj_entry.projectname, prj_entry.projectname)) self.fields['selprj'].choices = avail_prjs if missing_guest: p_choices = [('selprj', _('Select existing projects')), ('newprj', _('Create new project'))] else: p_choices = [('selprj', _('Select existing projects')), ('newprj', _('Create new project')), ('guestprj', _('Use guest project'))] self.fields['prjaction'].choices = p_choices
class CreateAccountGenericAction(CommonAccountGenericAction): class Meta(object): name = _("Generic") slug = 'account_generic' project_mapping = forms.ChoiceField( label=_('Mapping'), choices=[('0', 'Create New Project'), ('1', 'Use Existing Project')], required=False, widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'project_mapping' })) project_name = forms.CharField( label=_('Project Name'), required=False, widget=forms.TextInput( attrs={ 'placeholder': 'must be a valid project name', 'class': 'switched', 'data-switch-on': 'project_mapping', 'data-project_mapping-0': _('Project Name') })) description = forms.CharField( label=_("Description"), required=False, widget=forms.widgets.Textarea( attrs={ 'rows': 4, 'class': 'switched', 'data-switch-on': 'project_mapping', 'data-project_mapping-0': _('Description') })) username = forms.CharField( label=_('Project User'), required=False, widget=forms.TextInput( attrs={ 'placeholder': 'leave blank to use value of project name', 'class': 'switched', 'data-switch-on': 'project_mapping', 'data-project_mapping-0': _('Project User') })) # password = forms.CharField( # label=_('Password'), # required=False, # widget=forms.TextInput(attrs={ # 'placeholder': password_requirement_str, # 'type': 'password', # 'class': 'switched', # 'data-switch-on': 'project_mapping', # 'data-project_mapping-0': _('Password') # }) # ) # confirm_password = forms.CharField( # label=_('Confirm Password'), # required=False, # widget=forms.TextInput(attrs={ # 'placeholder': 'must match password value above', # 'type': 'password', # 'class': 'switched', # 'data-switch-on': 'project_mapping', # 'data-project_mapping-0': _('Confirm Password') # }) # ) password = forms.RegexField( label=_("Password"), widget=forms.TextInput( attrs={ 'placeholder': password_requirement_str, 'type': 'password', 'class': 'switched', 'data-switch-on': 'project_mapping', 'data-project_mapping-0': _('Password') }), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Password"), widget=forms.TextInput( attrs={ 'placeholder': 'must match password value above', 'type': 'password', 'class': 'switched', 'data-switch-on': 'project_mapping', 'data-project_mapping-0': _('Confirm Password') })) project_id = forms.ChoiceField( label=_('Project'), choices=[], required=False, widget=forms.Select( attrs={ 'class': 'switched', 'data-switch-on': 'project_mapping', 'data-project_mapping-1': _('Project') })) billing_type = forms.ChoiceField(label=_('Billing Type'), choices=[], required=False) def __init__(self, request, *args, **kwargs): super(CreateAccountGenericAction, self).__init__(request, *args, **kwargs) # populate existing projects #Keystone connection #(_projects, _) = keystone.tenant_list(self.request) (_projects, _) = get_tenants(self.request) projects = [(project.id, project.name) for project in _projects] self.fields['project_id'].choices = projects # populate billing types # TODO (div): switch on astudeclient lib [get_billing_types()] billing_types = [(billing_type['id'], billing_type['name']) for billing_type in get_billing_types(request)] self.fields['billing_type'].choices = billing_types # data clean up and validation def clean(self): cleaned_data = super(CreateAccountGenericAction, self).clean() if str(cleaned_data.get('project_mapping')) == '0': # validate new project fields msg_field_is_required = 'This field is required.' cleaned_data['project_name'] = (cleaned_data.get('project_name') or '').strip() project_name = cleaned_data['project_name'] if project_name == '': self.add_error('project_name', msg_field_is_required) else: # check if specified project is already exists #if len([p for p in keystone.tenant_list(self.request)[0] if p.name == project_name]) > 0: if len([ p for p in get_projects(self.request) if p.name == project_name ]) > 0: self.add_error( 'project_name', 'Project `%s` already exists.' % project_name) cleaned_data['username'] = (cleaned_data.get('username') or cleaned_data.get('project_name') or '').strip() username = cleaned_data['username'] if username != '': # check if specified user is already exists #if len([u for u in keystone.user_list(self.request) if u.name == username]) > 0: ks = get_admin_ksclient() if len( [u for u in get_users(self.request) if u.name == username ]) > 0: self.add_error('username', 'User `%s` already exists.' % username) password = cleaned_data.get('password') if not password: self.add_error('password', msg_field_is_required) # else: # # check password strength # if not ( # any(c.isupper() for c in password) and \ # any(c.islower() for c in password) and \ # any(c.isdigit() for c in password) and \ # len(password) >= 8 # ): # self.add_error('password', 'Password is too weak: %s.' % password_requirement_str) confirm = cleaned_data.get('confirm_password') if not confirm: self.add_error('confirm_password', msg_field_is_required) if password and confirm and password != confirm: self.add_error('confirm_password', 'Confirmation does not match password.') return cleaned_data
class RebuildInstanceForm(forms.SelfHandlingForm): instance_id = forms.CharField(widget=forms.HiddenInput()) image = forms.ChoiceField(label=_("Select Image"), widget=fields.SelectWidget( attrs={'class': 'image-selector'}, data_attrs=('size', 'display-name'), transform=_image_choice_title)) password = forms.RegexField( label=_("Rebuild Password"), required=False, widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Rebuild Password"), required=False, widget=forms.PasswordInput(render_value=False)) def __init__(self, request, *args, **kwargs): super(RebuildInstanceForm, self).__init__(request, *args, **kwargs) instance_id = kwargs.get('initial', {}).get('instance_id') self.fields['instance_id'].initial = instance_id images = utils.get_available_images(request, request.user.tenant_id) choices = [(image.id, image) for image in images] if choices: choices.insert(0, ("", _("Select Image"))) else: choices.insert(0, ("", _("No images available."))) self.fields['image'].choices = choices if not api.nova.can_set_server_password(): del self.fields['password'] del self.fields['confirm_password'] def clean(self): cleaned_data = super(RebuildInstanceForm, self).clean() if 'password' in cleaned_data: passwd = cleaned_data.get('password') confirm = cleaned_data.get('confirm_password') if passwd is not None and confirm is not None: if passwd != confirm: raise forms.ValidationError(_("Passwords do not match.")) return cleaned_data # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data', 'password') def handle(self, request, data): instance = data.get('instance_id') image = data.get('image') password = data.get('password') or None try: api.nova.server_rebuild(request, instance, image, password) messages.success(request, _('Rebuilding instance %s.') % instance) except Exception: redirect = reverse('horizon:project:instances:index') exceptions.handle(request, _("Unable to rebuild instance."), redirect=redirect) return True
class RebuildInstanceForm(forms.SelfHandlingForm): instance_id = forms.CharField(widget=forms.HiddenInput()) image = forms.ChoiceField( label=_("New Image"), widget=forms.SelectWidget(attrs={'class': 'image-selector'}, data_attrs=('size', 'display-name'), transform=_image_choice_title)) username = forms.CharField(max_length=64, label=_("User Name")) sync_set_root = forms.BooleanField(label=_("Sync set root/Administrator password"), initial=True, required=False) password = forms.RegexField( label=_("Rebuild Password"), required=False, widget=forms.PasswordInput(render_value=False, attrs={'placeholder': _('begin letter,8-64 bits,with number,letter and symbol')}), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) confirm_password = forms.CharField( label=_("Confirm Rebuild Password"), required=False, widget=forms.PasswordInput(render_value=False)) # disk_config = forms.ChoiceField(label=_("Disk Partition"), # required=False) def __init__(self, request, *args, **kwargs): super(RebuildInstanceForm, self).__init__(request, *args, **kwargs) instance_id = kwargs.get('initial', {}).get('instance_id') self.fields['instance_id'].initial = instance_id self.fields["username"].initial = 'syscloud' images = utils.get_available_images(request, request.user.tenant_id) choices = [(image.id, image) for image in images] if choices: choices.insert(0, ("", _("Select Image"))) else: choices.insert(0, ("", _("No images available"))) self.fields['image'].choices = choices if not api.nova.can_set_server_password(): del self.fields['password'] del self.fields['confirm_password'] # try: # if not api.nova.extension_supported("DiskConfig", request): # del self.fields['disk_config'] # else: # # Set our disk_config choices # config_choices = [("AUTO", _("Automatic")), # ("MANUAL", _("Manual"))] # self.fields['disk_config'].choices = config_choices # except Exception: # exceptions.handle(request, _('Unable to retrieve extensions ' # 'information.')) def clean(self): cleaned_data = super(RebuildInstanceForm, self).clean() is_allow_inject_passwd = False select_image_id = cleaned_data.get('image', None) if select_image_id != None: image = api.glance.image_get(self.request, select_image_id) is_allow_inject_passwd = getattr(image, 'is_allow_inject_passwd', False) cleaned_data['is_allow_inject_passwd'] = is_allow_inject_passwd cleaned_data['image_name'] = image.name if 'password' in cleaned_data: passwd = cleaned_data.get('password') confirm = cleaned_data.get('confirm_password') if passwd is not None and confirm is not None: if passwd != confirm: raise forms.ValidationError(_("Passwords do not match.")) if is_allow_inject_passwd: if not validators.validate_password(passwd): raise forms.ValidationError(_("The password must begin with a letter, " "and the length is between the 8-64 bits, " "and the number, the letter and the symbol are the same.")) return cleaned_data # We have to protect the entire "data" dict because it contains the # password and confirm_password strings. @sensitive_variables('data', 'password') def handle(self, request, data): instance = data.get('instance_id') image = data.get('image') image_name = data.get('image_name', None) is_allow_inject_passwd = data.get('is_allow_inject_passwd', None) username = data.get('username', 'syscloud') password = data.get('password') or None disk_config = data.get('disk_config', None) is_sync_set_root = data.get('sync_set_root', False) if is_allow_inject_passwd: user_data_script_helper = userdata.UserDataScriptHelper(image_name, is_sync_set_root=is_sync_set_root, is_rebuild=True) password = user_data_script_helper.get_user_data(username, password) try: api.nova.server_rebuild(request, instance, image, password, disk_config) messages.success(request, _('Rebuilding instance %s.') % instance) # operation log config = _('Instance ID: %s') %instance api.logger.Logger(request).create(resource_type='instance', action_name='Rebuild Instance', resource_name='Instance', config=config, status='Success') except Exception: redirect = reverse('horizon:instances:instances:index') exceptions.handle(request, _("Unable to rebuild instance."), redirect=redirect) # operation log config = _('Instance ID: %s') %instance api.logger.Logger(request).create(resource_type='instance', action_name='Rebuild Instance', resource_name='Instance', config=config, status='Error') return True
def __init__(self, request, *args, **kwargs): super(RegistrForm, self).__init__(request, *args, **kwargs) self.registr_err = None initial = kwargs['initial'] if 'initial' in kwargs else dict() ################################################################################# # Account section ################################################################################# username_attrs = {'readonly': 'readonly'} if 'username' in initial else {} self.fields['username'] = forms.CharField( label=_('User name'), max_length=OS_LNAME_LEN, widget=forms.TextInput(attrs=username_attrs) ) self.fields['federated'] = forms.CharField( max_length=OS_LNAME_LEN, widget=forms.HiddenInput ) gname_attrs = {'readonly': 'readonly'} if 'givenname' in initial else {} self.fields['givenname'] = forms.CharField( label=_('First name'), max_length=OS_LNAME_LEN, widget=forms.TextInput(attrs=gname_attrs) ) sname_attrs = {'readonly': 'readonly'} if 'sn' in initial else {} self.fields['sn'] = forms.CharField( label=_('Last name'), max_length=OS_LNAME_LEN, widget=forms.TextInput(attrs=sname_attrs) ) if initial['needpwd']: self.fields['pwd'] = forms.RegexField( label=_("Password"), max_length=PWD_LEN, widget=forms.PasswordInput(render_value=False), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()} ) self.fields['repwd'] = forms.CharField( label=_("Confirm Password"), max_length=PWD_LEN, widget=forms.PasswordInput(render_value=False) ) mail_attrs = {'readonly': 'readonly'} if 'email' in initial else {} self.fields['email'] = forms.EmailField( label=_('Email Address'), max_length=EMAIL_LEN, widget=forms.TextInput(attrs=mail_attrs) ) ################################################################################# # Projects section ################################################################################# org_table = settings.HORIZON_CONFIG.get('organization', {}) dept_list = org_table.get(initial.get('organization', ''), None) if 'selprj' in initial: self.fields['prjaction'] = forms.CharField( label=_('Project action'), widget=forms.HiddenInput ) self.fields['selprj'] = forms.CharField( label=_('Available projects'), widget=forms.HiddenInput ) else: p_choices = [ ('selprj', _('Select existing projects')), ('newprj', _('Create new project')) ] prjguest_name = settings.HORIZON_CONFIG.get('guest_project', "") avail_prjs = list() for prj_entry in Project.objects.exclude(status=PRJ_PRIVATE): if prj_entry.projectname == prjguest_name: p_choices.append(('guestprj', _('Use guest project'))) elif prj_entry.projectid: avail_prjs.append((prj_entry.projectname, prj_entry.projectname)) self.fields['prjaction'] = forms.ChoiceField( label=_('Project action'), choices = p_choices, widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'actsource' }) ) self.fields['newprj'] = forms.CharField( label=_('Project name'), max_length=OS_SNAME_LEN, required=True, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Project name') }) ) self.fields['prjdescr'] = forms.CharField( label=_("Project description"), required=True, widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Project description') }) ) self.fields['prjpriv'] = forms.BooleanField( label=_("Private project"), required=False, initial=False, widget=forms.widgets.CheckboxInput(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Private project') }) ) if dept_list: self.fields['contactper'] = forms.CharField( widget=forms.HiddenInput, initial='unknown' ) else: self.fields['contactper'] = forms.CharField( label=_('Contact person'), required=False, widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-newprj': _('Contact person') }) ) self.fields['selprj'] = forms.MultipleChoiceField( label=_('Available projects'), required=False, choices=avail_prjs, widget=forms.SelectMultiple(attrs={ 'class': 'switched', 'data-switch-on': 'actsource', 'data-actsource-selprj': _('Select existing project') }), ) ################################################################################# # Other Fields ################################################################################# if 'organization' in initial: self.fields['organization'] = forms.CharField(required=True, widget=forms.HiddenInput) if dept_list: self.fields['org_unit'] = forms.ChoiceField( label=_('Organization Unit'), required=True, choices=[ x[:2] for x in dept_list ] ) else: # # Workaround: hex string is required by the selector index # all_orgs = [ (x.encode('hex'), x) for x in org_table.keys() ] all_orgs.append(('other', _('Other organization'))) self.fields['encoded_org'] = forms.ChoiceField( label=_('Organization'), required=True, choices=all_orgs, widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'orgwidget' }) ) self.fields['custom_org'] = forms.CharField( label=_('Enter organization'), required=False, widget=forms.widgets.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'orgwidget', 'data-orgwidget-other': _('Enter organization') }) ) for org_id, ou_list in org_table.items(): enc_org_id = org_id.encode('hex') if not ou_list: continue self.fields['org_unit_%s' % enc_org_id] = forms.ChoiceField( label=_('Organization Unit'), required=True, choices=[ x[:2] for x in ou_list ], widget=forms.Select(attrs={ 'class': 'switched', 'data-switch-on': 'orgwidget', 'data-orgwidget-%s' % enc_org_id: _('Organization Unit') }) ) # In case use regex: '^\s*\+*[0-9]+[0-9\s.]+\s*$' if 'phone_regex' in settings.HORIZON_CONFIG: self.fields['phone'] = forms.RegexField( label=_('Phone number'), required=True, regex=settings.HORIZON_CONFIG['phone_regex'], error_messages={'invalid': _("Wrong phone format")} ) else: self.fields['phone'] = forms.CharField( widget=forms.HiddenInput, initial='00000000' ) self.fields['notes'] = forms.CharField( label=_('Notes'), required=False, widget=forms.widgets.Textarea() ) self.fields['aupok'] = forms.CharField( widget=forms.HiddenInput, initial='reject' )
class CloudEditAction(workflows.Action): id= forms.CharField(widget=forms.HiddenInput(), required=False) cloudtype_choices = ( ("", _("Select CloudType")), ('private','Private'), ('public','Public'),) cloudtype = forms.ChoiceField( label=_("Cloud Type"), required=False, widget=forms.HiddenInput(), choices=cloudtype_choices ) cloudslist = forms.ChoiceField( label=_("Platform"), required=False, widget=fields.SelectWidget( data_attrs=('platform',), transform=lambda x: ("%s " % (x.platform))) ) cloudname1 = forms.CharField(label=_("Cloud Name"),max_length=80) username1 = forms.CharField(max_length=80, label=_("User Name")) password1 = forms.RegexField( label=_("Password"), widget=forms.PasswordInput(render_value=True), regex=validators.password_validator(), error_messages={'invalid': validators.password_validator_msg()}) endpoint1 = forms.CharField(max_length=80, label=_("Endpoint(IP with HTTP)")) def populate_cloudslist_choices(self, request, context): try: roles = [] id = context.get('id', None) cloud = tenantclouds.objects(id = id).first() roles.append((cloud.id,cloud)) except Exception: exceptions.handle(request, _('Unable to retrieve list of Cloud Details')) roles = [] return roles class Meta: name = _("Edit Cloud") def __init__(self, *args, **kwargs): super(CloudEditAction, self).__init__(*args, **kwargs) try: region_list = get_regions_wo_connection() tenantcloud_id = args[-1]["id"] cloud = tenantclouds.objects(id = tenantcloud_id).first() cloud_obj = clouds.objects(id=cloud.cloudid.id).first() self.fields['username1'].label = _(cloud_obj.credential_fields[0]) self.fields["password1"].label = _(cloud_obj.credential_fields[1]) if cloud_obj.name == "Amazon": self.fields["endpoint1"] = forms.ChoiceField(label=_("Default Region"), choices = region_list, help_text=_("Select default region")) self.fields["endpoint1"].label = _(cloud_obj.credential_fields[2]) else: self.fields["endpoint1"].label = _(cloud_obj.credential_fields[2]) except Exception, e: messages.error(self.request,_(e.message)) LOG.error(e.message)