Esempio n. 1
0
 private Func <string, FormItem> getRadioGroup(
     string label, RadioButtonSetup setup, bool noSelection = false, bool singleButton = false, FormAction selectionChangedAction = null,
     PageModificationValue <bool> pageModificationValue     = null) =>
 id => {
     var group = new RadioButtonGroup(noSelection, disableSingleButtonDetection: singleButton, selectionChangedAction: selectionChangedAction);
     return(new StackList(
                group
                .CreateRadioButton(
                    !noSelection,
                    "First".ToComponents(),
                    setup: setup,
                    validationMethod: (postBackValue, validator) => AddStatusMessage(
                        StatusMessageType.Info,
                        "{0}-1: {1}".FormatWith(id, postBackValue.Value.ToString())))
                .ToFormItem()
                .ToListItem()
                .ToCollection()
                .Concat(
                    singleButton
                                                         ? Enumerable.Empty <ComponentListItem>()
                                                         : group.CreateFlowRadioButton(
                        false,
                        "Second".ToComponents(),
                        setup: FlowRadioButtonSetup.Create(
                            nestedContentGetter: () => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit.".ToComponents()),
                        validationMethod: (postBackValue, validator) => AddStatusMessage(
                            StatusMessageType.Info,
                            "{0}-2: {1}".FormatWith(id, postBackValue.Value.ToString())))
                    .ToFormItem()
                    .ToListItem()
                    .ToCollection()
                    .Append(
                        group.CreateRadioButton(
                            false,
                            "Third".ToComponents(),
                            setup: RadioButtonSetup.Create(),
                            validationMethod: (postBackValue, validator) => AddStatusMessage(
                                StatusMessageType.Info,
                                "{0}-3: {1}".FormatWith(id, postBackValue.Value.ToString())))
                        .ToFormItem()
                        .ToListItem()))).ToFormItem(
                label: "{0}. {1}".FormatWith(id, label)
                .ToComponents()
                .Concat(
                    pageModificationValue != null
                                                         ? new LineBreak().ToCollection <PhrasingComponent>()
                    .Append(
                        new SideComments(
                            "First button value: ".ToComponents()
                            .Concat(
                                pageModificationValue.ToGenericPhrasingContainer(
                                    v => v.ToString(),
                                    valueExpression => "{0} ? 'True' : 'False'".FormatWith(valueExpression)))
                            .Materialize()))
                                                         : Enumerable.Empty <PhrasingComponent>())
                .Materialize()));
 };
        /// <summary>
        /// Creates a user editor.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="modificationMethod"></param>
        /// <param name="availableRoles">Pass a restricted list of <see cref="Role"/>s the user may select. Otherwise, Roles available in the System Provider are
        /// used.</param>
        /// <param name="userInserterOrUpdater">A function that takes the validated data, inserts or updates the user, and returns the user’s ID. Pass null to have
        /// the user-management provider handle the insert or update.</param>
        public UserEditor(
            int?userId, out Action modificationMethod, List <Role> availableRoles = null, UserInserterOrUpdaterMethod userInserterOrUpdater = null)
        {
            availableRoles = (availableRoles?.OrderBy(r => r.Name) ?? UserManagementStatics.SystemProvider.GetRoles()).ToList();

            var user = userId.HasValue ? UserManagementStatics.GetUser(userId.Value, true) : null;

            var          email           = new DataValue <string>();
            var          roleId          = new DataValue <int>();
            Action <int> passwordUpdater = null;

            var b = FormItemList.CreateStack();

            b.AddItems(
                email.ToEmailAddressControl(false, value: user != null ? user.Email : "")
                .ToFormItem(label: "Email address".ToComponents())
                .Append(
                    roleId.ToDropDown(
                        DropDownSetup.Create(from i in availableRoles select SelectListItem.Create((int?)i.RoleId, i.Name)),
                        value: new SpecifiedValue <int?>(user?.Role.RoleId))
                    .ToFormItem(label: "Role".ToComponents()))
                .Materialize());

            if (UserManagementStatics.LocalIdentityProviderEnabled)
            {
                var group = new RadioButtonGroup(false);
                var providePasswordSelected = new DataValue <bool>();
                b.AddFormItems(
                    new StackList(
                        group.CreateRadioButton(true, label: userId.HasValue ? "Keep the current password".ToComponents() : "Do not create a password".ToComponents())
                        .ToFormItem()
                        .ToListItem()
                        .Append(
                            providePasswordSelected.ToFlowRadioButton(
                                group,
                                "Provide a {0}".FormatWith(userId.HasValue ? "new password" : "password").ToComponents(),
                                setup: FlowRadioButtonSetup.Create(
                                    nestedContentGetter: () => {
                    return(FormState.ExecuteWithValidationPredicate(
                               () => providePasswordSelected.Value,
                               () => FormItemList.CreateStack(
                                   generalSetup: new FormItemListSetup(classes: new ElementClass("newPassword")),
                                   items: AuthenticationStatics.GetPasswordModificationFormItems(out passwordUpdater))
                               .ToCollection()));
                }),
                                value: false)
                            .ToFormItem()
                            .ToListItem())).ToFormItem(label: "Password".ToComponents()));
            }

            children = new Section("Security Information", b.ToCollection()).ToCollection();

            modificationMethod = () => {
                if (userInserterOrUpdater != null)
                {
                    userId = userInserterOrUpdater(email, roleId);
                }
                else
                {
                    userId = UserManagementStatics.SystemProvider.InsertOrUpdateUser(userId, email.Value, roleId.Value, user?.LastRequestTime);
                }
                passwordUpdater?.Invoke(userId.Value);
            };
        }
        /// <summary>
        /// Call this during LoadData.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="availableRoles">Pass a restricted list of <see cref="Role"/>s the user may select. Otherwise, Roles available
        /// in the System Provider are used.</param>
        public void LoadData(int?userId, List <Role> availableRoles = null)
        {
            availableRoles = (availableRoles?.OrderBy(r => r.Name) ?? UserManagementStatics.SystemProvider.GetRoles()).ToList();

            var user    = userId.HasValue ? UserManagementStatics.GetUser(userId.Value, true) : null;
            var facUser = includePasswordControls() && user != null?FormsAuthStatics.GetUser(user.UserId, true) : null;

            var b = FormItemList.CreateStack();

            b.AddFormItems(Email.ToEmailAddressControl(false, value: user != null ? user.Email : "").ToFormItem(label: "Email address".ToComponents()));

            if (includePasswordControls())
            {
                var group = new RadioButtonGroup(false);

                var keepPassword = group.CreateRadioButton(
                    true,
                    label: userId.HasValue ? "Keep the current password".ToComponents() : "Do not create a password".ToComponents(),
                    validationMethod: (postBackValue, validator) => {
                    if (!postBackValue.Value)
                    {
                        return;
                    }
                    if (user != null)
                    {
                        Salt.Value               = facUser.Salt;
                        SaltedPassword.Value     = facUser.SaltedPassword;
                        MustChangePassword.Value = facUser.MustChangePassword;
                    }
                    else
                    {
                        genPassword(false);
                    }
                })
                                   .ToFormItem();

                var generatePassword = group.CreateRadioButton(
                    false,
                    label: "Generate a {0} password and email it to the user".FormatWith(userId.HasValue ? "new, random" : "random").ToComponents(),
                    validationMethod: (postBackValue, validator) => {
                    if (postBackValue.Value)
                    {
                        genPassword(true);
                    }
                })
                                       .ToFormItem();

                var providePasswordSelected = new DataValue <bool>();
                var providePassword         = group.CreateFlowRadioButton(
                    false,
                    label: "Provide a {0}".FormatWith(userId.HasValue ? "new password" : "password").ToComponents(),
                    setup: FlowRadioButtonSetup.Create(
                        nestedContentGetter: () => {
                    return(FormState.ExecuteWithValidationPredicate(
                               () => providePasswordSelected.Value,
                               () => {
                        var password = new DataValue <string>();
                        var list = FormItemList.CreateStack(
                            generalSetup: new FormItemListSetup(classes: new ElementClass("newPassword")),
                            items: password.GetPasswordModificationFormItems());

                        new EwfValidation(
                            validator => {
                            var p = new Password(password.Value);
                            Salt.Value = p.Salt;
                            SaltedPassword.Value = p.ComputeSaltedHash();
                            MustChangePassword.Value = false;
                        });

                        return list.ToCollection();
                    }));
                }),
                    validationMethod: (postBackValue, validator) => providePasswordSelected.Value = postBackValue.Value)
                                              .ToFormItem();

                b.AddFormItems(
                    new StackList(keepPassword.ToListItem().ToCollection().Append(generatePassword.ToListItem()).Append(providePassword.ToListItem())).ToFormItem(
                        label: "Password".ToComponents()));
            }

            b.AddFormItems(
                RoleId.ToDropDown(
                    DropDownSetup.Create(from i in availableRoles select SelectListItem.Create(i.RoleId as int?, i.Name)),
                    value: new SpecifiedValue <int?>(user?.Role.RoleId))
                .ToFormItem(label: "Role".ToComponents()));

            this.AddControlsReturnThis(new Section("Security Information", b.ToCollection()).ToCollection().GetControls());
        }