コード例 #1
0
ファイル: AccountIdentity.cs プロジェクト: magudb/Console
        public AccountIdentity(string name)
        {
            Assert.ArgumentNotNullOrEmpty(name, "name");

            var domain  = "sitecore";
            var account = name;

            if (name.Contains(@"\"))
            {
                domain  = StringUtil.GetPrefix(name, '\\');
                account = StringUtil.GetPostfix(name, '\\');
            }

            if (!Regex.IsMatch(account, @"^\w[\w\s.\\_-]*$", RegexOptions.Compiled))
            {
                throw new ArgumentException(
                          $"The name '{name}' is improperly formatted.\n\nThe name can only contain the following characters: a-z, 0-9, periods, dashes, underscores, backslashes, and spaces.", "name");
            }

            Domain  = domain;
            Account = account;
            if (RolesInRolesManager.IsCreatorOwnerRole(account))
            {
                Name = name;
            }
            else
            {
                Name = string.IsNullOrEmpty(domain) ? account : domain + @"\" + account;
            }
        }
コード例 #2
0
        protected override IEnumerable <KeyValuePair <string, string> > GetNonSelectedItems()
        {
            // Return here your unselected items. First value is the ID you will store into your field, the second one is the display text.
            var retVal = RolesInRolesManager.GetAllRoles().ToKeyValuePair();

            return(retVal);
        }
コード例 #3
0
        public static bool CanFindAccount(this Cmdlet command, AccountIdentity account, AccountType accountType)
        {
            if (account == null)
            {
                return(false);
            }
            var name  = account.Name;
            var error = $"Cannot find an account with identity '{name}'.";

            if (accountType == AccountType.Role)
            {
                if (!Role.Exists(name) && !RolesInRolesManager.IsCreatorOwnerRole(name) && !RolesInRolesManager.IsSystemRole(name))
                {
                    command.WriteError(new ErrorRecord(new ObjectNotFoundException(error),
                                                       ErrorIds.AccountNotFound.ToString(),
                                                       ErrorCategory.ObjectNotFound, account));
                    return(false);
                }
            }

            if (accountType == AccountType.User && !User.Exists(name))
            {
                command.WriteError(new ErrorRecord(new ObjectNotFoundException(error), ErrorIds.AccountNotFound.ToString(),
                                                   ErrorCategory.ObjectNotFound, account));
                return(false);
            }

            return(true);
        }
コード例 #4
0
        public override void Display(DisplayElement dElement)
        {
            var role = dElement.Element as Role;

            if ((Account)role == (Account)null)
            {
                return;
            }

            foreach (var column in Columns)
            {
                switch (column.Name)
                {
                case "name":
                    dElement.AddColumn(column.Header, role.DisplayName);
                    break;

                case "description":
                    dElement.AddColumn(column.Header, role.Description);
                    break;

                case "domain":
                    dElement.AddColumn(column.Header, role.Domain.Name);
                    break;

                case "users":
                    string usersInRole = string.Join("|", RolesInRolesManager.GetUsersInRole(role, true).Select(u => u.DisplayName).ToArray());
                    dElement.AddColumn(column.Header, usersInRole);
                    break;
                }
            }
        }
コード例 #5
0
        public static Role EnsureAllRole([NotNull] string roleKind)
        {
            // ensure "sitecore\Bloggr All (role)" -> "sitecore\Bloggr All Users" -> "sitecore\Authors"
            Assert.ArgumentNotNull(roleKind, "roleKind");

            var all       = "sitecore\\Bloggr All " + roleKind;
            var allExists = Role.Exists(all);

            if (!allExists)
            {
                Log.Info("Creating role: " + all, typeof(BloggrInstallHook));
                Roles.CreateRole(all);
            }

            var allRole = Role.FromName(all);

            Assert.IsNotNull(allRole, "Role does not exist: " + all);

            if (!allExists)
            {
                RolesInRolesManager.AddRoleToRole(allRole, EnsureAllUsersRole());
            }

            return(allRole);
        }
コード例 #6
0
        public void Process(UnicornReserializeCompletePipelineArgs args)
        {
            var rolePredicate = args.Configuration.Resolve <IRolePredicate>();

            // no predicate = configuration doesn't include any roles
            if (rolePredicate == null)
            {
                return;
            }

            var dataStore = args.Configuration.Resolve <IRoleDataStore>();
            var logger    = args.Configuration.Resolve <ILogger>();

            logger.Info(string.Empty);
            logger.Info($"{args.Configuration.Name} roles are being reserialized.");

            dataStore.Clear();

            var roles = RolesInRolesManager.GetAllRoles()
                        .Select(role => new SitecoreRoleData(role))
                        .Where(role => rolePredicate.Includes(role).IsIncluded);

            int roleCount = 0;

            foreach (var role in roles)
            {
                dataStore.Save(role);
                roleCount++;
            }

            logger.Info($"{args.Configuration.Name} role reserialize complete. {roleCount} roles were reserialized.");
            logger.Info(string.Empty);
        }
コード例 #7
0
        private void DownloadRolesExport()
        {
            var allright = CurrentRights.GetAllRightsMaster();
            var rols     = Request.Form.Get("rol");

            if (rols != null)
            {
                foreach (var rol in rols.Split(','))
                {
                    var account = Sitecore.Security.Accounts.Role.FromName(rol);
                    if (account == null)
                    {
                        break;
                    }
                    dowload.Text += "role," + account.Name + ",";
                    int count = 0;
                    foreach (var subrol in RolesInRolesManager.GetRolesInRole(account, false))
                    {
                        if (count != 0)
                        {
                            dowload.Text += "|";
                        }
                        dowload.Text += subrol.Name;
                        count++;
                    }
                    dowload.Text += "\n";
                }
                foreach (var rol in rols.Split(','))
                {
                    var account = Sitecore.Security.Accounts.Role.FromName(rol);
                    if (account == null)
                    {
                        break;
                    }
                    foreach (var itemWithRights in allright)
                    {
                        var accessRules = itemWithRights.Security.GetAccessRules();
                        if (accessRules != null)
                        {
                            foreach (var rule in accessRules)
                            {
                                if (rule.Account == account)
                                {
                                    AccessRuleCollection ruleCollection = new AccessRuleCollection();
                                    ruleCollection.Add(rule);
                                    dowload.Text += itemWithRights.Paths.FullPath + "," + ruleCollection.ToString() + "\n";
                                }
                            }
                        }
                    }
                }
            }
            Response.Clear();
            Response.ContentType = "application/CSV";
            Response.AddHeader("Cache-Control", "must-revalidate");
            Response.AddHeader("Pragma", "must-revalidate");
            Response.AddHeader("Content-type", "application/x-download");
            Response.AddHeader("Content-disposition", "attachment; filename=sitecore-roles-export.csv");
        }
コード例 #8
0
        protected override IEnumerable <KeyValuePair <string, string> > GetSelectedItems()
        {
            // Return here your selected items. First value is the ID you will store into your field, the second one is the display text.
            var selectedRoles = Value.Split('|');
            var retVal        = RolesInRolesManager.GetAllRoles().Where(rl => selectedRoles.Contains(rl.LocalName)).ToKeyValuePair();

            return(retVal);
        }
コード例 #9
0
        protected virtual void DeserializeRole(IRoleData role)
        {
            bool addedRole = false;

            // Add role if needed
            var name = role.RoleName;

            if (!System.Web.Security.Roles.RoleExists(name))
            {
                _loaderLogger.AddedNewRole(role);
                addedRole = true;
                System.Web.Security.Roles.CreateRole(name);
            }

            Role targetRole           = Role.FromName(name);
            var  currentSourceParents = new SitecoreRoleData(targetRole).MemberOfRoles;
            var  currentTargetParents = role.MemberOfRoles;

            var addedRoleMembership   = new List <string>();
            var removedRoleMembership = new List <string>();
            var deferredUpdateLog     = new DeferredLogWriter <IRoleLoaderLogger>();

            // Loop over the serialized parent roles and set db roles if needed
            foreach (var serializedMemberRoleName in currentTargetParents)
            {
                var memberRole = Role.FromName(serializedMemberRoleName);

                // add nonexistant parent role if needed. NOTE: parent role need not be one we have serialized or included.
                if (!Role.Exists(serializedMemberRoleName))
                {
                    deferredUpdateLog.AddEntry(log => log.AddedNewRoleMembership(new SitecoreRoleData(memberRole)));
                    System.Web.Security.Roles.CreateRole(serializedMemberRoleName);
                }

                // Add membership if not already in the parent role
                if (!RolesInRolesManager.IsRoleInRole(targetRole, memberRole, false))
                {
                    addedRoleMembership.Add(memberRole.Name);
                    RolesInRolesManager.AddRoleToRole(targetRole, memberRole);
                }
            }

            // Loop over parent roles that exist in the database but not in serialized and remove them
            var membershipToRemove = currentSourceParents.Where(parent => !currentTargetParents.Contains(parent, StringComparer.OrdinalIgnoreCase));

            foreach (var roleToRemove in membershipToRemove)
            {
                removedRoleMembership.Add(roleToRemove);
                RolesInRolesManager.RemoveRoleFromRole(targetRole, Role.FromName(roleToRemove));
            }

            if (!addedRole && (addedRoleMembership.Count > 0 || removedRoleMembership.Count > 0))
            {
                _loaderLogger.RoleMembershipChanged(role, addedRoleMembership.ToArray(), removedRoleMembership.ToArray());
            }

            deferredUpdateLog.ExecuteDeferredActions(_loaderLogger);
        }
コード例 #10
0
        // Get list of other author emails from current author's content group, if any
        public static string GetToAddressesForApproveRejectEmail(User currentAuthor, string itemPath)
        {
            if (currentAuthor.IsInRole(scAuthor))
            {
                List <string> myDeptContentGroup = new List <string>();
                string        emailList          = "";
                string        currentAuthorEmail = currentAuthor.Profile.Email;
                UserRoles     allUserRoles       = currentAuthor.Roles;

                // Find current author's content group(s)
                foreach (Role role in allUserRoles)
                {
                    if (role.DisplayName.ToLower().StartsWith("hscnet\\sc_") && role.DisplayName.ToLower().EndsWith("_content"))
                    {
                        myDeptContentGroup.Add(role.DisplayName);
                    }
                }

                // If author is in at least one dept content group
                if (myDeptContentGroup.Count > 0)
                {
                    foreach (string dept in myDeptContentGroup)
                    {
                        IEnumerable <User> allMembersOfContentGroup = RolesInRolesManager.GetUsersInRole(Role.FromName(dept), true);
                        foreach (User person in allMembersOfContentGroup)
                        {
                            if (person.IsInRole(scAuthor))
                            {
                                using (new Sitecore.Security.Accounts.UserSwitcher(person))
                                {
                                    if (Sitecore.Configuration.Factory.GetDatabase("master").GetItem(itemPath).Security.CanWrite(person))
                                    {
                                        // other authors also have WRITE access to the item originally updated by contributor
                                        if ((!String.IsNullOrEmpty(person.Profile.Email)) && (!person.Profile.Email.Equals(currentAuthorEmail)))
                                        {
                                            emailList += person.Profile.Email + ";";
                                        }
                                    }
                                    else
                                    {
                                        goto nextGroup;
                                    }
                                }
                            }
                        }
                        if (!String.IsNullOrEmpty(emailList))
                        {
                            goto done;
                        }
                        nextGroup :;
                    }
                }
                done :;
                return(emailList);
            }
            return(null);
        }
コード例 #11
0
        private static IEnumerable <Role> GetRoles()
        {
            IEnumerable <Role> roles = RolesInRolesManager.GetAllRoles();

            if (roles != null)
            {
                return(roles);
            }

            return(new List <Role>());
        }
コード例 #12
0
        /// <summary>
        /// Pulls the selected Virtual User Roles from the InternalAccessItem
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        public IEnumerable <Role> GetVirtualUserRoles()
        {
            var retVal = new List <Role>();

            if (VirtualUserRoles != null && !VirtualUserRoles.IsNullOrEmpty())
            {
                var selectedRoles = VirtualUserRoles.Split('|');
                retVal = RolesInRolesManager.GetAllRoles().Where(rl => selectedRoles.Contains(rl.LocalName)).ToList();
            }

            return(retVal);
        }
コード例 #13
0
        protected override void ProcessRecord()
        {
            var name = Identity.Name;

            if (Role.Exists(name))
            {
                var targetRole = Role.FromName(name);

                foreach (var member in Members)
                {
                    if (User.Exists(member.Name))
                    {
                        var user = User.FromName(member.Name, false);
                        if (user.IsInRole(targetRole))
                        {
                            continue;
                        }

                        if (!ShouldProcess(targetRole.Name, $"Add user '{user.Name}' to role"))
                        {
                            continue;
                        }

                        var profile = UserRoles.FromUser(user);
                        profile.Add(targetRole);
                    }
                    else if (Role.Exists(member.Name))
                    {
                        var role = Role.FromName(member.Name);
                        if (RolesInRolesManager.IsRoleInRole(role, targetRole, false))
                        {
                            continue;
                        }

                        if (ShouldProcess(targetRole.Name, $"Add role '{role.Name}' to role"))
                        {
                            RolesInRolesManager.AddRoleToRole(role, targetRole);
                        }
                    }
                    else
                    {
                        WriteError(typeof(ObjectNotFoundException), $"Cannot find an account with identity '{member}'.",
                                   ErrorIds.AccountNotFound, ErrorCategory.ObjectNotFound, member);
                    }
                }
            }
            else
            {
                WriteError(typeof(ObjectNotFoundException), $"Cannot find an account with identity '{name}'.",
                           ErrorIds.AccountNotFound, ErrorCategory.ObjectNotFound, Identity);
            }
        }
コード例 #14
0
        /// <summary>
        /// Adds the roles to roles.
        /// </summary>
        private void AddRolesToRoles()
        {
            var accounting        = Role.FromName(OrderManagerRole.OrderManagerAccounting);
            var administrators    = Role.FromName(OrderManagerRole.OrderManagerAdministrators);
            var clientUsers       = Role.FromName(OrderManagerRole.OrderManagerClientUsers);
            var customerService   = Role.FromName(OrderManagerRole.OrderManagerCustomerService);
            var everyone          = Role.FromName(OrderManagerRole.OrderManagerEveryone);
            var logViewers        = Role.FromName(OrderManagerRole.OrderManagerLogViewers);
            var packaging         = Role.FromName(OrderManagerRole.OrderManagerPackaging);
            var processing        = Role.FromName(OrderManagerRole.OrderManagerProcessing);
            var exampleProcessing = Role.FromName(OrderManagerRole.OrderManagerExampleProcessing);
            var sales             = Role.FromName(OrderManagerRole.OrderManagerSales);
            var shipping          = Role.FromName(OrderManagerRole.OrderManagerShipping);

            var everyoneChildren = new List <Role>
            {
                accounting,
                administrators,
                customerService,
                packaging,
                processing,
                sales,
                shipping
            };

            var clientUsersChildren = new List <Role>
            {
                accounting,
                administrators,
                customerService,
                packaging,
                processing,
                sales,
                shipping
            };

            var logViewersChildren = new List <Role>
            {
                administrators
            };

            var processingChildren = new List <Role>
            {
                exampleProcessing
            };

            RolesInRolesManager.AddRolesToRole(everyoneChildren, everyone);
            RolesInRolesManager.AddRolesToRole(clientUsersChildren, clientUsers);
            RolesInRolesManager.AddRolesToRole(logViewersChildren, logViewers);
            RolesInRolesManager.AddRolesToRole(processingChildren, processing);
        }
コード例 #15
0
        private void AddOrUpdate(Item item, OperationType operation, IEnumerable <ChangedField> changedFields)
        {
            var userName = item.Statistics.UpdatedBy;

            if (string.IsNullOrEmpty(userName))
            {
                userName = item.Statistics.CreatedBy;
            }

            if (!_userService.IsUserInRole(userName))
            {
                return;
            }

            var user = _userAuditReportReposiotry.GetByUserName(userName);

            if (user == null)
            {
                var changes = new List <Change>
                {
                    new Change(changedFields, operation)
                };

                var changedItems = new List <ChangedItem>
                {
                    new ChangedItem(item.ID.ToString(), item.Paths.FullPath, item.Language.Name, changes)
                };

                var userRoles = RolesInRolesManager.GetRolesForUser(User.FromName(userName, false),
                                                                    true).Select(r => r.Name);
                user = new UserChange(userName, userRoles, changedItems);

                _userAuditReportReposiotry.Add(user);
            }
            else
            {
                var changedItem = user.ChangedItems.FirstOrDefault(i => i.ItemId.Equals(item.ID.ToString()) && i.Language.Equals(item.Language.Name));
                if (changedItem == null)
                {
                    changedItem = new ChangedItem(item.ID.ToString(), item.Paths.FullPath, item.Language.Name);
                    user.ChangedItems.Add(changedItem);
                }
                changedItem.ItemPath = item.Paths.FullPath;
                var change = new Change(changedFields, operation);

                changedItem.Changes.Add(change);
                _userAuditReportReposiotry.Update(user);
            }
        }
コード例 #16
0
        /// <summary>
        /// Gets user emails for a specified role.
        /// </summary>
        /// <param name="roleName">
        /// The role name.
        /// </param>
        /// <returns>
        /// Returns user's emails.
        /// </returns>
        private string GetRoleMembers(string roleName)
        {
            IEnumerable <string> emails = null;
            Role role = Role.Exists(roleName) ? Role.FromName(roleName) : null;

            if (role != null)
            {
                IEnumerable <Account> users = RolesInRolesManager.GetRoleMembers(role, false).Where(account => account.AccountType == AccountType.User);
                emails = users.Where(user => !string.IsNullOrEmpty(((User)user).Profile.Email)).Select(user => ((User)user).Profile.Email);
            }

            string emailList = emails != null?string.Join(",", emails.ToArray()) : null;

            return(emailList);
        }
コード例 #17
0
        /// <summary>
        /// Logins the specified user.
        /// </summary>
        /// <param name="user">The user.</param>
        public void Login(IPrincipal user)
        {
            var identity = user.Identity;

#if DEBUG
            WriteClaimsInfo(user.Identity as ClaimsIdentity);
#endif
            if (!identity.IsAuthenticated)
            {
                return;
            }
            var userName = string.Format("{0}\\{1}", Context.Domain.Name, identity.Name);
            try
            {
                var virtualUser = AuthenticationManager.BuildVirtualUser(userName, true);
                var roles       = Context.Domain.GetRoles();
                if (roles != null)
                {
                    var groups = GetGroups(user.Identity as ClaimsIdentity);
                    foreach (var role in from role in roles
                             let roleName = GetRoleName(role.Name)
                                            where groups.Contains(roleName.ToLower()) && !virtualUser.Roles.Contains(role)
                                            select role)
                    {
                        virtualUser.Roles.Add(role);
                    }
                    foreach (
                        var role2 in
                        virtualUser.Roles.SelectMany(
                            role1 =>
                            RolesInRolesManager.GetRolesForRole(role1, true)
                            .Where(role2 => !virtualUser.Roles.Contains(role2))))
                    {
                        virtualUser.Roles.Add(role2);
                    }

                    // Setting the user to be an admin.
                    virtualUser.RuntimeSettings.IsAdministrator =
                        groups.Contains(Settings.GetSetting("ADFS.Authenticator.AdminUserRole", "Admins"));
                }

                AuthenticationManager.Login(virtualUser);
            }
            catch (ArgumentException ex)
            {
                Log.Error("ADFS::Login Failed!", ex, this);
            }
        }
コード例 #18
0
        public static Account GetAccountFromIdentity(this Cmdlet command, AccountIdentity identity)
        {
            Account account = identity;

            if (account == null)
            {
                if (RolesInRolesManager.IsCreatorOwnerRole(identity.Name) || RolesInRolesManager.IsSystemRole(identity.Name))
                {
                    return(Role.FromName(identity.Name));
                }
                var error = $"Cannot find an account with identity '{identity.Name}'.";
                command.WriteError(new ErrorRecord(new ObjectNotFoundException(error), ErrorIds.AccountNotFound.ToString(),
                                                   ErrorCategory.ObjectNotFound, identity));
            }
            return(account);
        }
コード例 #19
0
        protected virtual void EvaluateOrphans(IRoleData[] roles)
        {
            var knownRoles = roles.ToLookup(key => key.RoleName);

            var allOrphanRoles = RolesInRolesManager.GetAllRoles(false)
                                 .Select(role => new SitecoreRoleData(role))
                                 .Where(role => _rolePredicate.Includes(role).IsIncluded)
                                 .Where(role => !knownRoles.Contains(role.RoleName))
                                 .ToArray();

            foreach (var orphan in allOrphanRoles)
            {
                _loaderLogger.RemovedOrphanRole(orphan);
                System.Web.Security.Roles.DeleteRole(orphan.RoleName);
            }
        }
コード例 #20
0
        protected override void ProcessRecord()
        {
            if (!this.CanFindAccount(Identity, AccountType.Role))
            {
                return;
            }

            var name = Identity.Name;

            var targetRole = Role.FromName(name);

            foreach (var member in Members)
            {
                if (User.Exists(member.Name))
                {
                    var user = User.FromName(member.Name, false);
                    if (!user.IsInRole(targetRole))
                    {
                        continue;
                    }

                    var profile = UserRoles.FromUser(user);
                    if (ShouldProcess(targetRole.Name, $"Remove user '{user.Name}' from role"))
                    {
                        profile.Remove(targetRole);
                    }
                }
                else if (Role.Exists(member.Name))
                {
                    var role = Role.FromName(member.Name);
                    if (!RolesInRolesManager.IsRoleInRole(role, targetRole, false))
                    {
                        continue;
                    }

                    if (ShouldProcess(targetRole.Name, $"Remove role '{role.Name}' from role"))
                    {
                        RolesInRolesManager.RemoveRoleFromRole(role, targetRole);
                    }
                }
                else
                {
                    WriteError(typeof(ObjectNotFoundException), $"Cannot find an account with identity '{member}'.",
                               ErrorIds.AccountNotFound, ErrorCategory.ObjectNotFound, member);
                }
            }
        }
コード例 #21
0
        public override void Display(DisplayElement dElement)
        {
            Role role = dElement.Element as Role;

            if ((Account)role == (Account)null)
            {
                return;
            }

            dElement.AddColumn("Name", role.DisplayName);
            dElement.AddColumn("Description", role.Description);
            dElement.AddColumn("Domain", role.Domain.Name);

            string usersInRole = string.Join("|", RolesInRolesManager.GetUsersInRole(role, true).Select(u => u.DisplayName).ToArray());

            dElement.AddColumn("Users", usersInRole);
        }
コード例 #22
0
        public void ShouldSwitchRolesInRolesProvider()
        {
            // arrange
            var roles = new[] { Role.FromName(@"sitecore/Editors") };

            var localProvider = Substitute.For <RolesInRolesProvider, IThreadLocalProvider <RolesInRolesProvider> >();

            localProvider.GetAllRoles(true).Returns(roles);

            // act
            using (new RolesInRolesSwitcher(localProvider))
            {
                // assert
                RolesInRolesManager.GetAllRoles(true).Should().BeSameAs(roles);
            }

            RolesInRolesManager.GetAllRoles(true).Should().BeEmpty();
        }
コード例 #23
0
        public static void EnsureBlogRoles([NotNull] string blogName)
        {
            Assert.ArgumentNotNull(blogName, "blogName");

            foreach (var roleKind in RoleKinds)
            {
                var globalRole = EnsureAllRole(roleKind);

                // ensure "sitecore\Bloggr (role) - (blog)" -> "sitecore\Bloggr All (role)" -> "sitecore\Bloggr All Users" -> "sitecore\Authors"
                var blogRoleName   = "sitecore\\Bloggr " + roleKind + " - " + blogName;
                var blogRoleExists = Role.Exists(blogRoleName);
                if (!blogRoleExists)
                {
                    Log.Info("Creating role: " + blogRoleName, typeof(BloggrInstallHook));
                    Roles.CreateRole(blogRoleName);
                    RolesInRolesManager.AddRoleToRole(Role.FromName(blogRoleName), globalRole);
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Gets email list according to roles per section set.
        /// </summary>
        /// <param name="item">Root of the section.</param>
        /// <returns>Comma-separated string containing emails to send to.</returns>
        private static string GetEmailsForSection(Item item)
        {
            const string sectionNotFoundMessage = "Item '{0}' is not in any section";
            const string roleNotFoundMessage    = "Could not find roles to notify for item '{0}'!";
            const string usersNotFoundMessage   = "Could not find users to notify for item '{0}'!";

            ScheduledPublishSection section = item.GetParentSection();

            if (section == null)
            {
                Log.Warn(string.Format(sectionNotFoundMessage, item.Name), typeof(MailManager));
                return(string.Empty);
            }

            IEnumerable <string> sectionRoleNames = section.SectionRoleNames;
            IList <Role>         sectionRoles     = sectionRoleNames.Where(Role.Exists).Select(Role.FromName).ToList();

            if (sectionRoles.Count == 0)
            {
                Log.Error(string.Format(roleNotFoundMessage, item.Name), typeof(MailManager));
                return(string.Empty);
            }

            IList <User> users = new List <User>();

            foreach (var sectionRole in sectionRoles)
            {
                users = users.Union(RolesInRolesManager.GetUsersInRole(sectionRole, true)).ToList();
            }

            if (users.Count == 0)
            {
                Log.Warn(string.Format(usersNotFoundMessage, item.Name), typeof(MailManager));
                return(string.Empty);
            }

            IEnumerable <string> emailList = users
                                             .Where(x => !string.IsNullOrWhiteSpace(x.Profile.Email))
                                             .Select(x => x.Profile.Email);

            return(string.Join(", ", emailList));
        }
コード例 #25
0
ファイル: RemoveRoleCommand.cs プロジェクト: vsegrad/Console
        protected override void ProcessRecord()
        {
            if (!this.CanFindAccount(Identity, AccountType.Role))
            {
                return;
            }

            var name = ParameterSetName == "Id" ? Identity.Name : Instance.Name;

            if (!ShouldProcess(name, "Remove role"))
            {
                return;
            }

            var role = Role.FromName(name);

            if (!role.IsEveryone)
            {
                var usersInRoles = Roles.GetUsersInRole(name);
                if (usersInRoles.Any())
                {
                    Roles.RemoveUsersFromRole(usersInRoles, name);
                }

                if (RolesInRolesManager.RolesInRolesSupported)
                {
                    var rolesInRole = RolesInRolesManager.GetRolesForRole(role, false);
                    if (rolesInRole.Any())
                    {
                        RolesInRolesManager.RemoveRolesFromRole(rolesInRole, role);
                    }
                }

                Roles.DeleteRole(name, true);
            }
            else
            {
                WriteError(typeof(SecurityException), $"Cannot remove role '{name}'.",
                           ErrorIds.InsufficientSecurityRights, ErrorCategory.PermissionDenied, name);
            }
        }
コード例 #26
0
 private static void CreateRolInRols(List <string> rols)
 {
     foreach (var line in rols)
     {
         var splitted = line.Split(',');
         if (splitted.Length == 3 && splitted[0] == "role")
         {
             var rol = Sitecore.Security.Accounts.Role.FromName(splitted[1]);
             foreach (var subrolstring in splitted[2].Split('|'))
             {
                 var subrol = Sitecore.Security.Accounts.Role.FromName(subrolstring);
                 if (rol != null && subrol != null)
                 {
                     if (RolesInRolesManager.RolesInRolesSupported && !RolesInRolesManager.IsRoleInRole(subrol, rol, false))
                     {
                         RolesInRolesManager.AddRoleToRole(subrol, rol);
                     }
                 }
             }
         }
     }
 }
コード例 #27
0
        public static MailMessage AddRecipientsToMail(MailMessage mailMessage, string roleName)
        {
            if (Role.Exists(roleName))
            {
                Role        role  = Role.FromName(roleName);
                List <User> users = RolesInRolesManager.GetUsersInRole(role, true)
                                    .Where(x => x.IsInRole(role))
                                    .Where(user => !string.IsNullOrEmpty(user.Profile.Email))
                                    .ToList();

                foreach (User user in users)
                {
                    mailMessage.To.Add(user.Profile.Email);
                }
            }
            else
            {
                Log.Error($"No Users with valid email addresses found in role {roleName}", typeof(SubmissionNotification));
            }

            return(mailMessage);
        }
コード例 #28
0
        private static Role EnsureAllUsersRole()
        {
            Role allUsersRole;
            var  allUsers       = "sitecore\\Bloggr All Users";
            var  allUsersExists = Role.Exists(allUsers);

            if (!allUsersExists)
            {
                Log.Info("Creating role: " + allUsers, typeof(BloggrInstallHook));
                Roles.CreateRole(allUsers);
            }

            allUsersRole = Role.FromName(allUsers);
            Assert.IsNotNull(allUsersRole, "Role does not exist: " + allUsers);

            if (!allUsersExists)
            {
                RolesInRolesManager.AddRoleToRole(allUsersRole, Role.FromName("sitecore\\Author"));
            }

            return(allUsersRole);
        }
コード例 #29
0
        protected override bool Execute(T ruleContext)
        {
            Assert.ArgumentNotNull(ruleContext, nameof(ruleContext));

            var configuredRoles = this.Value;

            if (configuredRoles == null)
            {
                return(false);
            }

            foreach (var configuredRole in configuredRoles.Split(new [] { "|" }, StringSplitOptions.RemoveEmptyEntries))
            {
                var role = Role.FromName(configuredRole);

                if (RolesInRolesManager.IsUserInRole(Context.User, role, true))
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #30
0
        private static void EnsureRoles()
        {
            // ensure "sitecore\Bloggr All Users" -> "sitecore\Authors"
            var allUsersRole = EnsureAllUsersRole();

            // ensure "sitecore\Bloggr Global Administrators" -> "sitecore\Bloggr All Users" -> "sitecore\Author"
            Role globalAdminsRole;
            var  globalAdmins       = "sitecore\\Bloggr Global Administrators";
            var  globalAdminsExists = Role.Exists(globalAdmins);

            if (!globalAdminsExists)
            {
                Log.Info("Creating role: " + globalAdmins, typeof(BloggrInstallHook));
                Roles.CreateRole(globalAdmins);
            }

            globalAdminsRole = Role.FromName(globalAdmins);
            Assert.IsNotNull(globalAdminsRole, "Role does not exist: " + globalAdmins);

            if (!globalAdminsExists)
            {
                RolesInRolesManager.AddRoleToRole(globalAdminsRole, allUsersRole);
            }

            var blogNames = BloggrFactory.GetBlogNames();

            foreach (var roleKind in RoleKinds)
            {
                EnsureAllRole(roleKind);
            }

            foreach (var blogName in blogNames)
            {
                EnsureBlogRoles(blogName);
            }
        }