Esempio n. 1
0
        /// <summary>
        /// Creates <see cref="User"/> instance from name.
        /// </summary>
        /// <param name="name">User name.</param>
        /// <param name="context">Instance of <see cref="DavContext"/>.</param>
        /// <returns>Instance of <see cref="User"/> or <c>null</c> if user is not found.</returns>
        public static User FromName(string name, DavContext context)
        {
            // Calling FindByIdentity on a machine that is not on a domain is
            // very slow (even with new PrincipalContext(ContextType.Machine)).
            // using PrincipalSearcher on a local machine and FindByIdentity on a domain.
            Principal        principal;
            PrincipalContext principalContext = context.GetPrincipalContext();

            try
            {
                if (principalContext.ContextType == ContextType.Machine)
                {
                    // search local machine
                    UserPrincipal principalToSearch = new UserPrincipal(principalContext);
                    principalToSearch.SamAccountName = name;
                    principal = new PrincipalSearcher(principalToSearch).FindOne();
                }
                else
                {
                    // search domain
                    principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, name);
                }
                if ((principal == null) || !(principal is UserPrincipal))
                {
                    return(null);
                }
            }
            catch (PrincipalOperationException)
            {
                //This exception is thrown if user cannot be found.
                return(null);
            }

            return(new User(principal as UserPrincipal, context));
        }
Esempio n. 2
0
        /// <summary>
        /// Creates <see cref="Group"/> or <see cref="User"/> for windows SID.
        /// </summary>
        /// <param name="sid">Windows SID.</param>
        /// <param name="context">Instance of <see cref="DavContext"/>.</param>
        /// <returns>Corresponding <see cref="User"/> or <see cref="Group"/> or <c>null</c> if there's no user
        /// or group which correspond to specified sid.</returns>
        public static IPrincipalAsync GetPrincipalFromSid(string sid, DavContext context)
        {
            using (HostingEnvironment.Impersonate())
            { // This code runs as the application pool user
                Principal pr = Principal.FindByIdentity(context.GetPrincipalContext(), IdentityType.Sid, sid);

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

                return(pr is GroupPrincipal
                           ? (IPrincipalAsync) new Group((GroupPrincipal)pr, context)
                           : new User((UserPrincipal)pr, context));
            }
        }