Beispiel #1
0
class SignupForm(SelfHandlingForm):

    username = forms.CharField(
        label=_("Username"),
        max_length=255,
        widget=forms.TextInput(attrs={
            'placeholder': _('Username'),
            'autofocus': 'autofocus'
        }))
    email = forms.EmailField(widget=forms.TextInput(
        attrs={
            'type': 'email',
            'placeholder': _('E-mail address')
        }))

    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))
    no_autocomplete = True

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(SignupForm, self).clean()

        # basic check for now
        if 'username' in data:
            if User.objects.filter(username=data['username'],
                                   email=data['email']).exists():
                raise validators.ValidationError(
                    _('Username or email exists in database.'))

        if 'password' in data:
            if data['password'] != data.get('confirm_password', None):
                raise validators.ValidationError(_('Passwords do not match.'))
            else:
                data.pop('confirm_password')
        return data

    def handle(self, request, data):

        try:
            user = User.objects.create_user(**data)
            messages.success(
                request,
                _("User account {} was successfuly created.".format(user)))

        except Exception as e:
            raise e
        else:
            data.pop('email')
            return LoginForm().handle(request, data)

        messages.error(request, _("Create Account failed."))
        return False
Beispiel #2
0
class PasswordForm(forms.SelfHandlingForm):
    current_password = forms.CharField(
        label=_("Current password"),
        strip=False,
        widget=forms.PasswordInput(render_value=False))
    new_password = forms.RegexField(
        label=_("New password"),
        strip=False,
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=_("Confirm new password"),
        strip=False,
        widget=forms.PasswordInput(render_value=False))
    no_autocomplete = True

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super().clean()
        if 'new_password' in data:
            if data['new_password'] != data.get('confirm_password', None):
                raise ValidationError(_('Passwords do not match.'))
            if data.get('confirm_password', None) == \
                    data.get('current_password', None):
                raise ValidationError(
                    _('Old password and new password '
                      'must be different'))
        return data

    # We have to protect the entire "data" dict because it contains the
    # oldpassword and newpassword strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        user_is_editable = api.keystone.keystone_can_edit_user()
        user_id = request.user.id
        user = api.keystone.user_get(self.request, user_id, admin=False)
        options = getattr(user, "options", {})
        lock_password = options.get("lock_password", False)
        if lock_password:
            messages.error(request, _('Password is locked.'))
            return False

        if user_is_editable:
            try:
                api.keystone.user_update_own_password(request,
                                                      data['current_password'],
                                                      data['new_password'])
                response = http.HttpResponseRedirect(settings.LOGOUT_URL)
                msg = _("Password changed. Please log in again to continue.")
                utils.add_logout_reason(request, response, msg)
                return response
            except Exception:
                exceptions.handle(request, _('Unable to change password.'))
                return False
        else:
            messages.error(request, _('Changing password is not supported.'))
            return False
Beispiel #3
0
class Update(forms.SelfHandlingForm):
    name = forms.CharField(max_length="255", label=_("Share Name"))
    dns_ip = forms.CharField(
        max_length="15", label=_("DNS IP"), required=False)
    ou = forms.CharField(
        max_length="255",
        label=_("Organizational Unit"),
        required=False)
    server = forms.CharField(
        max_length="255", label=_("Server"), required=False)
    domain = forms.CharField(
        max_length="255", label=_("Domain"), required=False)
    user = forms.CharField(
        max_length="255", label=_("User"), required=False)
    password = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput(render_value=False),
        required=False)
    confirm_password = forms.CharField(
        label=_("Confirm Password"),
        widget=forms.PasswordInput(render_value=False),
        required=False)
    description = forms.CharField(
        widget=forms.Textarea, label=_("Description"), required=False)

    def clean(self):
        '''Check to make sure password fields match.'''
        cleaned_data = super(forms.Form, self).clean()
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password != confirm_password:
            raise ValidationError(_('Passwords do not match.'))
        return cleaned_data

    @sensitive_variables('data')
    def handle(self, request, data):
        sec_service_id = self.initial['sec_service_id']
        try:
            manila.security_service_update(
                request, sec_service_id,
                dns_ip=data['dns_ip'],
                ou=data['ou'],
                server=data['server'],
                domain=data['domain'],
                password=data.get('password') or None,
                user=data['user'],
                name=data['name'],
                description=data['description'])

            message = _('Successfully updated security service '
                        '"%s"') % data['name']
            messages.success(request, message)
            return True
        except Exception:
            redirect = reverse("horizon:project:security_services:index")
            exceptions.handle(request,
                              _('Unable to update security service.'),
                              redirect=redirect)
Beispiel #4
0
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 Password"),
        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 Password"),
        required=False,
        widget=forms.PasswordInput(render_value=False))
    groups = forms.MultipleChoiceField(label=_("Security Groups"),
                                       required=False,
                                       initial=["default"],
                                       widget=forms.CheckboxSelectMultiple(),
                                       help_text=_("Launch instance in these "
                                                   "security groups."))

    class Meta(object):
        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):
        keypairs = instance_utils.keypair_field_data(request, True)
        if len(keypairs) == 2:
            self.fields['keypair'].initial = keypairs[1][0]
        return keypairs

    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
Beispiel #5
0
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:
            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
Beispiel #6
0
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.name) for image in images]
        if choices:
            choices.insert(0, ("", _("Select Image")))
        else:
            choices.insert(0, ("", _("No images available.")))
        self.fields['image'].choices = choices

    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
Beispiel #7
0
class PasswordForm(forms.SelfHandlingForm):
    current_password = forms.CharField(
        label=_("Current password"),
        widget=forms.PasswordInput(render_value=False))
    new_password = forms.RegexField(
        label=_("New password"),
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=_("Confirm new password"),
        widget=forms.PasswordInput(render_value=False))
    no_autocomplete = True

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(PasswordForm, self).clean()
        if 'new_password' in data:
            if data['new_password'] != data.get('confirm_password', None):
                raise ValidationError(_('Passwords do not match.'))
        return data

    # We have to protect the entire "data" dict because it contains the
    # oldpassword and newpassword strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        user_is_editable = api.keystone.keystone_can_edit_user()

        if user_is_editable:
            try:
                api.keystone.user_update_own_password(request,
                                                      data['current_password'],
                                                      data['new_password'])
                response = http.HttpResponseRedirect(settings.LOGOUT_URL)
                msg = _("Password changed. Please log in again to continue.")
                utils.add_logout_reason(request, response, msg)
                api.nova.systemlogs_create(request, request.user.username,
                                           record_action.CHANGEPASSWORD)
                return response
            except Exception:
                msg = _('Unable to change password.')
                exceptions.handle(request, msg)
                api.nova.systemlogs_create(request,
                                           request.user.username,
                                           record_action.CHANGEPASSWORD,
                                           result=False,
                                           detail=msg)
                return False
        else:
            messages.error(request, _('Changing password is not supported.'))
            api.nova.systemlogs_create(request,
                                       request.user.username,
                                       record_action.CHANGEPASSWORD,
                                       result=False,
                                       detail=msg)
            return False
class ResetPasswordAction(workflows.Action):
    instance_id = forms.CharField(label=_("Instance ID"),
                                  widget=forms.HiddenInput(),
                                  required=False)

    is_allow_inject_passwd = forms.CharField(widget=forms.HiddenInput(), required=False)

    image_name = forms.CharField(widget=forms.HiddenInput(), required=False)

    validate_code = forms.CharField(max_length=64,
                                    label=_("Please Input Validate Code"),
                                    required=False)

    username = forms.CharField(max_length=64, label=_("User Name"), required=False)

    is_sync_set_root = forms.BooleanField(label=_("Sync set root/Administrator password"), initial=True, required=False)

    password = forms.RegexField(
        label=_("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 Password"),
        required=False,
        widget=forms.PasswordInput(render_value=False))

    is_reboot = forms.BooleanField(label=_("Reboot after reset password successfully"), initial=True, required=False) 

    def __init__(self, request, context, *args, **kwargs):
        super(ResetPasswordAction, self).__init__(request, context, *args, **kwargs)

        self.fields["username"].initial = 'syscloud'

        is_allow_inject_passwd = context.get('is_allow_inject_passwd')
        if not is_allow_inject_passwd:
            del self.fields['username']
            del self.fields['is_sync_set_root']
            del self.fields['password']
            del self.fields['confirm_password']
            del self.fields['is_reboot']

    class Meta(object):
        name = _("Reset Password")
        slug = 'reset_password'
        help_text_template = ("instances/instances/"
                              "_reset_password.html")

    def clean(self):
        cleaned_data = super(ResetPasswordAction, self).clean()
        return cleaned_data

    '''
class CreateUserAction(workflows.Action):
    username = forms.CharField(max_length=80, label=_("User Name"),
                               validators=[RegexValidator(r'^[\w]*$',
                                                          message='Username must be alphanumeric without spaces',
                                                          code='Invalid Username')]
                               )
    
    roles = forms.MultipleChoiceField(label=_("Roles"),
                                       required=False,
                                       initial=["default"],
                                       widget=forms.CheckboxSelectMultiple(),
                                       help_text=_("Create user with these "
                                                   "roles."))
    password = forms.RegexField(
        label=_("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 Password"),
        required=False,
        widget=forms.PasswordInput(render_value=False))
    email = forms.EmailField(label=_("Email ID"),
             required=True)


    def populate_roles_choices(self, request, context):
        roles = []
        success = []
        try:
            if request.user.roles:
                for role in  request.user.roles:
                    if (role.name == "Tenant Admin") & (role.roletype == "Tenant Admin"):
                        success.append("Tenant Admin")
                    else:
                        success.append("Member")
                if "Tenant Admin" in success:
                    rolelist = roledetail.objects(tenantid=request.user.tenantid.id)
                    roles = [(role.id, role.name) for role in rolelist]
                else:   
                    rolelist = roledetail.objects(tenantid=request.user.tenantid.id)
                    for role in rolelist:
                        if (role.name == "Tenant Admin") & (role.roletype == "Tenant Admin"):
                            pass
                        else:
                            roles.append((role.id, role.name))
            else:
                roles = []
                                  
        except Exception, e:
            messages.error(request,_(e.message))
            LOG.error(e.message)
            roles = []
        return roles
Beispiel #10
0
    def _build_parameter_fields(self, template_validate):
        self.fields['password'] = forms.CharField(
            label=_('Password for user "%s"') % self.request.user.username,
            help_text=_('This is required for operations to be performed '
                        'throughout the lifecycle of the stack'),
            widget=forms.PasswordInput())

        self.help_text = template_validate['Description']

        params = template_validate.get('Parameters', {})
        if template_validate.get('ParameterGroups'):
            params_in_order = []
            for group in template_validate['ParameterGroups']:
                for param in group.get('parameters', []):
                    if param in params:
                        params_in_order.append((param, params[param]))
        else:
            # no parameter groups, so no way to determine order
            params_in_order = params.items()
        for param_key, param in params_in_order:
            field_key = self.param_prefix + param_key
            field_args = {
                'initial': param.get('Default', None),
                'label': param.get('Label', param_key),
                'help_text': param.get('Description', ''),
                'required': param.get('Default', None) is None
            }

            param_type = param.get('Type', None)
            hidden = strutils.bool_from_string(param.get('NoEcho', 'false'))

            if 'AllowedValues' in param:
                choices = map(lambda x: (x, x), param['AllowedValues'])
                field_args['choices'] = choices
                field = forms.ChoiceField(**field_args)

            elif param_type in ('CommaDelimitedList', 'String'):
                if 'MinLength' in param:
                    field_args['min_length'] = int(param['MinLength'])
                    field_args['required'] = param.get('MinLength', 0) > 0
                if 'MaxLength' in param:
                    field_args['max_length'] = int(param['MaxLength'])
                if hidden:
                    field_args['widget'] = forms.PasswordInput()
                field = forms.CharField(**field_args)

            elif param_type == 'Number':
                if 'MinValue' in param:
                    field_args['min_value'] = int(param['MinValue'])
                if 'MaxValue' in param:
                    field_args['max_value'] = int(param['MaxValue'])
                field = forms.IntegerField(**field_args)

            self.fields[field_key] = field
Beispiel #11
0
class CreateUserForm(BaseUserForm):
    name = forms.CharField(label=_("User Name"))
    email = forms.EmailField(label=_("Email"))
    secretkey = forms.CharField(label=_("Secret Key"), 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"),
            required=False,
            widget=forms.PasswordInput(render_value=False))
    tenant_id = 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

    # 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):
        try:
            LOG.info('Creating user with name "%s"' % data['name'])
            new_user = api.keystone.user_create_with_otp(request,
                                                data['name'],
                                                data['email'],
                                                data['secretkey'],
                                                data['password'],
                                                data['tenant_id'],
                                                True)
            messages.success(request,
                             _('User "%s" was successfully created.')
                             % data['name'])
            if data['role_id']:
                try:
                    api.keystone.add_tenant_user_role(request,
                                             data['tenant_id'],
                                             new_user.id,
                                             data['role_id'])
                except:
                    exceptions.handle(request,
                                      _('Unable to add user'
                                        'to primary project.'))
            return new_user
        except:
            exceptions.handle(request, _('Unable to create user.'))
Beispiel #12
0
class PasswordForm(forms.SelfHandlingForm):
    action = reverse_lazy('horizon:settings:multisettings:password')
    description = 'Change your password'
    template = 'settings/multisettings/_collapse_form.html'

    current_password = forms.CharField(
        label=('Current password'),
        widget=forms.PasswordInput(render_value=False))
    new_password = forms.RegexField(
        label=('New password'),
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=('Confirm new password'),
        widget=forms.PasswordInput(render_value=False))
    no_autocomplete = True

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(forms.Form, self).clean()
        if 'new_password' in data:
            if data['new_password'] != data.get('confirm_password', None):
                raise ValidationError(('Passwords do not match.'))
        return data

    # We have to protect the entire 'data' dict because it contains the
    # oldpassword and newpassword strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        user_is_editable = api.keystone.keystone_can_edit_user()

        if user_is_editable:
            try:
                api.keystone.user_update_own_password(request,
                                                      data['current_password'],
                                                      data['new_password'])
                response = http.HttpResponseRedirect(settings.LOGOUT_URL)
                msg = ('Password changed. Please log in again to continue.')
                LOG.info(msg)
                utils.add_logout_reason(request, response, msg)
                response.set_cookie('logout_reason_level',
                                    'success',
                                    max_age=10)
                return response
            except Exception:
                exceptions.handle(request, ('Unable to change password.'))
                return False
        else:
            messages.error(request, ('Changing password is not supported.'))
            return False
class PasswordForm(forms.SelfHandlingForm):
    current_password = forms.CharField(
        label=_("Current password"),
        widget=forms.PasswordInput(render_value=False))
    new_password = forms.RegexField(
        label=_("New password"),
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=_("Confirm new password"),
        widget=forms.PasswordInput(render_value=False))

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(forms.Form, self).clean()
        if 'new_password' in data:
            if data['new_password'] != data.get('confirm_password', None):
                raise ValidationError(_('Passwords do not match.'))
        return data

    # We have to protect the entire "data" dict because it contains the
    # oldpassword and newpassword strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        user_is_editable = api.keystone.keystone_can_edit_user()

        if user_is_editable:
            try:
                api.keystone.user_update_own_password(request,
                                                      data['current_password'],
                                                      data['new_password'])
                #   response = http.HttpResponseRedirect(settings.LOGOUT_URL)
                response = http.HttpResponseRedirect('/horizon/auth/login')

                userid = request.user.id
                print "this is setting userid : '%s'" % userid
                print "this is setting data['new_password'] : '******'" % data[
                    'new_password']
                update_user_password(userid, data['new_password'])
                msg = _("Password changed. Please log in again to continue.")
                utils.add_logout_reason(request, response, msg)
                return response
            except Exception:
                exceptions.handle(request, _('Unable to change password.'))
                return False
        else:
            messages.error(request, _('Changing password is not supported.'))
            return False

        return True
Beispiel #14
0
class RescueInstanceForm(forms.SelfHandlingForm):
    image = forms.ChoiceField(label=_("Select Image"),
                              widget=forms.ThemableSelectWidget(
                                  attrs={'class': 'image-selector'},
                                  data_attrs=('size', 'display-name'),
                                  transform=_image_choice_title))
    password = forms.CharField(label=_("Password"),
                               max_length=255,
                               required=False,
                               widget=forms.PasswordInput(render_value=False))
    failure_url = 'horizon:project:instances:index'

    def __init__(self, request, *args, **kwargs):
        super(RescueInstanceForm, self).__init__(request, *args, **kwargs)
        images = image_utils.get_available_images(request,
                                                  request.user.tenant_id)
        choices = [(image.id, image) for image in images]
        if not choices:
            choices.insert(0, ("", _("No images available")))
        self.fields['image'].choices = choices

    def handle(self, request, data):
        try:
            api.nova.server_rescue(request,
                                   self.initial["instance_id"],
                                   password=data["password"],
                                   image=data["image"])
            messages.success(request, _('Successfully rescued instance'))
            return True
        except Exception:
            redirect = reverse(self.failure_url)
            exceptions.handle(request,
                              _('Unable to rescue instance'),
                              redirect=redirect)
class LoginForm(SelfHandlingForm):

    username = forms.CharField(label=_("Username"),
                               max_length=255,
                               widget=forms.TextInput(
                                   attrs={'placeholder':
                                          _('Username'),
                                          'autofocus': 'autofocus'}))

    password = forms.CharField(label=_("Password"),
                               widget=forms.PasswordInput(render_value=False))
    remember = forms.BooleanField(label=_("Remember Me"),
                                  required=False)

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.helper.layout = Layout(
            'username', 'password', 'remember',
        )

    def handle(self, request, data):

        user = authenticate(**data)
        if user is not None:
            if user.is_active:
                login(request, user)

                messages.success(request, "Login success.")
                return True
        messages.error(request, "Login failed.")
        return False
Beispiel #16
0
class UserUpdateForm(BaseUserForm):
    id = forms.CharField(
        label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    # FIXME: keystone doesn't return the username from a get API call.
    #name = forms.CharField(label=_("Name"))
    email = forms.CharField(label=_("Email"))
    password = forms.CharField(label=_("Password"),
                               widget=forms.PasswordInput(render_value=False),
                               required=False)
    tenant_id = forms.ChoiceField(label=_("Primary Tenant"))

    def handle(self, request, data):
        updated = []
        if data['email']:
            updated.append('email')
            api.user_update_email(request, data['id'], data['email'])
        if data['password']:
            updated.append('password')
            api.user_update_password(request, data['id'], data['password'])
        if data['tenant_id']:
            updated.append('tenant')
            api.user_update_tenant(request, data['id'], data['tenant_id'])
        messages.success(
            request,
            _('Updated %(attrib)s for %(user)s.') % {
                "attrib": ', '.join(updated),
                "user": data['id']
            })
        return shortcuts.redirect('horizon:syspanel:users:index')
Beispiel #17
0
class NodeCreateAction(workflows.Action):
    # node_macs = forms.CharField(label=_("MAC Addresses"),
    #     widget=forms.Textarea(attrs={'rows': 12, 'cols': 20}),
    #     required=False)

    node_name = forms.CharField(label="Name", required=True)
    prov_mac_address = forms.CharField(label=("MAC Address"), required=True)

    # Hardware Specifications
    cpus = forms.CharField(label="CPUs", required=True)
    memory_mb = forms.CharField(label="Memory", required=True)
    local_gb = forms.CharField(label="Local Disk (GB)", required=True)

    # Power Management
    pm_address = forms.CharField(label="Power Management IP", required=False)
    pm_user = forms.CharField(label="Power Management User", required=False)
    pm_password = forms.CharField(
        label="Power Management Password",
        required=False,
        widget=forms.PasswordInput(render_value=False))

    # Access
    terminal_port = forms.CharField(label="Terminal Port", required=False)

    class Meta:
        name = _("Nodes")
Beispiel #18
0
class SettingsForm(forms.SelfHandlingForm):
    neo_host = forms.CharField(label=_('NEO Server'), required=False)
    ufm_host = forms.CharField(label=_('UFM Server'), required=False)
    neo_host_user = forms.CharField(label=_('NEO Username'), required=False)
    n_a_ = forms.CharField(label=_('a'), required=False)
    neo_host_password = forms.CharField(
        label=_('NEO Password'),
        required=False,
        widget=forms.PasswordInput(render_value=False))
    no_autocomplete = False

    def handle(self, request, data):
        response = shortcuts.redirect(request.build_absolute_uri())
        request.session['mellanox_neo_host'] = data['neo_host']
        response.set_cookie('mellanox_neo_host',
                            data['neo_host'],
                            expires=_one_year())

        request.session['mellanox_neo_host_user'] = data['neo_host_user']
        response.set_cookie('mellanox_neo_host_user',
                            data['neo_host_user'],
                            expires=_one_year())

        request.session['mellanox_neo_host_password'] = \
            data['neo_host_password']
        response.set_cookie('mellanox_neo_host_password',
                            data['neo_host_password'],
                            expires=_one_year())

        request.session['mellanox_ufm_host'] = data['ufm_host']
        response.set_cookie('mellanox_ufm_host',
                            data['ufm_host'],
                            expires=_one_year())

        return response
Beispiel #19
0
 def __init__(self, request, *args, **kwargs):
     super(FillUserAccountInfoAction,
           self).__init__(request, *args, **kwargs)
     self.fields["keystone_initial_pwd"].widget = forms.PasswordInput(
         render_value=False)
     self.fields[
         "keystone_initial_pwd"].regex = validators.password_validator()
Beispiel #20
0
class GeneralConfigAction(workflows.Action):
    data_source_name = forms.CharField(label=_("Name"))

    data_source_type = forms.ChoiceField(
        label=_("Data Source Type"),
        choices=[("swift", "Swift"), ("hdfs", "HDFS")],
        widget=forms.Select(attrs={"class": "data_source_type_choice"}))

    data_source_url = forms.CharField(label=_("URL"))

    data_source_credential_user = forms.CharField(label=_("Source username"),
                                                  required=False)

    data_source_credential_pass = forms.CharField(
        widget=forms.PasswordInput(attrs={'autocomplete': 'off'}),
        label=_("Source password"),
        required=False)

    data_source_description = forms.CharField(
        label=_("Description"),
        required=False,
        widget=forms.Textarea(attrs={'rows': 4}))

    def __init__(self, request, *args, **kwargs):
        super(GeneralConfigAction, self).__init__(request, *args, **kwargs)

    class Meta:
        name = _("Create Data Source")
        help_text_template = ("project/data_processing.data_sources/"
                              "_create_data_source_help.html")
Beispiel #21
0
class CreateUserForm(BaseUserForm):
    name = forms.CharField(label=_("Name"))
    email = forms.CharField(label=_("Email"))
    password = forms.CharField(label=_("Password"),
                               widget=forms.PasswordInput(render_value=False),
                               required=False)
    tenant_id = forms.ChoiceField(label=_("Primary Project"))

    def handle(self, request, data):
        try:
            LOG.info('Creating user with name "%s"' % data['name'])
            new_user = api.user_create(request, data['name'], data['email'],
                                       data['password'], data['tenant_id'],
                                       True)
            messages.success(
                request,
                _('User "%s" was successfully created.') % data['name'])
            try:
                default_role = api.keystone.get_default_role(request)
                if default_role:
                    api.add_tenant_user_role(request, data['tenant_id'],
                                             new_user.id, default_role.id)
            except:
                exceptions.handle(request,
                                  _('Unable to add user to primary tenant.'))
            return shortcuts.redirect('horizon:syspanel:users:index')
        except:
            exceptions.handle(request, _('Unable to create user.'))
            return shortcuts.redirect('horizon:syspanel:users:index')
Beispiel #22
0
class Create(forms.SelfHandlingForm):
    name = forms.CharField(max_length="255", label=_("Name"))
    dns_ip = forms.CharField(max_length="15", label=_("DNS IP"))
    ou = forms.CharField(
        max_length="255",
        label=_("Organizational Unit"),
        required=False)
    server = forms.CharField(max_length="255", label=_("Server"))
    domain = forms.CharField(max_length="255", label=_("Domain"))
    user = forms.CharField(max_length="255", label=_("User"), required=False)
    password = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput(render_value=False),
        required=False)
    confirm_password = forms.CharField(
        label=_("Confirm Password"),
        widget=forms.PasswordInput(render_value=False),
        required=False)
    type = forms.ChoiceField(choices=(("", ""),
                                      ("active_directory", "Active Directory"),
                                      ("ldap", "LDAP"),
                                      ("kerberos", "Kerberos")),
                             label=_("Type"))
    description = forms.CharField(widget=forms.Textarea,
                                  label=_("Description"), required=False)

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(forms.Form, self).clean()
        if 'password' in data:
            if data['password'] != data.get('confirm_password', None):
                raise ValidationError(_('Passwords do not match.'))
        return data

    @sensitive_variables('data')
    def handle(self, request, data):
        try:
            data.pop('confirm_password')
            security_service = manila.security_service_create(
                request, **data)
            messages.success(request, _('Successfully created security '
                                        'service: %s') % data['name'])
            return security_service
        except Exception:
            exceptions.handle(request,
                              _('Unable to create security service.'))
            return False
Beispiel #23
0
class PasswordMixin(forms.SelfHandlingForm):
    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))
    no_autocomplete = True

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(forms.Form, self).clean()
        if 'password' in data and 'confirm_password' in data:
            if data['password'] != data['confirm_password']:
                raise ValidationError(_('Passwords do not match.'))
        return data
Beispiel #24
0
class PasswordForm(forms.SelfHandlingForm):
    new_password = forms.RegexField(
        label=_("New password"),
        max_length=PWD_LEN,
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=_("Confirm new password"),
        max_length=PWD_LEN,
        widget=forms.PasswordInput(render_value=False))

    def clean(self):
        data = super(forms.Form, self).clean()
        if 'new_password' in data:
            if data['new_password'] != data.get('confirm_password', None):
                raise ValidationError(_('Passwords do not match.'))
        return data

    @sensitive_variables('data')
    def handle(self, request, data):

        user_is_editable = api.keystone.keystone_can_edit_user()
        if not user_is_editable:
            messages.error(request, _('Activating password is not supported.'))
            return False

        try:
            #api.keystone.user_update_own_password(request, None, data['new_password'])
            api.keystone.user_update_password(request, request.user.id,
                                              data['new_password'], False)

            if get_manager(request):
                return http.HttpResponseRedirect(reverse_lazy('login'))
            else:
                response = http.HttpResponseRedirect(reverse_lazy('logout'))
                msg = _("Password changed. Please log in again to continue.")
                utils.add_logout_reason(request, response, msg)
                return response

        except Exception:
            exceptions.handle(request, _('Unable to activate password.'))

        return False
Beispiel #25
0
class EmailForm(forms.SelfHandlingForm):
    action = reverse_lazy('horizon:settings:multisettings:useremail')
    description = 'Change your email'
    template = 'settings/multisettings/_collapse_form.html'

    email = forms.EmailField(label=("Email"), required=True)
    password = forms.CharField(label=("Current password"),
                               widget=forms.PasswordInput(render_value=False),
                               required=True)

    # We have to protect the entire "data" dict because it contains the
    # password string.
    @sensitive_variables('data')
    def handle(self, request, data):
        # the user's password to change the email, only to update the password
        try:
            # check if the password is correct
            password = data['password']
            domain = getattr(settings, 'OPENSTACK_KEYSTONE_DEFAULT_DOMAIN',
                             'Default')
            default_region = (settings.OPENSTACK_KEYSTONE_URL,
                              "Default Region")
            region = getattr(settings, 'AVAILABLE_REGIONS',
                             [default_region])[0][0]

            name = request.user.name
            result = django_auth.authenticate(request=request,
                                              username=name,
                                              password=password,
                                              user_domain_name=domain,
                                              auth_url=region)

            # send a verification email
            email = data['email']
            signer = Signer()
            verification_key = signer.sign(name + email).split(':')[1]

            email_utils.send_verification_email(request.user, verification_key,
                                                email)

            # redirect user to settings home
            response = shortcuts.redirect(
                'horizon:settings:multisettings:index')
            msg = ("An email has been sent to verify your account."
                   " Follow the provided link to change your email.")
            messages.success(request, msg)
            return response

        except auth_exceptions.KeystoneAuthException as exc:
            messages.error(request, ('Invalid password'))
            LOG.error(exc)
            return False
        except Exception as e:
            exceptions.handle(request, ('Unable to change email.'))
            LOG.error(e)
            return False
Beispiel #26
0
class SyncControlCenterForm(forms.SelfHandlingForm):
    tenantname = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    virtualplatformtype = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    domain_name = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    hostname = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    virtualplatformIP = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    datacentersandclusters = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    name = forms.CharField(label=_("hiddeninfo"),widget=forms.HiddenInput())
    
    network_id = forms.ChoiceField(label=_("Network Name"))
    username = forms.CharField(label=_("Cloud Platform Account"),
                               widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    passwd = forms.CharField(label=_("Cloud Platform Password"),
                             widget=forms.PasswordInput(attrs={'autocomplete': 'off'}))
    virtualplatformusername = forms.CharField(label=_("Heterogeneous Platform Account"),
                               widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    virtualplatformpassword = forms.CharField(label=_("Heterogeneous Platform Password"),
                                              widget=forms.PasswordInput(attrs={'autocomplete': 'off'}))
    
    def __init__(self, request, *args, **kwargs):
        super(SyncControlCenterForm, self).__init__(request, *args, **kwargs)
        networks = []
        try:
            _networks = api.neutron.network_list(self.request)
            networks = [(n.id,n.name) for n in _networks]
        except Exception:
            networks = []
            msg = _('Network list can not be retrieved.')
            exceptions.handle(request, msg)
        self.fields['network_id'].choices = networks

    def handle(self, request, data):
        try:
            requestapi = RequestApi()
            data['datacentersandclusters'] = json.loads(data['datacentersandclusters'])
            res = requestapi.postRequestInfo('api/heterogeneous/platforms/sync',data)
            if res.get('action') == 'success':
                messages.success(request,_('Success to synchronize the control center.'))
                return True
        except Exception as e:
            exceptions.handle(request,
                              _('Unable to synchronize the control center.'))
        return False
Beispiel #27
0
    def __init__(self, request, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(request, *args, **kwargs)

        if getattr(settings, 'ENFORCE_PASSWORD_CHECK', False):
            self.fields["admin_password"] = forms.CharField(
                label=_("Admin Password"),
                widget=forms.PasswordInput(render_value=False))
            # Reorder form fields from multiple inheritance
            self.fields.keyOrder = ["id", "name", "admin_password",
                                    "password", "confirm_password"]
class CreateCloudAction(workflows.Action):

    cloudtype = forms.ChoiceField(label=_("Platform"),
                                  required=True,
                                  widget=fields.SelectWidget(
                                      data_attrs=(
                                          'name',
                                          'type',
                                      ),
                                      transform=lambda x: ("%s " % (x.name))))

    cloudlist = forms.ChoiceField(label=_("Cloud Type"),
                                  required=True,
                                  widget=fields.SelectWidget(
                                      data_attrs=(
                                          'name',
                                          'type',
                                      ),
                                      transform=lambda x: ("%s " % (x.type))))
    cloudname = forms.CharField(label=_("Cloud Name"), max_length=80)

    cloud_id = forms.CharField(required=False, widget=forms.HiddenInput())
    publickey = forms.CharField(label=_("Public Key"), max_length=None)
    secretkey = forms.RegexField(
        label=_("Secret Key"),
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    endpoint = forms.CharField(max_length=80,
                               label=_("Endpoint(IP with HTTP)"))

    class Meta:
        name = _("ADD Cloud")

    def __init__(self, *args, **kwargs):
        super(CreateCloudAction, self).__init__(*args, **kwargs)
        try:
            region_list = get_regions_wo_connection()
            cloud_id = args[-1]["cloud_id"]
            cloud_obj = clouds.objects(id=cloud_id).first()
            self.fields['publickey'].label = _(cloud_obj.credential_fields[0])
            self.fields["secretkey"].label = _(cloud_obj.credential_fields[1])
            if cloud_obj.name == "Amazon":
                self.fields["endpoint"] = forms.ChoiceField(
                    label=_("Default Region"),
                    choices=region_list,
                    help_text=_("Select default region"))
                self.fields["endpoint"].label = _(
                    cloud_obj.credential_fields[2])
            else:
                self.fields["endpoint"].label = _(
                    cloud_obj.credential_fields[2])
        except Exception, e:
            messages.error(self.request, _(e.message))
            LOG.error(e.message)
Beispiel #29
0
class CreateUserForm(BaseUserForm):
    username = 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(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=_("Confirm Password"),
        required=False,
        widget=forms.PasswordInput(render_value=False))
    company = forms.CharField(label=_("Company Name"), required=False)
    real_name = forms.CharField(label=_("Real Name"), required=False)
    ID_Card = forms.CharField(label=_("ID Card"), required=False)
    mobile = forms.CharField(label=_("Mobile"), required=False)
    qq = forms.CharField(label=_("QQ"), required=False)

    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)

    @sensitive_variables('data')
    def handle(self, request, data):
        try:
            LOG.info('Creating user with username "%s"' % data['username'])
            new_user = bill_users(
                username=data['username'],
                email=data['email'],
                password=data['password'],
                company=data['company'],
                real_name=data['real_name'],
                ID_Card=data['ID_Card'],
                mobile=data['mobile'],
                qq=data['qq'],
            )
            messages.success(
                request,
                _('User "%s" was successfully created.') % data['username'])
            new_user.save()
            return new_user
        except:
            exceptions.handle(request, _('Unable to create user.'))
Beispiel #30
0
class UpdateCertificate(forms.SelfHandlingForm):
    id = forms.CharField(
        label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    name = forms.CharField(label=_("Name"),
                           min_length=1,
                           max_length=255,
                           required=True)
    description = forms.CharField(label=_("Description"),
                                  min_length=1,
                                  max_length=255,
                                  required=True)
    cert_data = forms.CharField(label=_("Data"),
                                min_length=1,
                                max_length=1024,
                                required=True)
    key_data = forms.CharField(label=_("Key Data"),
                               min_length=1,
                               max_length=8000,
                               widget=forms.Textarea(attrs={
                                   'cols': 80,
                                   'rows': 15
                               }),
                               required=True)
    password = forms.CharField(label=_("Password"),
                               min_length=1,
                               max_length=1024,
                               widget=forms.PasswordInput(render_value=False),
                               required=False)
    intermediate_data = forms.CharField(
        label=_("Intermediate Certificate Data"),
        min_length=1,
        max_length=8000,
        widget=forms.Textarea(attrs={
            'cols': 80,
            'rows': 15
        }),
        required=False)

    failure_url = 'horizon:project:a10ssl:index'

    def handle(self, request, context):
        LOG.debug("UpdateCertificate:handle(): context" % context)
        try:
            certificate = api.certificate_update(request, **context)
            msg = _('Certificate {0} was successfully updated.').format(
                context['id'])
            LOG.debug(msg)
            messages.success(request, msg)
            return certificate
        except Exception:
            msg = _('Failed to update certificate %s') % context['id']
            LOG.exception(msg)
            redirect = reverse(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)