private static List <PrincipalInfo> ParallelGetPrincipal(string testUserName, RhetosAppOptions rhetosAppOptions, bool commitChanges)
        {
            var report = new ConcurrentDictionary <int, PrincipalInfo>();

            const int threadCount = 4;

            // Recompute membership on authorization with multiple parallel requests:
            Parallel.For(0, threadCount, thread =>
            {
                using (var container = new RhetosTestContainer(commitChanges))
                {
                    container.InitializeSession += builder => builder.RegisterInstance(rhetosAppOptions).ExternallyOwned();
                    try
                    {
                        var authorizationData = container.Resolve <AuthorizationDataLoader>();

                        // First call will automatically create a new principal, see AuthorizationAddUnregisteredPrincipals above.
                        // Other calls should return the same principal.
                        PrincipalInfo principal = authorizationData.GetPrincipal(testUserName);
                        report[thread]          = principal;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        container.Resolve <IPersistenceTransaction>().DiscardChanges();
                        throw;
                    }
                }
            });

            Assert.AreEqual(threadCount, report.Count);
            return(report.Values.ToList());
        }
示例#2
0
        /// <summary>
        /// Retrieves order for export and calls the IExportOrderService for each one
        /// </summary>
        /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
        public override string Execute()
        {
            PrincipalInfo.CurrentPrincipal = PrincipalInfo.CreatePrincipal("admin");
            //Call OnStatusChanged to periodically notify progress of job for manually started jobs
            OnStatusChanged("Starting looking for orders to export.");

            Stopwatch tmr = Stopwatch.StartNew();
            List <ExportOrderInformation> results = new List <ExportOrderInformation>();
            List <PurchaseOrder>          orders  = GetOrdersToExport();

            tmr.Stop();

            _log.Debug("Found {0} orders to export in {1}ms", orders.Count, tmr.ElapsedMilliseconds);


            if (_stopSignaled)
            {
                return("Job was stopped");
            }

            IExportOrderService service = ServiceLocator.Current.GetInstance <IExportOrderService>();

            foreach (PurchaseOrder purchaseOrder in orders)
            {
                if (_stopSignaled)
                {
                    return("Job was stopped");
                }
                OnStatusChanged(string.Format("Exporting order: {0}", purchaseOrder.TrackingNumber));

                results.Add(ExportOrder(purchaseOrder, service));
            }

            return(string.Format("Exported {0} orders", results.Count));
        }
示例#3
0
        public PrincipalPermission(string name, string role, bool isAuthenticated)
        {
            principals = new ArrayList();
            PrincipalInfo pi = new PrincipalInfo(name, role, isAuthenticated);

            principals.Add(pi);
        }
示例#4
0
        private static FieldUserValue GetUserFieldValue(string userName, ClientContext clientContext)
        {
            //Returns first principal match based on user identifier (display name, email, etc.)
            ClientResult <PrincipalInfo> principalInfo = Utility.ResolvePrincipal(
                clientContext,       //context
                clientContext.Web,   //web
                userName,            //input
                PrincipalType.User,  //scopes
                PrincipalSource.All, //sources
                null,                //usersContainer
                false);              //inputIsEmailOnly

            clientContext.ExecuteQuery();
            PrincipalInfo person = principalInfo.Value;

            if (person != null)
            {
                //Get User field from login name
                User validatedUser = clientContext.Web.EnsureUser(person.LoginName);
                clientContext.Load(validatedUser);
                clientContext.ExecuteQuery();

                if (validatedUser != null && validatedUser.Id > 0)
                {
                    //Sets lookup ID for user field to the appropriate user ID
                    FieldUserValue userFieldValue = new FieldUserValue();
                    userFieldValue.LookupId = validatedUser.Id;
                    return(userFieldValue);
                }
            }
            return(null);
        }
示例#5
0
        public void FromXml(SecurityElement esd)
        {
            // General validation in CodeAccessPermission
            CheckSecurityElement(esd, "esd", version, version);
            // Note: we do not (yet) care about the return value
            // as we only accept version 1 (min/max values)

            principals.Clear();
            // Children is null, not empty, when no child is present
            if (esd.Children != null)
            {
                foreach (SecurityElement se in esd.Children)
                {
                    if (se.Tag != "Identity")
                    {
                        throw new ArgumentException("not IPermission/Identity");
                    }
                    string name            = se.Attribute("ID");
                    string role            = se.Attribute("Role");
                    string auth            = se.Attribute("Authenticated");
                    bool   isAuthenticated = false;
                    if (auth != null)
                    {
                        try {
                            isAuthenticated = Boolean.Parse(auth);
                        }
                        catch {}
                    }
                    PrincipalInfo pi = new PrincipalInfo(name, role, isAuthenticated);
                    principals.Add(pi);
                }
            }
        }
        /// <summary>
        /// After the page is imported
        /// </summary>
        public void DataImporter_ContentImported(DataImporter dataImported, ContentImportedEventArgs e)
        {
            PageData page = null;

            if (!ContentReference.IsNullOrEmpty(e.ContentLink))
            {
                page = DataFactory.Instance.Get <PageData>(e.ContentLink).CreateWritableClone();
            }

            if (page == null)
            {
                return;
            }

            page["PageSaved"]              = _originalValues.PageSaved;
            page["PageChanged"]            = _originalValues.PageChanged;
            page["PageChangedBy"]          = _originalValues.PageChangedBy;
            page["PageCreatedBy"]          = _originalValues.PageCreatedBy;
            page["PageChangedOnPublish"]   = true;
            PrincipalInfo.CurrentPrincipal = PrincipalInfo.CreatePrincipal(_originalValues.PageChangedBy);
            try {
                global::EPiServer.BaseLibrary.Context.Current["PageSaveDB:PageSaved"] = true;
                DataFactory.Instance.Save(page, SaveAction.ForceCurrentVersion | SaveAction.Publish
                                          | SaveAction.SkipValidation,
                                          AccessLevel.NoAccess);
            }
            finally {
                global::EPiServer.BaseLibrary.Context.Current["PageSaveDB:PageSaved"] = null;
            }

            MigrationHook.Invoke(new AfterPageImportEvent(e), Log);
        }
示例#7
0
        /// <summary>
        /// Gets roles for given principle
        /// </summary>
        /// <param name="principle"></param>
        /// <returns></returns>
        public static IEnumerable <string> GetRoles(this IPrincipal principle)
        {
            if (principle == null)
            {
                throw new ArgumentNullException(nameof(principle));
            }

            var userPrinciple = new PrincipalInfo(principle);
            var list          = new List <string>(userPrinciple.RoleList);

            foreach (string name in _VirtualRoleRepository.Service.GetAllRoles())
            {
                VirtualRoleProviderBase virtualRoleProvider;

                if (_VirtualRoleRepository.Service.TryGetRole(name, out virtualRoleProvider) && virtualRoleProvider.IsInVirtualRole(userPrinciple.Principal, null))
                {
                    list.Add(name);
                }
            }

            if (Roles.Enabled)
            {
                list.AddRange(Roles.GetRolesForUser(userPrinciple.Name));
            }

            return(list.Distinct());
        }
示例#8
0
        private static List <PrincipalInfo> ParallelGetPrincipal(string testUserName, RhetosAppOptions rhetosAppOptions, bool commitChanges)
        {
            var report = new ConcurrentDictionary <int, PrincipalInfo>();

            const int threadCount = 4;

            // Recompute membership on authorization with multiple parallel requests:
            Parallel.For(0, threadCount, thread =>
            {
                using (var scope = TestScope.Create(builder => builder.RegisterInstance(rhetosAppOptions).ExternallyOwned()))
                {
                    var authorizationData = scope.Resolve <AuthorizationDataLoader>();

                    // First call will automatically create a new principal, see AuthorizationAddUnregisteredPrincipals above.
                    // Other calls should return the same principal.
                    PrincipalInfo principal = authorizationData.GetPrincipal(testUserName);
                    report[thread]          = principal;
                    if (commitChanges)
                    {
                        scope.CommitAndClose();
                    }
                }
            });

            Assert.AreEqual(threadCount, report.Count);
            return(report.Values.ToList());
        }
示例#9
0
        private IEnumerable <PrincipalInfo> EnumerateMembershipUsersInRole(string providerName, string roleName)
        {
            List <PrincipalInfo> userInfos = new List <PrincipalInfo>();

            try {
                RoleProvider provider = Roles.Providers[providerName];
                if (provider == null)
                {
                    throw new ConfigurationErrorsException(String.Format("Role provider \"{0}\" not found", providerName));
                }
                foreach (string username in provider.GetUsersInRole(roleName))
                {
                    PrincipalInfo resolvedUser = ResolveMembershipUser(null, username);
                    if (resolvedUser != null)
                    {
                        userInfos.Add(resolvedUser);
                    }
                }
            } catch (PrincipalResolveException) {
                throw;
            } catch (Exception ex) {
                userInfos.Add(ExceptionHandler(new PrincipalResolveException(roleName, ex)));
            }
            return(userInfos);
        }
示例#10
0
 public IEnumerable <PrincipalInfo> Resolve(SPUser user, IDisposable implicitContext)
 {
     try {
         CommonHelper.ConfirmNotNull(user, "user");
         if (!resolvedIdentities.Contains(user.ID))
         {
             resolvedIdentities.Add(user.ID);
             parentPrincipal = user;
             if (SPClaimProviderManager.IsEncodedClaim(user.LoginName))
             {
                 SPClaim claim = SPClaimProviderManager.Local.DecodeClaim(user.LoginName);
                 if (claim.OriginalIssuer == "Windows")
                 {
                     if (claim.ClaimType == SPClaimTypes.UserLogonName)
                     {
                         PrincipalInfo userInfo = ResolveActiveDirectoryUser(IdentityType.SamAccountName, claim.Value);
                         if (userInfo != null)
                         {
                             return(new[] { userInfo });
                         }
                         return(new PrincipalInfo[0]);
                     }
                     if (claim.ClaimType == ClaimTypes_GroupSid)
                     {
                         return(EnumerateActiveDirectoryGroup(IdentityType.SamAccountName, user.Name));
                     }
                 }
                 if (claim.OriginalIssuer.StartsWith("Forms:"))
                 {
                     string providerName = claim.OriginalIssuer.Substring(6);
                     if (claim.ClaimType == SPClaimTypes.UserLogonName)
                     {
                         PrincipalInfo userInfo = ResolveMembershipUser(providerName, claim.Value);
                         if (userInfo != null)
                         {
                             return(new[] { userInfo });
                         }
                         return(new PrincipalInfo[0]);
                     }
                     if (claim.ClaimType == ClaimTypes_Role)
                     {
                         return(EnumerateMembershipUsersInRole(providerName, claim.Value));
                     }
                 }
             }
             if (user.IsDomainGroup)
             {
                 return(EnumerateActiveDirectoryGroup(IdentityType.SamAccountName, user.LoginName));
             }
             return(EnumerateBySamAccountName(user.LoginName));
         }
         return(new PrincipalInfo[0]);
     } finally {
         if (implicitContext != null)
         {
             implicitContext.Dispose();
         }
     }
 }
		// Constructors

		public PrincipalPermission (PermissionState state)
		{
			principals = new ArrayList ();
			if (CodeAccessPermission.CheckPermissionState (state, true) == PermissionState.Unrestricted) {
				PrincipalInfo pi = new PrincipalInfo (null, null, true);
				principals.Add (pi);
			}
		}
示例#12
0
        // Constructors

        public PrincipalPermission(PermissionState state)
        {
            principals = new ArrayList();
            if (CodeAccessPermission.CheckPermissionState(state, true) == PermissionState.Unrestricted)
            {
                PrincipalInfo pi = new PrincipalInfo(null, null, true);
                principals.Add(pi);
            }
        }
示例#13
0
        private void TransformPage(PageData sourcePage, bool clearPropertyValues = true)
        {
            MigrationHook.Invoke(new BeforePageTransformEvent(sourcePage), Logger);

            _currentConvertablePageData.Properties = sourcePage.Property;
            _currentConvertablePageData.TypeName   = sourcePage.PageTypeName;

            var pTRepo         = ServiceLocator.Current.GetInstance <PageTypeRepository>();
            var sourcePageType = pTRepo.Load(sourcePage.PageTypeID);
            var targetPageType = pTRepo.Load(_mapper.GetTargetPageType(sourcePage));

            string result;

            //Convert The Page
            if (clearPropertyValues)
            {
                var keys       = new List <KeyValuePair <int, int> >();
                var properties = sourcePage.Property.Select(p => p.PropertyDefinitionID).Where(p => p > 0);
                foreach (var propertyId in properties)
                {
                    keys.Add(new KeyValuePair <int, int>(propertyId, 0));
                }

                //Convert The Page
                result = PageTypeConverter.Convert(sourcePage.PageLink, sourcePageType, targetPageType,
                                                   keys, false, false, _repo);
            }
            else
            {
                result = PageTypeConverter.Convert(sourcePage.PageLink, sourcePageType, targetPageType,
                                                   new List <KeyValuePair <int, int> >(), false, false, _repo);
            }
            Logger.Log(result);

            var transformedPage = _repo.Get <PageData>(sourcePage.PageLink).CreateWritableClone();

            _mapper.SetPropertyValues(transformedPage, _currentConvertablePageData);

            transformedPage.URLSegment = UrlSegment.GetUrlFriendlySegment(transformedPage.URLSegment);
            var oldPrincipal = PrincipalInfo.CurrentPrincipal;

            try {
                PrincipalInfo.CurrentPrincipal =
                    PrincipalInfo.CreatePrincipal(sourcePage.ChangedBy);
                global::EPiServer.BaseLibrary.Context.Current["PageSaveDB:PageSaved"] = true;
                var savedPage = _repo.Save(transformedPage,
                                           SaveAction.ForceCurrentVersion | SaveAction.Publish | SaveAction.SkipValidation,
                                           AccessLevel.NoAccess);

                MigrationHook.Invoke(new AfterPageTransformEvent(savedPage), Logger);
            }
            finally {
                global::EPiServer.BaseLibrary.Context.Current["PageSaveDB:PageSaved"] = null;
                PrincipalInfo.CurrentPrincipal = oldPrincipal;
            }
        }
示例#14
0
        private IEnumerable <PrincipalInfo> EnumerateBySamAccountName(string samAccountName)
        {
            List <PrincipalInfo> userInfos = new List <PrincipalInfo>();

            string[]         tokens  = samAccountName.Split('\\');
            PrincipalContext context = null;

            try {
                if (tokens.Length == 1)
                {
                    context = PrincipalContextScope.Current.LocalContext;
                }
                else if ("NT AUTHORITY".Equals(tokens[0], StringComparison.OrdinalIgnoreCase) || "SHAREPOINT".Equals(tokens[0], StringComparison.OrdinalIgnoreCase))
                {
                    context = null;
                }
                else
                {
                    context = PrincipalContextScope.Current.GetContextByDomainName(tokens[0]);
                }
            } catch (Exception ex) {
                userInfos.Add(ExceptionHandler(new ADPrincipalResolveException(IdentityType.SamAccountName, samAccountName, ex)));
            }

            if (context != null)
            {
                PrincipalContextScope.Current.EnterContext(context);
                try {
                    Principal principal = Principal.FindByIdentity(context, IdentityType.SamAccountName, tokens.Last());
                    if (principal != null)
                    {
                        using (principal) {
                            if (principal is GroupPrincipal)
                            {
                                userInfos.AddRange(EnumerateActiveDirectoryGroup((GroupPrincipal)principal));
                            }
                            else if (principal is UserPrincipal)
                            {
                                PrincipalInfo userInfo = ResolveActiveDirectoryUser((UserPrincipal)principal);
                                if (userInfo != null)
                                {
                                    userInfos.Add(userInfo);
                                }
                            }
                        }
                    }
                } catch (ADPrincipalResolveException) {
                    throw;
                } catch (Exception ex) {
                    userInfos.Add(ExceptionHandler(new ADPrincipalResolveException(IdentityType.SamAccountName, samAccountName, ex)));
                } finally {
                    PrincipalContextScope.Current.LeaveContext();
                }
            }
            return(userInfos);
        }
示例#15
0
        private static void AddCurrentUserToEpiLogin(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return;
            }

            PrincipalInfo.CurrentPrincipal = PrincipalInfo.CreatePrincipal(userName);
            SetAuthCookie(userName, false);
        }
示例#16
0
        public IPermission Intersect(IPermission target)
        {
            PrincipalPermission pp = Cast(target);

            if (pp == null)
            {
                return(null);
            }

            if (IsUnrestricted())
            {
                return(pp.Copy());
            }
            if (pp.IsUnrestricted())
            {
                return(Copy());
            }

            PrincipalPermission intersect = new PrincipalPermission(PermissionState.None);

            foreach (PrincipalInfo pi in principals)
            {
                foreach (PrincipalInfo opi in pp.principals)
                {
                    if (pi.IsAuthenticated == opi.IsAuthenticated)
                    {
                        string name = null;
                        if ((pi.Name == opi.Name) || (opi.Name == null))
                        {
                            name = pi.Name;
                        }
                        else if (pi.Name == null)
                        {
                            name = opi.Name;
                        }
                        string role = null;
                        if ((pi.Role == opi.Role) || (opi.Role == null))
                        {
                            role = pi.Role;
                        }
                        else if (pi.Role == null)
                        {
                            role = opi.Role;
                        }
                        if ((name != null) || (role != null))
                        {
                            PrincipalInfo ipi = new PrincipalInfo(name, role, pi.IsAuthenticated);
                            intersect.principals.Add(ipi);
                        }
                    }
                }
            }

            return((intersect.principals.Count > 0) ? intersect : null);
        }
示例#17
0
        /// <summary>
        /// Login user to CMS
        /// </summary>
        private void Login()
        {
            if (User.Identity.IsAuthenticated)
            {
                return;
            }

            PrincipalInfo.CurrentPrincipal = PrincipalInfo.CreatePrincipal(UserName);

            if (FormsSettings.IsFormsAuthentication)
            {
                FormsAuthentication.SetAuthCookie(UserName, false);
            }
        }
示例#18
0
        internal SPUserInformation(PrincipalInfo principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            Id       = principal.PrincipalId;
            Name     = principal.DisplayName;
            Login    = principal.LoginName;
            Email    = principal.Email;
            ImageUrl = $"/api/web/users/photo/{Email}/S";//$"https://outlook.office365.com/owa/service.svc/s/GetPersonaPhoto?email={Email}&size=HR64x64";
            Phone    = principal.Mobile;
        }
示例#19
0
        /// <summary>
        /// Provides information about one principal, either a user or a group.
        /// </summary>
        /// <param name="adobeConnectXmlApi">The adobe connect XML API.</param>
        /// <param name="principalId">The principal identifier.</param>
        /// <returns>
        ///   <see cref="PrincipalInfo" />
        /// </returns>
        /// <exception cref="System.ArgumentNullException">principalId</exception>
        public static PrincipalInfoStatus GetPrincipalInfo(this AdobeConnectXmlAPI adobeConnectXmlApi, string principalId)
        {
            if (String.IsNullOrEmpty(principalId))
            {
                throw new ArgumentNullException("principalId");
            }

            ApiStatus s = adobeConnectXmlApi.ProcessApiRequest("principal-info", String.Format("principal-id={0}", principalId));

            var principalInfoStatus = Helpers.WrapBaseStatusInfo <PrincipalInfoStatus>(s);

            if (s.Code != StatusCodes.OK || s.ResultDocument == null)
            {
                return(null);
            }

            var principalInfo = new PrincipalInfo();

            try
            {
                XElement contactData = s.ResultDocument.XPathSelectElement("//contact");

                if (contactData != null)
                {
                    principalInfo.Contact = XmlSerializerHelpersGeneric.FromXML <Contact>(contactData.CreateReader());
                }

                XElement preferencesData = s.ResultDocument.XPathSelectElement("//preferences");

                if (preferencesData != null)
                {
                    principalInfo.Preferences = XmlSerializerHelpersGeneric.FromXML <Preferences>(preferencesData.CreateReader());
                }

                XElement principalData = s.ResultDocument.XPathSelectElement("//principal");

                if (principalData != null)
                {
                    principalInfo.PrincipalData = XmlSerializerHelpersGeneric.FromXML <Principal>(principalData.CreateReader());
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            principalInfoStatus.Result = principalInfo;

            return(principalInfoStatus);
        }
示例#20
0
        /// <summary>
        /// Ladda alla noder med data från filstrukturen
        /// </summary>
        /// <param name="context">Den HttpContext appen körs i</param>
        /// <param name="dirId">GUID för rotkatalogen</param>
        private FileTreeInfo Load(HttpContext context, string dirId)
        {
            //Hämta epi användare.
            var username          = context.User.Identity.Name;
            var epiUser           = PrincipalInfo.CreatePrincipal(username);
            var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>();
            var folder            = contentRepository.Get <ContentFolder>(ContentReference.Parse(dirId));

            var rootNode = new FileTreeInfo
            {
                id       = "root",
                parentId = "",
                name     = "roten",
                size     = 0,
                link     = "",
                type     = "root",
                children = new List <FileTreeInfo>()

                           //folder = true,
                           //folderPath = "",
                           //key = "0",
                           //path = "",
                           //title = "rooten",
            };

            var includedRootNode = new FileTreeInfo
            {
                id       = dirId.ToString(CultureInfo.InvariantCulture),
                type     = "dir",
                name     = folder.Name,
                parentId = rootNode.id,
                size     = 0,
                link     = folder.Name,
                children = new List <FileTreeInfo>()

                           //key = dirId.ToString(CultureInfo.InvariantCulture),
                           //folder = true,
                           //title = folder.Name,
                           //path = folder.Name,
                           //folderPath = folder.Name + "/",
                           //edit = getRightsJson(folder, AccessLevel.Edit),
                           //delete = getRightsJson(folder, AccessLevel.Delete),
                           //contentreference = folder.ContentLink.ToString(),
                           //typeofmedia = "folder",
            };

            rootNode.children.Add(includedRootNode);
            LoadRecursiveFromMedia(folder, includedRootNode, epiUser, dirId);
            return(rootNode);
        }
示例#21
0
        public static PrincipalInfo GetInfo(this ClaimsPrincipal principal)
        {
            if (!principal.Identity.IsAuthenticated)
            {
                throw new NotAuthorizedException("Principal is not authenticated");
            }
            var identity = (ClaimsIdentity)principal.Identity;
            var claims   = identity.Claims.ToList();

            PrincipalInfo result = new PrincipalInfo();

            Set(() => result.Login, claims, "login");
            Set(() => result.CompanyIdentifier, claims, "company");

            return(result);
        }
示例#22
0
        public virtual async Task <IHttpActionResult> PostCmsImport(Guid id)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                _logger.Error(InvalidMediaTypeMessage, Request.CreateResponseException(InvalidMediaTypeMessage, HttpStatusCode.UnsupportedMediaType));
                throw Request.CreateResponseException(InvalidMediaTypeMessage, HttpStatusCode.UnsupportedMediaType);
            }

            var file = await Request.GetUploadedFile(UploadPaths.IntegrationDataPath);

            var destinationRoot = _permanentLinkMapper.Find(id);

            if (destinationRoot == null)
            {
                return(Ok(id));
            }

            var importerOptions = ImportOptions.DefaultOptions;

            importerOptions.KeepIdentity                = true;
            importerOptions.ValidateDestination         = true;
            importerOptions.EnsureContentNameUniqueness = true;
            importerOptions.IsTest = false;
            var importer = _dataImporterAccessor();

            PrincipalInfo.RecreatePrincipalForThreading();
            var state = new ImporterState
            {
                Destination = destinationRoot.ContentReference,
                Importer    = importer,
                Options     = importerOptions,
                Stream      = new FileStream(file.LocalFileName, FileMode.Open)
            };

            var message = await ImportFileThread(state);

            if (string.IsNullOrEmpty(message))
            {
                return(Ok(id));
            }
            else
            {
                throw Request.CreateResponseException(message, HttpStatusCode.InternalServerError);
            }
        }
示例#23
0
        public IPermission Union(IPermission target)
        {
            // Handle the easy cases first.
            if (target == null)
            {
                return(Copy());
            }
            else if (!(target is PrincipalPermission))
            {
                throw new ArgumentException(_("Arg_PermissionMismatch"));
            }
            else if (IsUnrestricted() ||
                     ((PrincipalPermission)target).IsUnrestricted())
            {
                return(new PrincipalPermission
                           (PermissionState.Unrestricted));
            }

            // Form the union of the two lists.
            PrincipalPermission perm =
                new PrincipalPermission(this, true);
            PrincipalInfo other, newPrin;

            foreach (PrincipalInfo prin in ((PrincipalPermission)target)
                     .principals)
            {
                other = perm.Find(prin.name, prin.role);
                if (other == null)
                {
                    newPrin                 = new PrincipalInfo();
                    newPrin.name            = prin.name;
                    newPrin.role            = prin.role;
                    newPrin.isAuthenticated = prin.isAuthenticated;
                    perm.principals.Add(newPrin);
                }
                else
                {
                    other.isAuthenticated =
                        (prin.isAuthenticated || other.isAuthenticated);
                }
            }
            return(perm);
        }
示例#24
0
        private IEnumerable <PrincipalInfo> EnumerateActiveDirectoryGroup(GroupPrincipal group)
        {
            List <PrincipalInfo> userInfos = new List <PrincipalInfo>();

            if (!resolvedIdentities.Contains(group.DistinguishedName))
            {
                resolvedIdentities.Add(group.DistinguishedName);
                try {
                    DirectoryEntry groupEntry = (DirectoryEntry)group.GetUnderlyingObject();
                    foreach (string dn in groupEntry.Properties["member"])
                    {
                        try {
                            DirectoryEntry     memberEntry = new DirectoryEntry("LDAP://" + dn);
                            PropertyCollection userProps   = memberEntry.Properties;
                            object[]           objectClass = (object[])userProps["objectClass"].Value;

                            if (objectClass.Contains("group"))
                            {
                                userInfos.AddRange(EnumerateActiveDirectoryGroup(IdentityType.DistinguishedName, userProps["distinguishedName"].Value.ToString()));
                                continue;
                            }
                            if (objectClass.Contains("foreignSecurityPrincipal"))
                            {
                                userInfos.AddRange(EnumerateForeignSecurityPrincipal(memberEntry));
                                continue;
                            }
                            PrincipalInfo userInfo = ResolveActiveDirectoryUser(IdentityType.DistinguishedName, dn);
                            if (userInfo != null)
                            {
                                userInfos.Add(userInfo);
                            }
                        } catch (Exception ex) {
                            userInfos.Add(ExceptionHandler(new ADPrincipalResolveException(IdentityType.DistinguishedName, dn, ex)));
                        }
                    }
                } catch (ADPrincipalResolveException) {
                    throw;
                } catch (Exception ex) {
                    userInfos.Add(ExceptionHandler(new ADPrincipalResolveException(IdentityType.DistinguishedName, group.DistinguishedName, ex)));
                }
            }
            return(userInfos);
        }
示例#25
0
        public IPermission Intersect(IPermission target)
        {
            // Handle the easy cases first.
            if (target == null)
            {
                return(target);
            }
            else if (!(target is PrincipalPermission))
            {
                throw new ArgumentException(_("Arg_PermissionMismatch"));
            }
            else if (((PrincipalPermission)target).IsUnrestricted())
            {
                if (IsUnrestricted())
                {
                    return(Copy());
                }
            }
            else if (IsUnrestricted())
            {
                return(target.Copy());
            }

            // Form the intersection of the two principal lists.
            PrincipalPermission perm = new PrincipalPermission(this, false);
            PrincipalInfo       other, newPrin;

            foreach (PrincipalInfo prin in principals)
            {
                other = Find(prin.name, prin.role);
                if (other != null)
                {
                    newPrin                 = new PrincipalInfo();
                    newPrin.name            = prin.name;
                    newPrin.role            = prin.role;
                    newPrin.isAuthenticated = prin.isAuthenticated &&
                                              other.isAuthenticated;
                    perm.principals.Add(newPrin);
                }
            }
            return(perm);
        }
示例#26
0
 /// <summary>
 /// Retrieves the full name of a C-Access user.
 /// </summary>
 /// <param name="user">The C-Access user to retrieve.</param>
 /// <returns>The full name on record for C-Access user <paramref name="user"/> otherwise null.</returns>
 public static string GetFullName(MembershipUser user)
 {
     if (user != null)
     {
         string username = ToSPLoginName(user.UserName);
         using (People proxy = new People())
         {
             if (!string.IsNullOrWhiteSpace(SPContentSiteUrl))
             {
                 proxy.Url = SPContentSiteUrl + "/_vti_bin/People.asmx";
             }
             proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
             PrincipalInfo[] matches = proxy.SearchPrincipals(username, 1, SPPrincipalType.User);
             if (matches.Length > 0)
             {
                 PrincipalInfo userPI = matches[0];
                 return(userPI.DisplayName);
             }
         }
     }
     return(null);
 }
	public IPermission Intersect(IPermission target)
			{
				// Handle the easy cases first.
				if(target == null)
				{
					return target;
				}
				else if(!(target is PrincipalPermission))
				{
					throw new ArgumentException(_("Arg_PermissionMismatch"));
				}
				else if(((PrincipalPermission)target).IsUnrestricted())
				{
					if(IsUnrestricted())
					{
						return Copy();
					}
				}
				else if(IsUnrestricted())
				{
					return target.Copy();
				}

				// Form the intersection of the two principal lists.
				PrincipalPermission perm = new PrincipalPermission(this, false);
				PrincipalInfo other, newPrin;
				foreach(PrincipalInfo prin in principals)
				{
					other = Find(prin.name, prin.role);
					if(other != null)
					{
						newPrin = new PrincipalInfo();
						newPrin.name = prin.name;
						newPrin.role = prin.role;
						newPrin.isAuthenticated = prin.isAuthenticated &&
												  other.isAuthenticated;
						perm.principals.Add(newPrin);
					}
				}
				return perm;
			}
示例#28
0
        public void ParallelRequestsTryCreatePrincipal()
        {
            string u1Name           = TestName + "U";
            string r1Name           = TestName + "P";
            string commonTestSuffix = Guid.NewGuid().ToString().Replace("-", "");

            IPrincipal u1Prototype;

            Common.Role      r1;
            RhetosAppOptions rhetosAppOptions;

            using (var scope = TestScope.Create($"{u1Name}-{r1Name}", commonTestSuffix))
            {
                rhetosAppOptions = scope.Resolve <RhetosAppOptions>();

                u1Prototype = scope.NewPrincipal(u1Name);

                var roles = scope.Resolve <GenericRepository <Common.Role> >();
                r1 = scope.NewRole(r1Name);
                roles.Insert(r1);

                scope.CommitAndClose();
            }

            rhetosAppOptions.AuthorizationAddUnregisteredPrincipals = true;

            for (int test = 0; test < 5; test++)
            {
                Console.WriteLine("Test: " + test);

                // Test setup: PrincipalHasRole is deleted to make sure it is not up-to-date.
                // PrincipalHasRole will be recomputed when reading PrincipalHasRole.
                using (var scope = TestScope.Create($"{u1Name}-{r1Name}", commonTestSuffix))
                {
                    var principals = scope.Resolve <GenericRepository <IPrincipal> >();
                    principals.Delete(principals.Load(p => p.Name.Contains(TestName)));

                    var membership = scope.Resolve <GenericRepository <Common.PrincipalHasRole> >();
                    membership.Delete(membership.Load());
                    Assert.AreEqual(@"", scope.ReportMembership(), "Initial empty membership.");
                    AuthorizationDataCache.ClearCache();

                    scope.CommitAndClose();
                }

                // Recompute membership on authorization with multiple parallel requests:
                Parallel.For(0, 4, thread =>
                {
                    using (var scope = TestScope.Create($"{u1Name}-{r1Name}", commonTestSuffix,
                                                        builder => builder.RegisterInstance(rhetosAppOptions).ExternallyOwned()))
                    {
                        var authorizationData     = scope.Resolve <IAuthorizationData>();
                        var authorizationProvider = scope.Resolve <CommonAuthorizationProvider>();

                        PrincipalInfo u1 = authorizationData.GetPrincipal(u1Prototype.Name); // First call will automatically create a new principal, see AuthorizationAddUnregisteredPrincipals above.
                        var userRoles    = authorizationProvider.GetUsersRoles(u1);
                        Assert.AreEqual($@"\{r1Name}", scope.ReportRoles(userRoles), "User's roles should be recomputed.");
                        Assert.AreEqual($@"\{u1Name}-\{r1Name}", scope.ReportMembership(), "Updated role membership");

                        scope.CommitAndClose();
                    }
                });
            }
        }
示例#29
0
 public static void SetPrincipalInfo(this HttpContext context, PrincipalInfo principalInfo)
 {
     context.Items[RequestDataKey.PrincipalInfo] = principalInfo;
 }
示例#30
0
                private void LoadDefaultGroupOwner(string adminGroup)
                {
                   
                    _parentModel.IsBusy = true;
                    _parentModel.IsError = false;

                    _peopleServiceAgent.ResolvePrincipal(adminGroup, (principalInfo, e) =>
                        {
                            _dispatcher.BeginInvoke(new Action(() =>
                            {
                                if (e == null)
                                    _adminGroupInfo = principalInfo;
                                else
                                {
                                    _parentModel.IsError = true;
                                    _parentModel.ErrorMessage = "Resolve User or Group Failed!";
                                }
                                _parentModel.IsBusy = false;
                            }));
                        });

                    
                }
	public IPermission Union(IPermission target)
			{
				// Handle the easy cases first.
				if(target == null)
				{
					return Copy();
				}
				else if(!(target is PrincipalPermission))
				{
					throw new ArgumentException(_("Arg_PermissionMismatch"));
				}
				else if(IsUnrestricted() ||
				        ((PrincipalPermission)target).IsUnrestricted())
				{
					return new PrincipalPermission
						(PermissionState.Unrestricted);
				}

				// Form the union of the two lists.
				PrincipalPermission perm =
					new PrincipalPermission(this, true);
				PrincipalInfo other, newPrin;
				foreach(PrincipalInfo prin in ((PrincipalPermission)target)
													.principals)
				{
					other = perm.Find(prin.name, prin.role);
					if(other == null)
					{
						newPrin = new PrincipalInfo();
						newPrin.name = prin.name;
						newPrin.role = prin.role;
						newPrin.isAuthenticated = prin.isAuthenticated;
						perm.principals.Add(newPrin);
					}
					else
					{
						other.isAuthenticated =
							(prin.isAuthenticated || other.isAuthenticated);
					}
				}
				return perm;
			}
示例#32
0
 /// <summary>
 /// Gets principal from username
 /// </summary>
 /// <param name="username"></param>
 /// <returns></returns>
 public static IPrincipal GetUser(string username) => PrincipalInfo.CreatePrincipal(username);
        public static void AddAclForUser(this AccessControlListQuery query, VirtualRoleRepository <VirtualRoleProviderBase> virtualRoleRepository, PrincipalInfo principal, object context)
        {
            if (principal == null)
            {
                return;
            }
            Validator.ThrowIfNull("virtualRoleRepository", virtualRoleRepository);
            if (!string.IsNullOrEmpty(principal.Name))
            {
                query.AddUser(principal.Name);
            }
            ICollection <string> roleList = principal.RoleList;

            if (roleList != null)
            {
                foreach (string current in roleList)
                {
                    query.AddRole(current);
                }
            }
            foreach (string current2 in virtualRoleRepository.GetAllRoles())
            {
                VirtualRoleProviderBase virtualRoleProviderBase;
                if (virtualRoleRepository.TryGetRole(current2, out virtualRoleProviderBase) && virtualRoleProviderBase.IsInVirtualRole(principal.Principal, context))
                {
                    query.AddRole(current2);
                }
            }
        }
		public PrincipalPermission (string name, string role, bool isAuthenticated)
		{
			principals = new ArrayList ();
			PrincipalInfo pi = new PrincipalInfo (name, role, isAuthenticated);
			principals.Add (pi);
		}
 public static void AddAclForUser(this AccessControlListQuery query, PrincipalInfo principal, object context)
 {
     query.AddAclForUser(VirtualRoleRepository <VirtualRoleProviderBase> .GetDefault(), principal, context);
 }
		public IPermission Intersect (IPermission target) 
		{
			PrincipalPermission pp = Cast (target);
			if (pp == null)
				return null;

			if (IsUnrestricted ())
				return pp.Copy ();
			if (pp.IsUnrestricted ())
				return Copy ();

			PrincipalPermission intersect = new PrincipalPermission (PermissionState.None);
			foreach (PrincipalInfo pi in principals) {
				foreach (PrincipalInfo opi in pp.principals) {
					if (pi.IsAuthenticated == opi.IsAuthenticated) {
						string name = null;
						if ((pi.Name == opi.Name) || (opi.Name == null))
							name = pi.Name;
						else if (pi.Name == null)
							name = opi.Name;
						string role = null;
						if ((pi.Role == opi.Role) || (opi.Role == null))
							role = pi.Role;
						else if (pi.Role == null)
							role = opi.Role;
						if ((name != null) || (role != null)) {
							PrincipalInfo ipi = new PrincipalInfo (name, role, pi.IsAuthenticated);
							intersect.principals.Add (ipi);
						}
					}
				}
			}

			return ((intersect.principals.Count > 0) ? intersect : null);
		}
		public void FromXml (SecurityElement elem) 
		{
			// General validation in CodeAccessPermission
			CheckSecurityElement (elem, "elem", version, version);
			// Note: we do not (yet) care about the return value 
			// as we only accept version 1 (min/max values)

			principals.Clear ();
			// Children is null, not empty, when no child is present
			if (elem.Children != null) {
				foreach (SecurityElement se in elem.Children) {
					if (se.Tag != "Identity")
						throw new ArgumentException ("not IPermission/Identity");
					string name = se.Attribute ("ID");
					string role = se.Attribute ("Role");
					string auth = se.Attribute ("Authenticated");
					bool isAuthenticated = false;
					if (auth != null) {
						try {
							isAuthenticated = Boolean.Parse (auth);
						}
						catch {}
					}
					PrincipalInfo pi = new PrincipalInfo (name, role, isAuthenticated);
					principals.Add (pi);
				}
			}
		}