Пример #1
0
        public async Task SetUserStatusAsync(int userId, UserStatusEnum userStatus)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError($"Unknown user (user id {userId})");
                }
                if (user.UserStatus != userStatus)
                {
                    user.UserStatus = userStatus;
                    if (userStatus == UserStatusEnum.Approved)
                    {
                        user.LoginFailures = 0;
                    }
                    UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

                    if (status != UpdateStatusEnum.OK)
                    {
                        throw new InternalError($"Unexpected status {status} updating user account in {nameof(SetUserStatusAsync)}");
                    }
                }
            }
        }
Пример #2
0
        public async Task AddEnabledTwoStepAuthenticationAsync(int userId, string auth)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError($"Unexpected error in {nameof(AddEnabledTwoStepAuthenticationAsync)} - no user found");
                }
                TwoStepDefinition authDef = new DataProvider.TwoStepDefinition {
                    Name = auth
                };
                if (!user.EnabledTwoStepAuthentications.Contains(authDef, new TwoStepDefinitionComparer()))
                {
                    user.EnabledTwoStepAuthentications.Add(authDef);
                    UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

                    if (status != UpdateStatusEnum.OK)
                    {
                        throw new InternalError($"Unexpected status {status} updating user account in {nameof(AddEnabledTwoStepAuthenticationAsync)}");
                    }
                    Manager.Need2FAState = null;//reevaluate now that user has enabled a two-step authentication
                }
            }
        }
Пример #3
0
        public async Task AddTwoStepLoginFailureAsync()
        {
            int userId = Manager.SessionSettings.SiteSettings.GetValue <int>(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);

            if (userId == 0)
            {
                throw new InternalError("No user id available in AddTwoStepLoginFailure");
            }
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError("Unexpected error in AddTwoStepLoginFailure - no user found");
                }
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                user.LoginFailures = user.LoginFailures + 1;
                if (config.MaxLoginFailures != 0 && user.LoginFailures >= config.MaxLoginFailures)
                {
                    if (user.UserStatus != UserStatusEnum.Suspended)
                    {
                        user.UserStatus = UserStatusEnum.Suspended;
                    }
                }
                UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

                if (status != UpdateStatusEnum.OK)
                {
                    throw new InternalError("Unexpected status {0} updating user account in AddTwoStepLoginFailure", status);
                }
            }
        }
Пример #4
0
        public async Task <List <SelectionItem <string> > > GetUserRolesAsync(int userId)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                List <SelectionItem <string> > list = new List <SelectionItem <string> >();
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user != null)
                {
                    using (RoleDefinitionDataProvider roleDP = new RoleDefinitionDataProvider()) {
                        List <RoleDefinition> allRoles = roleDP.GetAllRoles();
                        foreach (Role r in user.RolesList)
                        {
                            RoleDefinition roleDef = (from a in allRoles where a.RoleId == r.RoleId select a).FirstOrDefault();
                            if (roleDef != null)
                            {
                                list.Add(new SelectionItem <string> {
                                    Text = roleDef.Name, Tooltip = roleDef.Description, Value = roleDef.Id
                                });
                            }
                        }
                    }
                }
                return(list);
            }
        }
Пример #5
0
        public async Task RemoveRoleFromUserAsync(int userId, string roleName)
        {
            int roleId;

            // get the role id for roleName
            using (RoleDefinitionDataProvider roleDP = new RoleDefinitionDataProvider()) {
                RoleDefinition role = await roleDP.GetItemAsync(roleName);

                if (role == null)
                {
                    throw new InternalError("Unexpected error in AddRoleToUser - expected role {0} not found", roleName);
                }
                roleId = role.RoleId;
            }
            // remove the role from the user
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user != null)
                {
                    Role role = (from Role r in user.RolesList where r.RoleId == roleId select r).FirstOrDefault();
                    if (role != null)
                    {
                        user.RolesList.Remove(role);
                        UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

                        if (status != UpdateStatusEnum.OK)
                        {
                            throw new InternalError("Unexpected status {0} updating user account in RemoveRoleFromUser", status);
                        }
                    }
                }
            }
        }
Пример #6
0
        public async Task <ActionResult> RecoveryCodes_Partial(EditModel model)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(Manager.UserId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", Manager.UserId);
                }

                EditModel.ModelProgressEnum progress = (EditModel.ModelProgressEnum)Manager.SessionSettings.SiteSettings.GetValue <int>(IDENTITY_RECOVERY_PROGRESS, (int)EditModel.ModelProgressEnum.New);

                model.ModelProgress = progress;
                model.UpdateData(user);

                if (!ModelState.IsValid)
                {
                    return(PartialView(model));
                }

                string msg = null;
                switch (progress)
                {
                case EditModel.ModelProgressEnum.New:
                    progress = EditModel.ModelProgressEnum.ShowLogin;
                    break;

                case EditModel.ModelProgressEnum.ShowLogin:
#if MVC6
                    if (!await Managers.GetUserManager().CheckPasswordAsync(user, model.Password))
#else
                    if (await Managers.GetUserManager().FindAsync(user.UserName, model.Password) == null)
#endif
                    { ModelState.AddModelError(nameof(model.Password), this.__ResStr("badPassword", "The password is invalid")); }

                    if (!ModelState.IsValid)
                    {
                        return(PartialView(model));
                    }

                    progress = EditModel.ModelProgressEnum.ShowCodes;
                    break;

                case EditModel.ModelProgressEnum.ShowCodes:
                    await GenerateRecoveryCodeAsync(userDP, user);

                    msg = this.__ResStr("newCode", "A new recovery code has been generated");
                    break;
                }
                Manager.SessionSettings.SiteSettings.SetValue <int>(IDENTITY_RECOVERY_PROGRESS, (int)progress);
                Manager.SessionSettings.SiteSettings.Save();

                model.ModelProgress = progress;
                model.UpdateData(user);

                return(FormProcessed(model, popupText: msg, ForceApply: true));
            }
        }
Пример #7
0
        public async Task <ActionResult> SelectTwoStepSetup()
        {
            EditModel model = new EditModel();

            Manager.NeedUser();
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(Manager.UserId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", Manager.UserId);
                }
                using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                    string ext = await logInfoDP.GetExternalLoginProviderAsync(Manager.UserId);

                    if (ext != null)
                    {
                        return(View("ShowMessage", this.__ResStr("extUser", "Your account uses a {0} account - Two-step authentication must be set up using your {0} account.", ext), UseAreaViewName: false));
                    }
                }
                TwoStepAuth         twoStep = new TwoStepAuth();
                List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

                List <string> procs = (from p in list select p.Name).ToList();
                List <string> enabledTwoStepAuths = (from e in user.EnabledTwoStepAuthentications select e.Name).ToList();
                foreach (string proc in procs)
                {
                    ITwoStepAuth auth = await twoStep.GetTwoStepAuthProcessorByNameAsync(proc);

                    if (auth != null)
                    {
                        ModuleAction action = await auth.GetSetupActionAsync();

                        if (action != null)
                        {
                            string status;
                            if (enabledTwoStepAuths.Contains(auth.Name))
                            {
                                status = this.__ResStr("enabled", "(Enabled)");
                            }
                            else
                            {
                                status = this.__ResStr("notEnabled", "(Not Enabled)");
                            }
                            model.AuthMethods.Add(new Controllers.SelectTwoStepSetupModuleController.EditModel.AuthMethod {
                                Action      = action,
                                Status      = status,
                                Description = auth.GetDescription()
                            });
                        }
                    }
                }
                model.AuthMethods = (from a in model.AuthMethods orderby a.Action.LinkText select a).ToList();
            }
            return(View(model));
        }
Пример #8
0
 public async Task <UserDefinition> FindByIdAsync(string userId, CancellationToken cancellationToken)
 {
     using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider(this.CurrentSiteIdentity)) {
         UserDefinition user = null;
         try {
             user = await dataProvider.GetItemByUserIdAsync(Convert.ToInt32(userId));
         } catch (Exception) { }
         return(user);
     }
 }
Пример #9
0
        public async Task <DateTime?> GetUserLastLoginDateAsync(int userId)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError($"Unknown user (user id {userId})");
                }
                return(user.LastLoginDate);
            }
        }
Пример #10
0
        public async Task <UserStatusEnum> GetUserStatusAsync(int userId)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError($"Unknown user (user id {userId})");
                }
                return(user.UserStatus);
            }
        }
Пример #11
0
        public async Task <string> GetUserEmailAsync(int userId)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    return(null);
                }
                return(user.Email);
            }
        }
Пример #12
0
        public async Task <bool> VerifyTwoStepAuthenticationRecoveryCodeAsync(int userId, string code)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError($"Unexpected error in {nameof(VerifyTwoStepAuthenticationRecoveryCodeAsync)} - no user found");
                }
                return(user.RecoveryCode == code);
            }
        }
Пример #13
0
        public async Task <string> GetUserPasswordAsync(int userId)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError($"Unknown user (user id {userId})");
                }
                return(user.PasswordPlainText);
            }
        }
Пример #14
0
        public async Task <bool> RemoveUserAsync(int userId)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    return(false);
                }
                return(await userDP.RemoveItemAsync(user.UserName));
            }
        }
Пример #15
0
        public async Task <bool> HasEnabledTwoStepAuthenticationAsync(int userId, string auth)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    return(false);
                }
                TwoStepDefinition authDef = new DataProvider.TwoStepDefinition {
                    Name = auth
                };
                return(user.EnabledTwoStepAuthentications.Contains(authDef, new TwoStepDefinitionComparer()));
            }
        }
Пример #16
0
        public async Task <string> RenderAsync(int model)
        {
            HtmlBuilder hb = new HtmlBuilder();

            YTagBuilder tag = new YTagBuilder("span");

            tag.AddCssClass("yt_yetawf_identity_userid");
            tag.AddCssClass("t_display");
            FieldSetup(tag, FieldType.Anonymous);

            ModuleAction actionDisplay = null;
            ModuleAction actionLoginAs = null;

            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                UserDefinition user = await dataProvider.GetItemByUserIdAsync(model);

                string userName = "";
                if (user == null)
                {
                    if (model != 0)
                    {
                        userName = string.Format("({0})", model);
                    }
                }
                else
                {
                    userName = user.UserName;
                    Modules.UsersDisplayModule modDisp = new Modules.UsersDisplayModule();
                    actionDisplay = modDisp.GetAction_Display(null, userName);
                    Modules.LoginModule modLogin = (Modules.LoginModule) await ModuleDefinition.CreateUniqueModuleAsync(typeof(Modules.LoginModule));

                    actionLoginAs = await modLogin.GetAction_LoginAsAsync(model, userName);
                }
                tag.SetInnerText(userName);
            }

            hb.Append(tag.ToString(YTagRenderMode.Normal));
            if (actionDisplay != null)
            {
                hb.Append(await actionDisplay.RenderAsync(ModuleAction.RenderModeEnum.IconsOnly));
            }
            if (actionLoginAs != null)
            {
                hb.Append(await actionLoginAs.RenderAsync(ModuleAction.RenderModeEnum.IconsOnly));
            }

            return(hb.ToString());
        }
Пример #17
0
        public async Task <string> RenderAsync(SerializableList <User> model)
        {
            HtmlBuilder hb = new HtmlBuilder();

            bool header  = PropData.GetAdditionalAttributeValue("Header", true);
            bool pager   = PropData.GetAdditionalAttributeValue("Pager", true);
            bool useSkin = PropData.GetAdditionalAttributeValue("UseSkinFormatting", true);

            GridModel grid = new GridModel()
            {
                GridDef = GetGridModel(header, pager, useSkin)
            };

            grid.GridDef.DirectDataAsync = async(int skip, int take, List <DataProviderSortInfo> sorts, List <DataProviderFilterInfo> filters) => {
                List <Entry> list = new List <Entry>();
                using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                    if (model != null)
                    {
                        foreach (User user in model)
                        {
                            UserDefinition userDef = await userDP.GetItemByUserIdAsync(user.UserId);

                            string userName;
                            if (userDef == null)
                            {
                                userName = __ResStr("noUser", "({0})", user.UserId);
                            }
                            else
                            {
                                userName = userDef.UserName;
                            }
                            list.Add(new Entry(userName));
                        }
                    }
                }
                return(new DataSourceResult {
                    Data = list.ToList <object>(),
                    Total = list.Count
                });
            };

            hb.Append($@"
<div class='yt_yetawf_identity_listofusernames t_display'>
    {await HtmlHelper.ForDisplayAsAsync(Container, PropertyName, FieldName, grid, nameof(grid.GridDef), grid.GridDef, "Grid", HtmlAttributes: HtmlAttributes)}
</div>");

            return(hb.ToString());
        }
Пример #18
0
        public async Task LoginAsAsync(int userId)
        {
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                UserDefinition user = await dataProvider.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new Error(this.__ResStr("noUser", "User with id {0} doesn't exist", userId));
                }
                if (user.UserStatus != UserStatusEnum.Approved)
                {
                    throw new Error(this.__ResStr("notApproved", "User account for user {0} has not been approved - can't log in", user.UserName));
                }
                await LoginModuleController.UserLoginAsync(user);
            }
        }
Пример #19
0
        public async Task <ActionResult> RecoveryCodes()
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(Manager.UserId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", Manager.UserId);
                }
                // Make sure this user is not using an external account
                using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                    if (await logInfoDP.IsExternalUserAsync(Manager.UserId))
                    {
                        return(new EmptyResult());
                    }
                }
                // Make sure there are any 2fa processors
                TwoStepAuth         twoStep = new TwoStepAuth();
                List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

                if (list.Count == 0)
                {
                    return(new EmptyResult());
                }

                // If there is no recovery code, generate one (upgraded system)
                if (user.RecoveryCode == null)
                {
                    await GenerateRecoveryCodeAsync(userDP, user);
                }

                EditModel.ModelProgressEnum progress = (EditModel.ModelProgressEnum)Manager.SessionSettings.SiteSettings.GetValue <int>(IDENTITY_RECOVERY_PROGRESS, (int)EditModel.ModelProgressEnum.New);

                EditModel model = new EditModel()
                {
                    ModelProgress = progress,
                };
                model.UpdateData(user);

                await Manager.AddOnManager.AddAddOnNamedAsync("YetaWF_ComponentsHTML", "clipboardjs.com.clipboard");// add clipboard support which is needed later (after partial form update)

                return(View(model));
            }
        }
Пример #20
0
        public async Task <bool> GetTwoStepLoginFailuresExceededAsync()
        {
            int userId = Manager.SessionSettings.SiteSettings.GetValue <int>(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);

            if (userId == 0)
            {
                throw new InternalError("No user id available in GetTwoStepLoginFailures");
            }
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError("Unexpected error in GetTwoStepLoginFailures - no user found");
                }
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                return(config.MaxLoginFailures != 0 && user.LoginFailures >= config.MaxLoginFailures);
            }
        }
Пример #21
0
        public async Task RemoveEnabledTwoStepAuthenticationAsync(int userId, string auth)
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError("Unexpected error in RemoveEnabledTwoStepAuthentication - no user found");
                }
                TwoStepDefinition authDef = user.EnabledTwoStepAuthentications.Find(m => m.Name == auth);
                if (authDef != null)
                {
                    user.EnabledTwoStepAuthentications.Remove(authDef);
                    UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

                    if (status != UpdateStatusEnum.OK)
                    {
                        throw new InternalError("Unexpected status {0} updating user account in RemoveEnabledTwoStepAuthentication", status);
                    }
                    Manager.Need2FAState = null;//reevaluate now that user has removed a two-step authentication
                }
            }
        }
Пример #22
0
        public async Task AddRoleToUserAsync(int userId, string roleName)
        {
            int roleId;

            // get the role id for roleName
            using (RoleDefinitionDataProvider roleDP = new RoleDefinitionDataProvider()) {
                RoleDefinition role = await roleDP.GetItemAsync(roleName);

                if (role == null)
                {
                    throw new InternalError("Unexpected error in AddRoleToUser - expected role {0} not found", roleName);
                }
                roleId = role.RoleId;
            }
            // add the role to the user
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError("Unexpected error in AddRoleToUser - no user found");
                }
                Role role = new Role {
                    RoleId = roleId
                };
                if (!user.RolesList.Contains(role, new RoleComparer()))
                {
                    user.RolesList.Add(role);
                    UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

                    if (status != UpdateStatusEnum.OK)
                    {
                        throw new InternalError("Unexpected status {0} updating user account in AddRoleToUser", status);
                    }
                }
            }
        }
Пример #23
0
        public async Task <ActionResult> SelectTwoStepAuth(int userId, string userName, string userEmail)
        {
            EditModel model = new EditModel {
                UserId    = userId,
                UserName  = userName,
                UserEmail = userEmail,
            };

            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", userId);
                }
                TwoStepAuth         twoStep = new TwoStepAuth();
                List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

                List <string> procs = (from p in list select p.Name).ToList();
                List <string> enabledTwoStepAuths = (from e in user.EnabledTwoStepAuthentications select e.Name).ToList();
                procs = procs.Intersect(enabledTwoStepAuths).ToList();
                foreach (string proc in procs)
                {
                    ITwoStepAuth auth = await twoStep.GetTwoStepAuthProcessorByNameAsync(proc);

                    if (auth != null)
                    {
                        model.Actions.New(await auth.GetLoginActionAsync(userId, userName, userEmail));
                    }
                }
                if (model.Actions.Count == 0)
                {
                    throw new InternalError("There are no two-step authentication providers installed");
                }
            }
            return(View(model));
        }
Пример #24
0
        public async Task <string> RenderAsync(int model)
        {
            SerializableList <User> users = GetSiblingProperty <SerializableList <User> >($"{PropertyName}_List");

            if (users != null)
            {
                users = new SerializableList <User>(from u in users select u);// copy list
            }
            else
            {
                users = new SerializableList <User>();
            }
            // add the user id that's current (i.e. the model) if it hasn't already been added
            if ((from u in users where u.UserId == model select u).FirstOrDefault() == null)
            {
                users.Add(new User {
                    UserId = model
                });
            }

            // get list of desired users (ignore users that are invalid, they may have been deleted)
            List <SelectionItem <int> > list = new List <SelectionItem <int> >();

            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                foreach (var u in users)
                {
                    UserDefinition user = await dataProvider.GetItemByUserIdAsync(u.UserId);

                    if (user != null)
                    {
                        list.Add(new SelectionItem <int> {
                            Text    = user.UserName,
                            Tooltip = __ResStr("selUser", "Select to log in as {0}", user.UserName),
                            Value   = user.UserId,
                        });
                    }
                }
            }

            list = (from l in list orderby l.Text select l).ToList();

            // add the superuser if it hasn't already been added
            using (SuperuserDefinitionDataProvider superDataProvider = new SuperuserDefinitionDataProvider()) {
                UserDefinition user = await superDataProvider.GetSuperuserAsync();

                if (user != null)
                {
                    if ((from l in list where l.Value == user.UserId select l).FirstOrDefault() == null)
                    {
                        list.Insert(0, new SelectionItem <int> {
                            Text    = user.UserName,
                            Tooltip = __ResStr("selUser", "Select to log in as {0}", user.UserName),
                            Value   = user.UserId,
                        });
                    }
                }
            }
            list.Insert(0, new SelectionItem <int> {
                Text    = __ResStr("noUser", "(none)"),
                Tooltip = __ResStr("selLogoff", "Select to log off"),
                Value   = 0,
            });
            return(await DropDownListIntComponent.RenderDropDownListAsync(this, model, list, "yt_yetawf_identity_loginusers"));
        }
Пример #25
0
        public async Task <string> RenderAsync(SerializableList <User> model)
        {
            HtmlBuilder hb = new HtmlBuilder();

            bool header = PropData.GetAdditionalAttributeValue("Header", true);

            GridModel grid = new GridModel()
            {
                GridDef = GetGridModel(header)
            };

            grid.GridDef.DirectDataAsync = async(int skip, int take, List <DataProviderSortInfo> sorts, List <DataProviderFilterInfo> filters) => {
                List <Entry> list = new List <Entry>();
                using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                    if (model != null)
                    {
                        foreach (User user in model)
                        {
                            UserDefinition userDef = await userDP.GetItemByUserIdAsync(user.UserId);

                            string userName;
                            if (userDef == null)
                            {
                                userName = __ResStr("noUser", "({0})", user.UserId);
                            }
                            else
                            {
                                userName = userDef.UserName;
                            }
                            list.Add(new Entry(user.UserId, userName));
                        }
                    }
                }
                return(new DataSourceResult {
                    Data = list.ToList <object>(),
                    Total = list.Count
                });
            };

            hb.Append($@"
<div class='yt_yetawf_identity_listofusernames t_edit' id='{DivId}'>
    {await HtmlHelper.ForDisplayAsAsync(Container, PropertyName, FieldName, grid, nameof(grid.GridDef), grid.GridDef, "Grid", HtmlAttributes: HtmlAttributes)}");

            using (Manager.StartNestedComponent(FieldName)) {
                NewModel newModel = new NewModel();
                hb.Append($@"
    <div class='t_newvalue'>
        {await HtmlHelper.ForLabelAsync(newModel, nameof(newModel.NewValue))}
        {await HtmlHelper.ForEditAsync(newModel, nameof(newModel.NewValue), Validation: false)}
        <input name='btnAdd' type='button' value='Add' disabled='disabled' />
    </div>");
            }

            GridModel gridAll = new GridModel()
            {
                GridDef = GetGridAllUsersModel()
            };
            ListOfUserNamesSetup setup = new ListOfUserNamesSetup {
                AddUrl    = Utility.UrlFor(typeof(ListOfUserNamesController), nameof(ListOfUserNamesController.AddUserName)),
                GridId    = grid.GridDef.Id,
                GridAllId = gridAll.GridDef.Id
            };

            hb.Append($@"
    <div id='{DivId}_coll'>
        {await ModuleActionHelper.BuiltIn_ExpandAction(__ResStr("lblFindUsers", "Find Users"), __ResStr("ttFindUsers", "Expand to find user names available on this site")).RenderAsNormalLinkAsync() }
    </div>
    <div id='{DivId}_exp' style='display:none'>
        {await ModuleActionHelper.BuiltIn_CollapseAction(__ResStr("lblAllUserNames", "All User Names"), __ResStr("ttAllUserNames", "Shows all user names available on this site - Select a user name to update the text box above, so the user name can be added to the list of user names - Click to close")).RenderAsNormalLinkAsync() }
        {await HtmlHelper.ForDisplayAsAsync(Container, PropertyName, FieldName, gridAll, nameof(gridAll.GridDef), gridAll.GridDef, "Grid")}
    </div>
</div>");

            Manager.ScriptManager.AddLast($@"
$YetaWF.expandCollapseHandling('{DivId}', '{DivId}_coll', '{DivId}_exp');
new YetaWF_Identity.ListOfUserNamesEditComponent('{DivId}', {Utility.JsonSerialize(setup)});");

            return(hb.ToString());
        }
Пример #26
0
        public async Task <string> RenderAsync(int model)
        {
            HtmlBuilder hb = new HtmlBuilder();

            string type = PropData.GetAdditionalAttributeValue <string>("Force", null);

            if (type == "Grid" || (await IsLargeUserBaseAsync() && type != "DropDown"))
            {
                string hiddenId = UniqueId();
                string allId    = UniqueId();
                string nameId   = UniqueId();
                string noUser   = __ResStr("noUser", "(none)");

                bool header = PropData.GetAdditionalAttributeValue("Header", true);

                UserIdUI ui = new UserIdUI {
                    UserId = model,
                };
                using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                    UserDefinition user = await userDP.GetItemByUserIdAsync(model);

                    if (user == null)
                    {
                        ui.UserName = __ResStr("noUser", "(none)");
                    }
                    else
                    {
                        ui.UserName = user.UserName;
                    }
                }

                ui.AllUsers    = GetGridAllUsersModel(header);
                ui.AllUsers.Id = allId;

                hb.Append($@"
<div class='yt_yetawf_identity_userid t_large t_edit' id='{DivId}'>
    {await HtmlHelper.ForEditComponentAsync(Container, PropertyName, model, "Hidden", HtmlAttributes: new { id = hiddenId, __NoTemplate = true })}");

                using (Manager.StartNestedComponent(FieldName)) {
                    hb.Append($@"
    <div class='t_name'>
        {await HtmlHelper.ForDisplayAsync(ui, nameof(ui.UserName), HtmlAttributes: new { id = nameId })}
        {ImageHTML.BuildKnownIcon("#RemoveLight", title: __ResStr("ttClear", "Clear the current selection"), cssClass: "t_clear")}
    </div>
    {await HtmlHelper.ForLabelAsync(ui, nameof(ui.AllUsers))}
    {await HtmlHelper.ForDisplayAsync(ui, nameof(ui.AllUsers))}");
                }
                hb.Append($@"
</div>");

                UserIdSetup setup = new UserIdSetup {
                    GridAllId = ui.AllUsers.Id,
                    HiddenId  = hiddenId,
                    NameId    = nameId,
                    NoUser    = noUser,
                };

                Manager.ScriptManager.AddLast($@"new YetaWF_Identity.UserIdEditComponent('{DivId}', {Utility.JsonSerialize(setup)});");
            }
            else
            {
                hb.Append($@"
<div class='yt_yetawf_identity_userid t_small t_edit'>");

                using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                    List <DataProviderSortInfo> sorts = null;
                    DataProviderSortInfo.Join(sorts, new DataProviderSortInfo {
                        Field = nameof(UserDefinition.UserName), Order = DataProviderSortInfo.SortDirection.Ascending
                    });
                    DataProviderGetRecords <UserDefinition> recs = await userDP.GetItemsAsync(0, MAXUSERS, sorts, null);

                    List <SelectionItem <int> > list = (from u in recs.Data select new SelectionItem <int> {
                        Text = u.UserName,
                        Value = u.UserId,
                    }).ToList();
                    list.Insert(0, new SelectionItem <int> {
                        Text  = __ResStr("select", "(select)"),
                        Value = 0,
                    });
                    hb.Append(await DropDownListIntComponent.RenderDropDownListAsync(this, model, list, null));
                }

                hb.Append($@"
</div>");
            }
            return(hb.ToString());
        }